package com.xiang.xservice.common.schedule;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.xiang.xmc.service.cache.service.IRedisService;
import com.xiang.xservice.basic.utils.DateUtils;
import com.xiang.xservice.basic.utils.HttpUtils;
import com.xiang.xservice.common.entity.DayResult;
import com.xiang.xservice.common.enums.RedisConstant;
import com.xiang.xservice.common.enums.UrlConstant;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.YearMonth;
import java.util.HashMap;
import java.util.Objects;

/**
 * @Author: xiang
 * @Date: 2025-10-04 10:09
 */
@Component
@RequiredArgsConstructor
@RestController
public class HolidayQueryJob {

    private final IRedisService redisService;

    private static final String API_KEY = "d20db0ca13e151ca7323d849d8efc6db";

    @Scheduled(cron = "0 0 0 1 1/1 ?")
    @PostMapping("/queryHolidayInfoJob")
    public void queryHolidayInfoJob() {
        YearMonth now = YearMonth.now(); // 当前年月
        LocalDate start = now.atDay(1);
        LocalDate end = now.atEndOfMonth();

        for (LocalDate d = start; !d.isAfter(end); d = d.plusDays(1)) {
            try {
                String date = DateUtils.getDateFromDate(d);
                HashMap<String, String> paramMap = Maps.newHashMap();
                paramMap.put("key", API_KEY);
                paramMap.put("date", date);
                paramMap.put("detail", "");
                HashMap<String, String> headers = Maps.newHashMap();
                headers.put("Content-Type", "application/x-www-form-urlencoded");
                String resp = HttpUtils.doGet(UrlConstant.HOLIDAY_QUERY_URL, headers, paramMap);
                if (StringUtils.isNotBlank(resp)) {
                    JSONObject jsonObject = JSON.parseObject(resp);
                    String reason = (String) jsonObject.get("reason");
                    if (!StringUtils.equals(reason, "success")) {
                        continue;
                    }
                    JSONObject result = jsonObject.getJSONObject("result");
                    DayResult dayResult = JSON.toJavaObject(result, DayResult.class);
                    if (Objects.isNull(dayResult)) {
                        continue;
                    }
                    redisService.hSet(RedisConstant.DAY_INFO_PREFIX_KEY + RedisConstant.getDate4Key(), date, result);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
