package com.malk.luyi.controller;


import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.aliwork.YDClient;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
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.*;
import java.time.temporal.ChronoUnit;
import java.util.*;

@Slf4j
@Configuration
@EnableScheduling
public class KSJC_timer {
    @Autowired
    private KSJCController legalEntityService;
    @Autowired
    private YDClient ydClient;


    /*集晨判断是否能打卡*/
    //每天早晨7点05分同步数据
    @Scheduled(cron = "0 5 7 * * ?")
    // @Scheduled(fixedRate = 500)
    public void LegalEntityList() {
        if (true) {
            log.info("k");
            System.out.println("考勤判断开始同步");
            try {
                legalEntityService.insetTHXM_TMER();
                System.out.println("集晨考勤判断，同步完成");
            } catch (Exception e) {
                //记录错误信息
                e.printStackTrace();
            }
        }
    }

    /**
     * 每天8点半  根据项目给项目人员发送待办
     */
   @Scheduled(cron = "0 30 8 * * ?")
     //@Scheduled(fixedRate = 100)
    public void create_DB() {
        if (true) {
            System.out.println("开始根据项目给项目人员发送待办");
            try {
                legalEntityService.create_DB();
                System.out.println("根据项目给项目人员发送待办，同步完成");
            } catch (Exception e) {
                //记录错误信息
                e.printStackTrace();
            }
        }
    }


    /**
     * 每小时累计异常工时和正常工时
     */
    @Scheduled(fixedRate = 1000 * 60 * 60)
    public void updatiemr() {
        if (true){

        System.out.println("同步判断异常数据区间");
        try {
            LocalDateTime currentTime = LocalDateTime.now();
            // 获取小时数（24小时制）
            int hour = currentTime.getHour();
            if (hour == 20 || hour == 21 || hour == 22 || hour == 23 || hour == 24 || hour == 0 || hour == 1 || hour == 2 || hour == 3 || hour == 4 || hour == 5 || hour == 6 || hour == 7) {
                // List<Map> searchCondition = Arrays.asList(YDConf.searchCondition_TextFiled("textField_m4v6nphm", "进行中", "eq"));
                List<Map> dataList_bgxx = (List<Map>) ydClient.queryData(YDParam.builder()
                        .appType("APP_X89Y00KKTG36B8JYGZVR")
                        .systemToken("QIA66091HJPLRHM3AUFJLCN24CUP2VNMO41XLW4")
                        .formUuid("FORM-C3B8A99E31FD42AC8AFFE0343A6A3CF3LUH7")
                        .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_m4v6nphm", "进行中")))
                        .build(), YDConf.FORM_QUERY.retrieve_search_form).getData();

                if (dataList_bgxx != null && dataList_bgxx.size() > 0) {
                    for (int i = 0; i < dataList_bgxx.size(); i++) {
                        try {
                            Map map = new HashMap<>();
                            map = dataList_bgxx.get(i);
                            if (map != null) {
                                String formInstanceId = (String) map.get("formInstanceId");
                                Map formData = (Map) JSON.parse(String.valueOf(map.get("formData")));
                                int pd = (int) formData.get("numberField_m4rt0yry");
                                int yy = (int) formData.get("numberField_m4v7v0ou");
                                ydClient.operateData(YDParam.builder()
                                        .appType("APP_X89Y00KKTG36B8JYGZVR")
                                        .systemToken("QIA66091HJPLRHM3AUFJLCN24CUP2VNMO41XLW4")
                                        .formInstanceId(String.valueOf(formInstanceId))
                                        .updateFormDataJson(JSON.toJSONString(UtilMap.map("numberField_m4rt0yry", pd + 1)))
                                        .build(), YDConf.FORM_OPERATION.update);
                            }
                        } catch (Exception e) {

                        }


                    }
                }

            }
            if (true) {

                // List<Map> searchCondition = Arrays.asList(YDConf.searchCondition_TextFiled("textField_m4v6nphm", "进行中", "eq"));
                List<Map> dataList_bgxx = (List<Map>) ydClient.queryData(YDParam.builder()
                        .appType("APP_X89Y00KKTG36B8JYGZVR")
                        .systemToken("QIA66091HJPLRHM3AUFJLCN24CUP2VNMO41XLW4")
                        .formUuid("FORM-C3B8A99E31FD42AC8AFFE0343A6A3CF3LUH7")
                        .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_m4v6nphm", "进行中")))
                        .build(), YDConf.FORM_QUERY.retrieve_search_form).getData();
                if (dataList_bgxx != null && dataList_bgxx.size() > 0) {
                    for (int i = 0; i < dataList_bgxx.size(); i++) {
                        try {
                            Map map = new HashMap<>();
                            map = dataList_bgxx.get(i);
                            if (map != null) {
                                String formInstanceId = (String) map.get("formInstanceId");
                                Map formData = (Map) JSON.parse(String.valueOf(map.get("formData")));
                                int yy = (int) formData.get("numberField_m4v7v0ou");
                                ydClient.operateData(YDParam.builder()
                                        .appType("APP_X89Y00KKTG36B8JYGZVR")
                                        .systemToken("QIA66091HJPLRHM3AUFJLCN24CUP2VNMO41XLW4")
                                        .formInstanceId(String.valueOf(formInstanceId))
                                        .updateFormDataJson(JSON.toJSONString(UtilMap.map("numberField_m4v7v0ou", yy + 1)))
                                        .build(), YDConf.FORM_OPERATION.update);
                            }
                        } catch (Exception e) {

                        }
                    }
                }
            }
            System.out.println("同步判断异常数据区间结束");
        } catch (Exception e) {
            //记录错误信息
            e.printStackTrace();
        }
        }
    }

