package io.hmit.modules.job.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.hmit.common.utils.ConvertUtils;
import io.hmit.common.utils.HttpRequestUtil;
import io.hmit.modules.appointment.dto.CalendarrDTO;
import io.hmit.modules.appointment.entity.CalendarrEntity;
import io.hmit.modules.appointment.service.CalendarrService;
import io.hmit.modules.job.dto.HolidayJsonDTO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Map;

/**
 * 更新每年的节假日信息（后台Calendar 表中的节假日维护到2030年）
 * @params
 */
@Component("updateCalendar")
public class UpdateHolidayTask implements ITask {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private CalendarrService calendarrService;

    @Override
    public void run(String params) {

        logger.debug("TestTask定时任务正在执行，参数为：{}", params);
        String year = params;
        if ("".equals(params) && StringUtils.isBlank(params)) {
            Calendar calendar = Calendar.getInstance();
            year = String.valueOf(calendar.get(Calendar.YEAR));
        }
        String url = "http://timor.tech/api/holiday/year";
        String jsontest = HttpRequestUtil.sendGet(url, year);
        System.out.println(jsontest);
        String holidayJson = "";
        Map<String, String> map = JSONArray.parseObject(jsontest, Map.class);
        for (Map.Entry entry : map.entrySet()) {
            String key = entry.getKey().toString();
            String value = entry.getValue().toString();
            if (key.contains("type")) {
                System.out.println(key);
                System.out.println(value);
                holidayJson = value;
            }
        }

        Map<String, String> map2 = JSONArray.parseObject(holidayJson, Map.class);

        for (Map.Entry entry : map2.entrySet()) {
            String day = entry.getKey().toString();
            String info = entry.getValue().toString();
            CalendarrEntity calendarr = calendarrService.selectByDay(day);
            //将获取到的节假日json 2023-11-11:{"week":6,"name":"周六","type":1} 转换成实体
            HolidayJsonDTO holidayInfo = JSONObject.parseObject(info, HolidayJsonDTO.class);
            calendarr.setDay(day);
            calendarr.setHoliday(holidayInfo.getType());
            CalendarrDTO calendarrDTO = ConvertUtils.sourceToTarget(calendarr, CalendarrDTO.class);
            calendarrService.update(calendarrDTO);
        }
    }
}