package com.red.circle.other.app.scheduler;

import com.red.circle.component.redis.annotation.TaskCacheLock;
import com.red.circle.other.infra.database.cache.service.other.FamilyCacheService;
import com.red.circle.other.infra.database.rds.service.family.FamilyMemberWeekAwardRecordService;
import com.red.circle.other.infra.database.rds.service.family.FamilyMemberWeekExpService;
import com.red.circle.tool.core.date.LocalDateTimeUtils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 家族榜单初始化（家族周，月榜， 成员周榜）， [ BATTER ] .
 *
 * @author pengshigang on 2021/7/24
 */
@Slf4j
//@Component
@AllArgsConstructor
public class FamilyLeaderboardInitTask {

  private final FamilyCacheService familyCacheService;
  private final FamilyMemberWeekExpService familyMemberWeekExpService;
  private final FamilyMemberWeekAwardRecordService familyMemberWeekAwardRecordService;

  /**
   * 初始化周榜单数
   */
  @Scheduled(cron = "0 0 0 ? * MON", zone = "Asia/Riyadh")
  @TaskCacheLock(key = "FAMILY_WEEK_LEADERBOARD_INIT", expireSecond = 10800)
  public void familyWeekLeaderboardInit() {
    long startTime = System.currentTimeMillis();
    log.info("exec family_week_leaderboard_init start");
    log.warn("[execute] familyWeekLeaderboardInit== start:{}",
        LocalDateTimeUtils.nowFormat("yyyy-MM-dd"));
    familyMemberWeekExpService.delete().execute();
    familyMemberWeekAwardRecordService.delete().execute();
    familyCacheService.setFamilyWeekRewardTime(getWeekStartEndDate());
    log.warn("[execute] familyWeekLeaderboardInit== end:{}",
        LocalDateTimeUtils.nowFormat("yyyy-MM-dd"));
    log.info("exec family_week_leaderboard_init end with {}",System.currentTimeMillis()-startTime);
  }

  /**
   * 获取当前时间所在一周的周一和周日时间
   *
   * @return 周一 + / + 周日
   */
  public String getWeekStartEndDate() {

    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");

    Calendar cal = Calendar.getInstance();
    // 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
    cal.setFirstDayOfWeek(Calendar.MONDAY);
    // 获得当前日期是一个星期的第几天
    int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
    if (dayWeek == 1) {
      dayWeek = 8;
    }

    // 根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
    cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - dayWeek);
    Date mondayDate = cal.getTime();
    String weekBegin = sdf.format(mondayDate);

    cal.add(Calendar.DATE, 4 + cal.getFirstDayOfWeek());
    Date sundayDate = cal.getTime();
    String weekEnd = sdf.format(sundayDate);

    return weekBegin + " / " + weekEnd;
  }

}
