package com.malk.huagao.schedule;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.malk.huagao.service.HuaGaoService;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.service.aliwork.YDClient;
import com.malk.utils.UtilDateTime;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @EnableScheduling 开启定时任务 [配置参考McScheduleTask]
 */
@Slf4j
@Configuration
@EnableScheduling
@ConditionalOnProperty(name = {"enable.scheduling"})
public class ScheduleTask {

    @Autowired
    private YDClient ydClient;

    @Autowired
    private HuaGaoService huaGaoService;

    /**
     *
     */
    @Scheduled(cron = "0 5 2 1 * ?")
    public void syncMonths() {
        log.info("考勤同步-月度");
        LocalDateTime startTime = LocalDate.now().minusMonths(1).atTime(LocalTime.MIN);
        LocalDateTime endTime = LocalDate.now().atTime(LocalTime.MIN);
        List<String> time = Arrays.asList(String.valueOf(UtilDateTime.getLocalDateTimeTimeStamp(startTime)), String.valueOf(UtilDateTime.getLocalDateTimeTimeStamp(endTime)));
        try {
            huaGaoService.syncKqData(startTime, endTime);
            compSave(time, "同步成功", "");
        } catch (Exception e) {
            e.printStackTrace();
            compSave(time, "异常", e.getMessage());
        }
    }

    /**
     *
     */
    @Scheduled(cron = "0 0 1 * * 1")
    public void syncWeek() {
        log.info("考勤同步-周度");
        LocalDateTime startTime = LocalDate.now().minusWeeks(1).atTime(LocalTime.MIN);
        LocalDateTime endTime = LocalDate.now().atTime(LocalTime.MIN);
        List<String> time = Arrays.asList(String.valueOf(UtilDateTime.getLocalDateTimeTimeStamp(startTime)), String.valueOf(UtilDateTime.getLocalDateTimeTimeStamp(endTime)));
        try {
            huaGaoService.syncKqData(startTime, endTime);
            compSave(time, "同步成功", "");
        } catch (Exception e) {
            e.printStackTrace();
            compSave(time, "异常", e.getMessage());
        }
    }

    /**
     *
     */
    @Scheduled(cron = "0 35 6 * * ?")
    public void syncDay() {
        log.info("考勤同步-昨天");
        LocalDateTime startTime = LocalDate.now().minusDays(1).atTime(LocalTime.MIN);
        LocalDateTime endTime = LocalDate.now().atTime(LocalTime.MIN);
        List<String> time = Arrays.asList(String.valueOf(UtilDateTime.getLocalDateTimeTimeStamp(startTime)), String.valueOf(UtilDateTime.getLocalDateTimeTimeStamp(endTime)));
        try {
            huaGaoService.syncKqData(startTime, endTime);
            compSave(time, "同步成功", "");
        } catch (Exception e) {
            e.printStackTrace();
            compSave(time, "异常", e.getMessage());
        }
    }

    /**
     *
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    public void sync() {
        MDC.put("MDC_KEY_PID", "1001");

        List<Map> list = (List<Map>) ydClient.queryData(YDParam.builder().formUuid("FORM-0D560B9D8B64464C8C885FE20B7C7C95T4IA").pageSize(1)
                .searchFieldJson(JSONObject.toJSONString(UtilMap.map("selectField_m8nud6t3", "待处理"))).build(), YDConf.FORM_QUERY.retrieve_list).getData();
        log.info("手动同步查询-结果，{}", list.size());
        if (list == null || list.size() < 1) {
            return;
        }
        Map data = list.get(0);
        log.info("{}", data);
        String formInstanceId = String.valueOf(data.get("formInstanceId"));
        processing(formInstanceId);
        Map formData = UtilMap.getMap(data, "formData");
        try {
            List<String> timeList = UtilMap.getList(formData, "cascadeDateField_m8nud6sy");
            LocalDateTime startTime = UtilDateTime.getLocalDateTimeFromTimestamp(Long.parseLong(timeList.get(0)));
            LocalDateTime endTime = UtilDateTime.getLocalDateTimeFromTimestamp(Long.parseLong(timeList.get(1)));
            huaGaoService.syncKqData(startTime, endTime);
            comp(formInstanceId, "同步成功！", "");
        } catch (Exception e) {
            e.printStackTrace();
            comp(formInstanceId, "异常", e.getMessage());
        }
    }

    private void processing(String id) {
        ydClient.operateData(YDParam.builder().formInstanceId(id)
                .updateFormDataJson(JSON.toJSONString(UtilMap.map("selectField_m8nud6t3", "处理中")))
                .build(), YDConf.FORM_OPERATION.update);
    }

    private void comp(String id, String result, String msg) {
        ydClient.operateData(YDParam.builder().formInstanceId(id)
                .updateFormDataJson(JSON.toJSONString(UtilMap.map("selectField_m8nud6t3, textField_m8nud6t9, textareaField_m8nud6tb", "已完成", result, msg)))
                .build(), YDConf.FORM_OPERATION.update);
    }

    private void compSave(List<String> time, String result, String msg) {
        ydClient.operateData(YDParam.builder().formUuid("FORM-0D560B9D8B64464C8C885FE20B7C7C95T4IA")
                .formDataJson(JSON.toJSONString(UtilMap.map("cascadeDateField_m8nud6sy, selectField_m8nud6t3, textField_m8nud6t9, textareaField_m8nud6tb", time, "已完成", result, msg)))
                .build(), YDConf.FORM_OPERATION.create);
    }

    public static void main(String[] args) {
        LocalDateTime startTime1 = LocalDate.now().minusDays(1).atTime(LocalTime.MIN);
        LocalDateTime endTime = LocalDate.now().atTime(LocalTime.MIN);
        long startTime = UtilDateTime.getLocalDateTimeTimeStamp(startTime1);
        //获取所属周（每周六-下周五）
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date = LocalDate.parse("2025-06-24", inputFormatter);
        LocalDate startOfWeek;
        // 获取该周的周六（开始日期）
        startOfWeek = date.with(TemporalAdjusters.previousOrSame(DayOfWeek.SATURDAY));

        // 获取该周的周五（结束日期）
        LocalDate endOfWeek = startOfWeek.plusDays(6);
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("MM.dd");
        String format = startOfWeek.format(outputFormatter);
//        LocalDateTime startTime2= LocalDate.now().minusMonths(1).atTime(LocalTime.MIN);
//        List<String> time= Arrays.asList(String.valueOf(UtilDateTime.getLocalDateTimeTimeStamp(startTime)),String.valueOf(UtilDateTime.getLocalDateTimeTimeStamp(endTime)));
//        LocalDateTime startTime1= LocalDate.now().minusWeeks(1).atTime(LocalTime.MIN);
//        String stTime=UtilDateTime.formatLocal(startTime,UtilDateTime.DATE_TIME_PATTERN);
//        String edTime=UtilDateTime.formatLocal(endTime,UtilDateTime.DATE_TIME_PATTERN);
//        String date = "2025-03-27 00:00:00";
//        Long dateTime= UtilDateTime.getLocalDateTimeTimeStamp(UtilDateTime.parseLocalDateTime(date));

        System.out.println(date);
        System.out.println(startTime);
        System.out.println(startOfWeek);
        System.out.println(endOfWeek);
        System.out.println(format);
//        System.out.println("===="+dateTime);
//
//
//        System.out.println(stTime);
//        System.out.println(edTime);

    }
}