package com.red.circle.scheduling.job.family;

import com.red.circle.other.inner.endpoint.family.FamilyMemberWeekAwardClient;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.elasticjob.api.ShardingContext;
import org.apache.shardingsphere.elasticjob.simple.job.SimpleJob;
import org.springframework.stereotype.Component;

/**
 * 初始化周榜单数.
 *
 * @author pengliang on 2023/11/16
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class FamilyWeekLeaderboardInitTask implements SimpleJob {

  private final FamilyMemberWeekAwardClient familyMemberWeekAwardClient;

  @Override
  public void execute(ShardingContext shardingContext) {
    familyMemberWeekAwardClient.deleteAllWeekActivity();
    familyMemberWeekAwardClient.setFamilyWeekRewardTime(getWeekStartEndDate());
  }

  /**
   * 获取当前时间所在一周的周一和周日时间
   *
   * @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;
  }

}
