package com.malk.kabeiyi;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.malk.kabeiyi.service.KabeiyiService;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.common.McException;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.aliwork.YDClient;
import com.malk.service.dingtalk.DDClient;
import com.malk.service.dingtalk.DDClient_Workflow;
import com.malk.utils.UtilDateTime;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class DdTest {


    @Autowired
    private DDClient ddClient;

    @Autowired
    private DDClient_Workflow ddClient_workflow;

    @Autowired
    private KabeiyiService kabeiyiService;

    @Autowired
    private YDClient ydClient;



    @Test
    public void test(){
        LocalDateTime now=LocalDateTime.now();
        Map data=new HashMap();
        data.put("maxResults",10);
        data.put("nextToken",0);
        data.put("statuses", Arrays.asList("COMPLETED"));
        String processCode = "PROC-34A203FD-7EDC-45ED-B081-820250801B44";//1.1、工厂用章流程(除采购营销人事)
//        String processCode = "PROC-AD06D122-828A-40A5-8EDC-94BB246B59D2";

        Map rsp=ddClient_workflow.getInstanceIds(ddClient.getAccessToken(),processCode,
                UtilDateTime.getLocalDateTimeTimeStamp(now.minusDays(120)),UtilDateTime.getLocalDateTimeTimeStamp(now),data);
        List<String> list=(List)rsp.get("list");
        List result=new ArrayList();
        for(String id:list){
            result.add(ddClient_workflow.getProcessInstanceId(ddClient.getAccessToken(),id));
        }
        log.info("result:{}",result);
    }


    @Test
    public void test2(){
        Map map = new HashMap<>();
        map.put("procInstId","gl7nXvi4TLebPjFW2oqmrA05771720664838");
        kabeiyiService.pushProcInstToYD(map);

    }

    @Test
    public void test3(){
        kabeiyiService.testInnerTable();
    }

    @Test
    public void test4(){
        //分层审核
        MDC.put("MDC_KEY_PID","1009");

        List<Map> dataList = (List<Map>) ydClient.queryData(YDParam.builder()
                .formUuid("FORM-89F515967FF94C62A9031F28EF6000B1YV5Q")//问题清单
                .pageNumber(3)
                .pageSize(100)
                .build(), YDConf.FORM_QUERY.retrieve_list).getData();

        for (Map data : dataList) {
            String formInstanceId = UtilMap.getString(data, "formInstanceId");

            Map formData = (Map) data.get("formData");

            String status = UtilMap.getString(formData, "selectField_m0d9pkzx");//整改状态

            if (Strings.isNotBlank(status)){
                Long deadLine = (Long) formData.get("dateField_m061zyev");

                Long date = (Long) formData.get("dateField_m0dbp77k");

                Map updateFormDate = new HashMap();

                if (Objects.isNull(date)){
                    updateFormDate.put("selectField_m0d9pkzx","已超期");
                }else {
                    if (date <= deadLine && !"未超期".equals(status)){
                        updateFormDate.put("selectField_m0d9pkzx","未超期");
                    }
                    if (date > deadLine && !"已超期".equals(status)){
                        updateFormDate.put("selectField_m0d9pkzx","已超期");
                    }
                }

                if (!updateFormDate.keySet().isEmpty()){
                    ydClient.operateData(YDParam.builder()
                            .formInstId(formInstanceId)
                            .updateFormDataJson(JSONObject.toJSONString(updateFormDate))
                            .build(), YDConf.FORM_OPERATION.update);
                }

            }
        }
    }

    @Test
    public void test5(){
        //分层审核
        MDC.put("MDC_KEY_PID","1009");

        List<Map> dataList = (List<Map>) ydClient.queryData(YDParam.builder()
                .formUuid("FORM-F4ED246EADD8427381BC13C4F0FEF7FDYMKJ")//审核任务
                .pageNumber(3)
                .pageSize(100)
                .build(), YDConf.FORM_QUERY.retrieve_list).getData();

        for (Map data : dataList) {
            String formInstanceId = UtilMap.getString(data, "formInstanceId");

            Map formData = (Map) data.get("formData");

            String status = UtilMap.getString(formData, "selectField_m0dbmfxd");//审核状态

            Long deadLine = (Long) formData.get("dateField_m061zye7");

            Long date = (Long) formData.get("dateField_m1hod4tv");

            long nowTime = new Date().getTime();

            //当前时间大于审核截止日期
            if (nowTime > deadLine){
                Map updateFormDate = new HashMap();

                if (Strings.isNotBlank(status)){
                    if (Objects.isNull(date)){
                        updateFormDate.put("selectField_m0dbmfxd","已超期");
                    }else {
                        if (date <= deadLine && !"未超期".equals(status)){
                            updateFormDate.put("selectField_m0dbmfxd","未超期");
                        }
                        if (date > deadLine && !"已超期".equals(status)){
                            updateFormDate.put("selectField_m0dbmfxd","已超期");
                        }
                    }
                }else {
                    updateFormDate.put("selectField_m0dbmfxd","已超期");
                }

                if (!updateFormDate.keySet().isEmpty()){
                    ydClient.operateData(YDParam.builder()
                            .formInstId(formInstanceId)
                            .updateFormDataJson(JSONObject.toJSONString(updateFormDate))
                            .build(), YDConf.FORM_OPERATION.update);
                }
            }


        }
    }

    //批量删除表单所有数据
    @Test
    public void deleteAllData(){
        MDC.put("MDC_KEY_PID","1019");

        DDR_New ddrNew;
        int pageNumber = 1;
        int pageSize = 50;
        String formUuid = "FORM-809458EB6D524CF5AE1A91A3492D8B1BZIMN";
        List<String> errorList = new ArrayList<>();
        do {
            ddrNew = ydClient.queryData(YDParam.builder()
                    .formUuid(formUuid)
                    .pageNumber(pageNumber)
                    .pageSize(pageSize).build(), YDConf.FORM_QUERY.retrieve_search_form_id);

            List<String> list =(List<String>) ddrNew.getData();

            int i=1;
            boolean flag = false;
            while (i<=5 && !flag){
                try {
                    ydClient.operateData(YDParam.builder()
                            .formUuid(formUuid)
                            .asynchronousExecution(false)
                            .formInstanceIdList(list)
                            .build(),YDConf.FORM_OPERATION.delete_batch);
                    flag = true;
                    Thread.sleep(3000);
                }catch (McException e){
                    if (e.getMessage().contains("The request has failed due to a temporary failure of the server.")){
                        log.info("请求失败，尝试次数:{}",i);
                        i++;
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException ex) {
                            throw new RuntimeException(ex);
                        }
                    }else {
                        log.info("删除失败 失败原因:{}" , e.getMessage());
                        errorList.addAll(list);
                        flag = true;
                    }
                }catch (Exception e){
                    log.info("删除失败 失败原因:{}" , e.getMessage());
                    errorList.addAll(list);
                    flag = true;
                }
            }
            if (i>5){
                log.info("删除失败，重试次数过多");
            }

        }while (ddrNew.getTotalCount() > 0);

        log.info("失败列表:{}",errorList);
    }

    @Test
    public void test6(){
        System.out.println("2025-06-13 "+ kabeiyiService.getWeekRange("2025-06-13"));

        System.out.println("2025-06-14 "+ kabeiyiService.getWeekRange("2025-06-14"));
        System.out.println("2025-06-15 "+ kabeiyiService.getWeekRange("2025-06-15"));
        System.out.println("2025-06-16 "+ kabeiyiService.getWeekRange("2025-06-16"));
        System.out.println("2025-06-17 "+ kabeiyiService.getWeekRange("2025-06-17"));
        System.out.println("2025-06-18 "+ kabeiyiService.getWeekRange("2025-06-18"));
        System.out.println("2025-06-19 "+ kabeiyiService.getWeekRange("2025-06-19"));
        System.out.println("2025-06-20 "+ kabeiyiService.getWeekRange("2025-06-20"));

        System.out.println("2025-06-21 "+ kabeiyiService.getWeekRange("2025-06-21"));
    }
}
