package com.malk.kuaikeli.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.malk.kuaikeli.entity.SupplierMaterial;
import com.malk.kuaikeli.listener.SupplierMaterialDataListener;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.common.McException;
import com.malk.server.common.McR;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.aliwork.YDClient;
import com.malk.service.aliwork.YDService;
import com.malk.service.dingtalk.DDClient;
import com.malk.utils.UtilHttp;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/test")
public class CdTestController {

    @Autowired
    private DDClient ddClient;
    @Autowired
    private YDClient ydClient;
    @Value("${server.port}")
    private String port;

    @GetMapping("/hello")
    public McR hello(){
        return McR.success("Hello "+ port);
    }

    @GetMapping("/dd")
    public McR dd(){
        return McR.success(ddClient.getAccessToken());
    }

    @PostMapping("/upload")
    public McR upload(MultipartFile file) throws IOException {
        System.out.println("2222222222222222");

        return McR.success();
    }

    @PostMapping("/test")
    public McR test(@RequestBody Map param){
        // FINST-J7666B91556KOPSCBKY425M8C73I3GCT10VULEQ1
        String id= UtilMap.getString(param,"id");
        Object obj= ydClient.queryData(YDParam.builder().searchCondition(
                JSONObject.toJSONString(UtilMap.map("textField_llkb7kd2",""))).build(), YDConf.FORM_QUERY.retrieve_id).getData();

        return McR.success();
    }

    //项目档案、项目信息刷新版本
    @GetMapping("/updateDept")
    public McR updateDept(){

        List<Map> datas = getYdFormDataList("FORM-B1ADCDCD7E81420193A9B82B64C45EB3ZQRN", "", YDConf.FORM_QUERY.retrieve_list);

        /*DDR_New ddrNew = ydClient.queryData(YDParam.builder()
                .formUuid("FORM-MP966K81PGGD51ZUEU29Q6YVKSOE3SDK29KLL9")
                .build(), YDConf.FORM_QUERY.retrieve_list);

        List<Map> datas = (List<Map>) ddrNew.getData();*/



        for (Map data : datas) {
            Map originator = (Map) data.get("originator");
            String userId = originator.get("userId").toString();
            String formInstId = data.get("formInstanceId").toString();
            //根据userId获取部门id
            Map params = UtilMap.map("access_token", ddClient.getAccessToken());
            Map body = UtilMap.map("userid", userId);
            DDR_New deptDDR = (DDR_New) UtilHttp.doPost("https://oapi.dingtalk.com/topapi/v2/department/listparentbyuser", null, params, body, DDR_New.class);

            //已离职人员处理
            if (Objects.isNull(deptDDR.getResult())){
                continue;
            }
            Map result = (Map) deptDDR.getResult();
            List<Map> parentList = (List<Map>) result.get("parent_list");
            if (!parentList.isEmpty()){
                List<Integer> parentDeptIdList = (List<Integer>) parentList.get(0).get("parent_dept_id_list");
                String deptId = parentDeptIdList.get(0) + "";

                Map updateFormData = new HashMap<>();
                updateFormData.put("departmentSelectField_m4xiv4p2", new String[]{deptId});
                ydClient.operateData(YDParam.builder()
                        .formInstId(formInstId)
                        .updateFormDataJson(JSONObject.toJSONString(updateFormData))
                        .useLatestVersion(true)
                        .build(),YDConf.FORM_OPERATION.update);
            }
        }

        return McR.success();
    }

    //todo 其余表单刷新版本
    @GetMapping("/updateDept2")
    public McR updateDept2(){

        String[] projectCodes = {"XM-20241012-109","XM-20241012-107","XM-20240909-105","XM-20240906-103","XM-20240905-101","XM-20240905-097","XM-20240905-095","XM-20240905-093","XM-20240905-092","XM-20240905-091","XM-20240905-087","XM-20240905-086","XM-20240905-085","XM-20240905-081","XM-20240905-079","XM-20240905-077","XM-20240905-075","XM-20240905-073","XM-20240905-071","XM-20240905-069","XM-20240905-067","XM-20240905-065","XM-20240905-063","XM-20240905-062","XM-20240905-061","XM-20240905-057","XM-20240905-056","XM-20240905-055","XM-20240905-054","XM-20240905-049","XM-20240905-047","XM-20240905-045","XM-20240905-043","XM-20240905-041","XM-20240905-039","XM-20240905-037","XM-20240905-035","XM-20240905-033","XM-20240902-030","XM-20240712-028","XM-20240708-026","XM-20240621-020"};

        String[] deptIds = {"979212547","979216577","979501086","979620048","978926758","979126624","979303506","979432119","979494169","979513084","979456147","979427125","979448150","978917851","979376407","979215562","978932775","979469131","979179580","979184553","979288509","979438115","979183507","979297492","979539101","979310511","979558118","979020693","979393470","979114698","979486138","979535109","979186510","979293403","979370427","979297523","979286439","979596136","979592110","979512152","979304440","979342530"};

        List<Map> datas = getYdFormDataList("FORM-AB6CD19F32774DDD9D8F102BFD202963GGZV", "", YDConf.FORM_QUERY.retrieve_list);

        int maxAttempts = 5; // 尝试的最大次数
        int attempt = 0;

        for (Map data : datas) {
            boolean success = false;
            attempt = 0; // 重置当前迭代的尝试次数

            String formInstId = data.get("formInstanceId").toString();
            Map formData = (Map) data.get("formData");
            //项目编号
            String projectCode = formData.get("textField_lluhtqlx").toString();

            //根据项目编号获取部门id
            String deptId = "";
            for (int i = 0; i < projectCodes.length; i++) {
                if (projectCode.equals(projectCodes[i])) {
                    deptId = deptIds[i];
                    break;
                }
            }

             Map updateFormData = new HashMap<>();
             updateFormData.put("departmentSelectField_m4xiv4p2", new String[]{deptId});

            while (!success && attempt < maxAttempts){
                try {
                    ydClient.operateData(YDParam.builder()
                            .formInstId(formInstId)
                            .updateFormDataJson(JSONObject.toJSONString(updateFormData))
                            .useLatestVersion(true)
                            .build(),YDConf.FORM_OPERATION.update);
                    success = true;
                }catch (McException e){
                    if (e.getMessage().equals("The request has failed due to a temporary failure of the server.")){
                        attempt++;
                        // 线程睡眠3秒
                        try {
                            Thread.sleep(3000);
                            log.info("尝试第{}次，formInstanceId:{},异常信息:{}", attempt, formInstId, e.getMessage());
                        } catch (InterruptedException ie) {
                            Thread.currentThread().interrupt(); // 重新设置中断状态
                            System.err.println("Sleep interrupted: " + ie.getMessage());
                        }
                    }
                }catch (Exception e){
                    log.error("更新失败，formInstanceId:{},异常信息:{}", formInstId, e.getMessage());
                    success = true;
                }
            }


        }

        return McR.success();
    }


    private List<Map> getYdFormDataList(String formUuid, String searchCondition, YDConf.FORM_QUERY formQuery) {
        List<Map> list = new ArrayList<>();
        DDR_New ddrNew = new DDR_New();
        int pageNumber = 1;
        int pageSize = 100;
        do {
            ddrNew = ydClient.queryData(YDParam.builder().formUuid(formUuid)
                    .searchCondition(searchCondition)
                    .pageNumber(pageNumber)
                    .pageSize(pageSize).build(), formQuery);

            list.addAll((List<Map>) ddrNew.getData());
            pageNumber++;
        }while (ddrNew.getTotalCount() > ddrNew.getPageNumber() * pageSize);
        return list;
    }
}