    /**
     * 每天8点更改项目进度天数
     */
  @Scheduled(cron = "0 0 8 * * ?")
    //@Scheduled(fixedRate = 1000)
    public void updateGS_day() {
      if (true) {
          log.info("k");
          System.out.println("开始--同步更改项目进度天数");
          try {
              long currentTimestamp = System.currentTimeMillis();//当前时间戳
              List<Map> dataList_bgxx = (List<Map>) ydClient.queryData(YDParam.builder()
                      .appType("APP_X89Y00KKTG36B8JYGZVR")
                      .systemToken("QIA66091HJPLRHM3AUFJLCN24CUP2VNMO41XLW4")
                      .formUuid("FORM-0DA535E7D9564265B9A85A503AF0041EN39H")
                      .build(), YDConf.FORM_QUERY.retrieve_search_form).getData();
              if (dataList_bgxx != null && dataList_bgxx.size() > 0) {
                  for (int i = 0; i < dataList_bgxx.size(); i++) {
                      try {
                          Map map = new HashMap<>();
                          map = dataList_bgxx.get(i);
                          if (map != null) {
                              String formInstanceId = (String) map.get("formInstanceId");
                              Map formData = (Map) JSON.parse(String.valueOf(map.get("formData")));
                              Long XMCJSJ = (Long) formData.get("dateField_m2a4epem");
                              Long SJXBOM = (Long) formData.get("dateField_m2a4o7j8");
                              Long DQXBOM = (Long) formData.get("dateField_m2bmqgdf");
                              Long WLRK = (Long) formData.get("dateField_m2a4o7ja");
                              Long ZZQRWC = (Long) formData.get("dateField_m2a4o7j9");
                              Long PJWC = (Long) formData.get("dateField_m2a4o7jb");
                              Long XCDW = (Long) formData.get("dateField_m2a4o7je");
                              Long YSWC = (Long) formData.get("dateField_m2a4o7jd");
                              int numberField_m4v8pnva = 0;
                              int numberField_m4v8pnvb = 0;
                              int numberField_m4v8pnvc = 0;
                              int numberField_m2a4o7jm = 0;
                              int numberField_m2bb9qyh = 0;
                              int numberField_m2bb9qyi = 0;

                              if (XMCJSJ != null && SJXBOM != null) {
                                  numberField_m4v8pnva = (int) getDys(XMCJSJ, SJXBOM);
                              } else if (XMCJSJ != null && SJXBOM == null) {
                                  numberField_m4v8pnva = (int) getDys(XMCJSJ, currentTimestamp);
                              }
                              if (WLRK != null && SJXBOM != null) {
                                  numberField_m4v8pnvb = (int) getDys(SJXBOM, WLRK);
                              } else if (WLRK == null && SJXBOM != null) {
                                  numberField_m4v8pnvb = (int) getDys(SJXBOM, currentTimestamp);
                              }
                              if (ZZQRWC != null && WLRK != null) {
                                  numberField_m4v8pnvc = (int) getDys(WLRK, ZZQRWC);
                                  numberField_m2a4o7jm = (int) getDys(WLRK, ZZQRWC);
                              } else if (ZZQRWC == null && WLRK != null) {
                                  numberField_m4v8pnvc = (int) getDys(WLRK, currentTimestamp);
                                  numberField_m2a4o7jm = (int) getDys(WLRK, currentTimestamp);
                              }
                              if (PJWC != null && ZZQRWC != null) {
                                  numberField_m2bb9qyh = (int) getDys(ZZQRWC, PJWC);
                              } else if (PJWC == null && ZZQRWC != null) {
                                  numberField_m2bb9qyh = (int) getDys(ZZQRWC, currentTimestamp);
                              }
                              if (YSWC != null && XCDW != null) {
                                  numberField_m2bb9qyh = (int) getDys(XCDW, YSWC);
                              } else if (YSWC == null && XCDW != null) {
                                  numberField_m2bb9qyh = (int) getDys(XCDW, currentTimestamp);
                              }
                              ydClient.operateData(YDParam.builder()
                                      .appType("APP_X89Y00KKTG36B8JYGZVR")
                                      .systemToken("QIA66091HJPLRHM3AUFJLCN24CUP2VNMO41XLW4")
                                      .formInstanceId(String.valueOf(formInstanceId))
                                      .updateFormDataJson(JSON.toJSONString(UtilMap.map("numberField_m4v8pnva, numberField_m4v8pnvb, numberField_m4v8pnvc, numberField_m2a4o7jm, numberField_m2bb9qyh, numberField_m2bb9qyi", numberField_m4v8pnva, numberField_m4v8pnvb, numberField_m4v8pnvc, numberField_m2a4o7jm, numberField_m2bb9qyh, numberField_m2bb9qyi)))
                                      .build(), YDConf.FORM_OPERATION.update);
                          }
                      } catch (Exception e) {

                      }


                  }
              }

              System.out.println("同步更改项目进度天数---结束");
          } catch (Exception e) {
              //记录错误信息
              e.printStackTrace();
          }
      }
    }










    /**
     * 计算两个时间段的差值天数
     * @param timestamp1
     * @param timestamp2
     * @return
     */
    public long getDys(long timestamp1, long timestamp2) {


        // 将时间戳转换为Instant对象
        Instant instant1 = Instant.ofEpochMilli(timestamp1);
        Instant instant2 = Instant.ofEpochMilli(timestamp2);

        // 将Instant对象转换为LocalDate对象（需要指定时区）
        // 这里使用UTC时区，因为时间戳通常是基于UTC的
        LocalDate date1 = instant1.atZone(ZoneId.of("UTC")).toLocalDate();
        LocalDate date2 = instant2.atZone(ZoneId.of("UTC")).toLocalDate();

        // 计算天数差值
        long daysBetween = ChronoUnit.DAYS.between(date1, date2);
        return daysBetween + 1;
    }


    //    @Scheduled(cron = "0 5 7 * * ?")
//    public void LegalEntityList1(){
//        log.info("k");
//        try{
//            System.out.println("开始同步项目数据");
//            legalEntityService.insetTHXM_TMER1();
//            System.out.println("集晨判断，同步完成");
//        }catch (Exception e){
//            //记录错误信息
//            e.printStackTrace();
//        }
//
//    }

}
