package com.malk.mc;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.malk.core.McProject;
import com.malk.mc.service.McYdService;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.aliwork.YDSearch;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.aliwork.YDClient;
import com.malk.service.aliwork.YDService;
import com.malk.utils.PublicUtil;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
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 javax.rmi.CORBA.Util;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.stream.Collectors;

/***
 * 逸耀宜搭
 */
@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class YyYdTest {

    @Autowired
    private YDClient ydClient;
    @Autowired
    private YDService ydService;

    @Autowired
    private McYdService mcYdService;

    private static String FORM_UUID="FORM-E83C9E307FFB4A978E0CB8DE1B899E9DXTXB";

    @Test
    public void ad(){
        McProject.addYida("2001",new String[]{"APP_JKO9PRYX6FK5KB9N56MM","FRB66P61QBNGH6BZ7YK9P9AQUZ4W1ZW9C3ZPLQQL"});
        MDC.put("MDC_KEY_PID","2001");
        Object obj=ydClient.queryData(YDParam.builder().formInstanceId("95bab7fb-5957-4a8c-9f82-b5b79de0844c").build(), YDConf.FORM_QUERY.retrieve_id);
        System.out.println(JSONObject.toJSONString(obj));
    }

    @Test
    public void tt(){
        // 人员名称修改后刷新历史数据
        MDC.put("MDC_KEY_PID","1001");
        List<Map> list = ydService.queryFormData_all(YDParam.builder().formUuid("FORM-FDB285F000E549A192A15525579EFE33SVKI").build());
        int i=1;
        for (Map map:list){
            log.info("进度:{}/{}",i,list.size());
            ydClient.operateData(YDParam.builder().formInstanceId(String.valueOf(map.get("formInstanceId")))
                    .updateFormDataJson(JSONObject.toJSONString(UtilMap.map("employeeField_lxjrgss7",map.get("employeeField_lxjrgss7_id")))).build(), YDConf.FORM_OPERATION.update);
            i++;
        }
    }

    @Test
    public void test2(){
        MDC.put("MDC_KEY_PID","1013");
//        List<String> ids= FileUtil.readUtf8Lines("/home/ids.txt");
        List<Map> list=ydService.queryAllFormData(YDParam.builder().formUuid("FORM-E83C9E307FFB4A978E0CB8DE1B899E9DXTXB")
                .searchFieldJson(JSONObject.toJSONString(UtilMap.map("textField_lu9l6otz","202210147"))).build());
        for (int i = 0; i < list.size();) {
            log.info("进度:{}/{}",i,list.size());
            String id=UtilMap.getString(list.get(i),"formInstanceId");
            Map formData=UtilMap.getMap(list.get(i),"formData");
            try {
                String no="";
                if(!PublicUtil.isNull(formData,"textField_lu9l6otz")){
                    no=UtilMap.getString(formData,"textField_lu9l6otz");
                    System.out.println("销售"+ no);
                }else if(!PublicUtil.isNull(formData,"textField_lvbu33zk")){
                    no=UtilMap.getString(formData,"textField_lvbu33zk");
                    System.out.println("维保"+no);
                }else if(!PublicUtil.isNull(formData,"textField_lwu3ucd5")){
                    no=UtilMap.getString(formData,"textField_lwu3ucd5");
                    System.out.println("采购"+no);
                }else{
                    System.out.println("其他");
                }
                Map map=new HashMap();
                if(!no.equals("")){
                    List<Map>  tab1MapList=new ArrayList<>();
                    List<Map>  tab2MapList=new ArrayList<>();
                    List<Map> tab1=ydService.queryFormData_all(YDParam.builder().formUuid("FORM-6EB79C0C67984EF2A0857D167B2883A9K4JL").searchFieldJson(JSONObject.toJSONString(UtilMap.map("textField_lu9l6otz",no))).build());
                    for (Map data:tab1){
                        Map tabmap=new HashMap();
                        tabmap.put("selectField_lw5rauoi", UtilMap.getString(data,"textField_lv0mf6ey")); // 软著产品
                        tabmap.put("numberField_lw60trpm",UtilMap.getString(data,"numberField_m4y162c9")); // 金额
                        tabmap.put("textField_lwkdqole",UtilMap.getString(data,"textField_lv0mf6ey")+""+UtilMap.getString(data,"numberField_m4y162c9"));
                        tabmap.put("textField_lw5rhd9n",IdUtil.simpleUUID());
                        tab1MapList.add(tabmap);
                    }
                    List<Map> tab2=ydService.queryFormData_all(YDParam.builder().formUuid("FORM-B2149CDBA96C437ABD0BBF430B2E2204XDCY").searchFieldJson(JSONObject.toJSONString(UtilMap.map("textField_lu9l6otz",no))).build());
                    for (Map data:tab2){
                        Map tabmap=new HashMap();
                        tabmap.put("selectField_ltdyaj0y",UtilMap.getString(data,"selectField_ltdyaj0y")); // 产品模块名称
                        tabmap.put("textField_lu2hd406",UtilMap.getString(data,"textField_lv0mf6ey")); // 产品编码
                        tabmap.put("numberField_lw8oxeid",UtilMap.getString(data,"numberField_m4zg4614"));
                        tabmap.put("numberField_lual03ls",UtilMap.getString(data,"numberField_lual03ls"));
                        tabmap.put("associationFormField_lu2hd407", JSON.parse(UtilMap.getString(data,"associationFormField_lu2hd407")));
                        tabmap.put("numberField_ltdyaj0z",UtilMap.getString(data,"numberField_ltdyaj0z"));
                        tabmap.put("numberField_lub0gska",UtilMap.getString(data,"numberField_lub0gska"));
                        tabmap.put("textField_lw8ogxzj",UtilMap.getString(data,"textField_lw8ogxzj"));
                        tabmap.put("numberField_lual03lt",UtilMap.getString(data,"numberField_ltdyaj10"));// 合计
//                        tabmap.put("numberField_lual03lt",data.get("numberField_m4zi7vib"));// 指导价合计
                        tabmap.put("textField_lu0x7jsx",UtilMap.getString(data,"textField_m5ug9229"));
                        tab2MapList.add(tabmap);
                    }
                    if(tab1MapList.size()>0){
                        map.put("tableField_lw5rauof",tab1MapList);
                    }
                    if(tab2MapList.size()>0){
                        map.put("tableField_ltdyaj0x",tab2MapList);
                    }
                }
                log.info("up:{}",map);
                ydClient.operateData(YDParam.builder()
                        .formInstId(id)
                        .useLatestVersion(true)
                        .updateFormDataJson(JSONObject.toJSONString(map)).build(), YDConf.FORM_OPERATION.update);
            }catch (Exception e){
                e.printStackTrace();
                log.info("重试{}",i);
                continue;
            }
            i++;
        }

    }

    /***
     * 变更次数统计并生成excel展示数据
     * @throws InterruptedException
     */
    @Test
    public void test() throws InterruptedException {
        MDC.put("MDC_KEY_PID","1013");
        List<String> ids= FileUtil.readUtf8Lines("/home/ids.txt");
        List<List<String>> result=new ArrayList<>();
        int i = 0,max=100;
        for (int t = 0; i < ids.size()/max; i++) {
            query(ids.subList(i*max,(i+1)*max),result);
            log.info("进度:{}/{}",i,ids.size()/max);
            Thread.sleep(2000);
        }
        query(ids.subList(i*max,ids.size()),result);
        log.info("result:{}",result);

        // 写法1
        String fileName = "/home/yyresult-" + System.currentTimeMillis() + ".xlsx";
        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        EasyExcel.write(fileName).head(Arrays.asList(
                Arrays.asList("实例ID"),Arrays.asList("变更记录数量")
        )).sheet("数量").doWrite(result);
    }

    private void query(List<String> ids,List<List<String>> result){
        Map<String,Object> map = ydClient.queryData(YDParam.builder().formUuid(FORM_UUID).formInstanceIdList(ids).build(), YDConf.FORM_QUERY.retrieve_changed).getOperationLogMap();
        for (String key:map.keySet()){
            List<Map> operations= UtilMap.getList(map,key);
            List<Map> evenOperations=operations.stream().filter(item ->
                    !UtilMap.getString(UtilMap.getMap(item,"operator"),"displayName").equals("宜搭平台")
            ).collect(Collectors.toList());
            log.info("数据[{}]操作记录条数：{}；过滤后：{}",key,operations.size(),evenOperations.size());
            result.add(Arrays.asList(key,String.valueOf(evenOperations.size()-1)));
        }
    }

    /***
     * 项目立项流程审批时间写入主表
     */
    @Test
    public void test3(){
        MDC.put("MDC_KEY_PID","1013");
        List<String> ids= FileUtil.readUtf8Lines("/home/ids.txt");
        for (int i = 0; i < ids.size(); i++) {
            log.info("进度:{}/{}",i+1,ids.size());
            cp(ids.get(i));
        }
    }

    private void cp(String id){
        Map keyMap=new HashMap();
        keyMap.put("项目启动项目经理填写","dateField_lv6a4gxu");
        keyMap.put("系统部署项目经理填写","dateField_lv6a4gxp");
        keyMap.put("系统对接项目经理填写","dateField_lv6a4gxq");
        keyMap.put("系统培训项目经理填写","dateField_lv6a4gxr");
        keyMap.put("系统上线项目经理填写","dateField_lv6a4gxs");
        keyMap.put("项目验收项目经理填写","dateField_lv6a4gxt");

        List<Map> list=(List<Map>) ydClient.queryData(YDParam.builder().processInstanceId(id).build(), YDConf.FORM_QUERY.retrieve_approval_record).getResult();
        Map upMap=new HashMap();
        for (int i = 0; i < list.size(); i++) {
            Map data=list.get(i);
//            System.out.println(JSONObject.toJSONString(list.get(i)));
            String showName=UtilMap.getString(data,"showName");
            if(keyMap.containsKey(showName)&&data.containsKey("actionExit")&&"agree".equals(UtilMap.getString(data,"actionExit"))){
                if(data.containsKey("operateTimeGMT")){
                    upMap.put(keyMap.get(showName),convertToTimestamp(UtilMap.getString(data,"operateTimeGMT")));
                }
            }
        }
        System.out.println(JSONObject.toJSONString(upMap));
        ydClient.operateData(YDParam.builder().formInstanceId(id).updateFormDataJson(JSONObject.toJSONString(upMap)).build(), YDConf.FORM_OPERATION.update);
    }

    /**
     * 自定义日期时间格式化器，允许解析没有秒数的ISO 8601格式时间字符串。
     */
    private static final DateTimeFormatter CUSTOM_ISO_DATE_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm[':ss']X");

    /**
     * 将ISO 8601格式的时间字符串转换为时间戳。
     *
     * @param isoDateTime ISO 8601格式的时间字符串，例如："2024-11-12T15:13Z"
     * @return 自1970-01-01T00:00:00Z以来的毫秒数
     */
    public static long convertToTimestamp(String isoDateTime) {
        try {
            // 使用自定义格式化器解析时间字符串
            Instant instant = Instant.from(CUSTOM_ISO_DATE_TIME.parse(isoDateTime));
            // 返回自纪元以来的毫秒数
            return instant.toEpochMilli()-28800000L;
        } catch (DateTimeParseException e) {
            throw new IllegalArgumentException("无法解析时间字符串: " + isoDateTime, e);
        }
    }

    /***
     * 合同档案最终用户回刷
     */
    @Test
    public void test5(){
        MDC.put("MDC_KEY_PID","1013");
        YDParam ydParam=YDParam.builder().formUuid("FORM-E83C9E307FFB4A978E0CB8DE1B899E9DXTXB").build();
        float pageSize = (float)YDConf.PAGE_SIZE_LIMIT;
        ydParam.setPageSize(1);
        long totalCount = this.ydClient.queryData(ydParam, YDConf.FORM_QUERY.retrieve_search_form).getTotalCount();
        ydParam.setCurrentPage(1);
        ydParam.setPageSize((int)pageSize);
        for(int page = 1; (double)page <= Math.ceil((double)((float)totalCount / pageSize)); ++page) {
            ydParam.setCurrentPage(page);
            List<Map> datalist=(List)this.ydClient.queryData(ydParam, YDConf.FORM_QUERY.retrieve_search_form).getData();
            for (int i = 0; i < datalist.size(); i++) {
                Map data=datalist.get(i);
                log.info("第{}页，第{}条数据:{}",page,i+1,data.get("formInstanceId"));
                Map formData=UtilMap.getMap(data,"formData");
//                if(PublicUtil.isNull(formData,"textField_m7txzt1j")){
//                    continue;
//                }
                List<Map> table=UtilMap.getList(formData,"tableField_lvuku8m3");
//                List<String> s1=new ArrayList<>(); // 省
//                List<String> s2=new ArrayList<>(); // 市
//                List<String> s3=new ArrayList<>(); // 最终用户
//                List<String> s4=new ArrayList<>(); // 医院等级
                for (Map item:table) {
                    String name=UtilMap.getString(item,"selectField_lw4jf0ys");
                    Map khMap=getData(name);
                    Map ddMap=JSONObject.parseObject(String.valueOf(khMap.get("addressField_lugff49g")),Map.class);
                    if(ddMap==null||!ddMap.containsKey("regionText")){
                        continue;
                    }
                    List<Map> regionText=UtilMap.getList(ddMap,"regionText");
                    item.put("textField_m7lccg50",UtilMap.getString(regionText.get(0),"zh_CN"));
                    item.put("textField_m7lccg51",UtilMap.getString(regionText.get(1),"zh_CN"));
                    item.put("textField_m1ajkyj0",UtilMap.getString(khMap,"selectField_lv0b91jn"));
//                    s1.add(UtilMap.getString(regionText.get(0),"zh_CN"));
//                    s2.add(UtilMap.getString(regionText.get(1),"zh_CN"));
//                    s3.add(name);
//                    s4.add(UtilMap.getString(khMap,"selectField_lv0b91jn"));

                }
                Map upMap=UtilMap.map("tableField_lvuku8m3",table);
//                Map upMap=UtilMap.map("tableField_lvuku8m3, textField_m7txzt1j, textField_m7txzt1k, textField_m7txsvfu, textField_m7txsvfv",
//                        table,String.join("/",s1),String.join("/",s2),String.join("/",s3),String.join("/",s4));
//                Map upMap=UtilMap.map("textField_m7txzt1j, textField_m7txzt1k, textField_m7txsvfu, textField_m7txsvfv","","","","");

//                List<Map> table=UtilMap.getList(formData,"tableField_lv0mefjq");
//                for (Map item:table) {
//                    String name=UtilMap.getString(item,"selectField_lv0mf6ew");
//                    Map khMap=getData(name);
//                    Map ddMap=JSONObject.parseObject(String.valueOf(khMap.get("addressField_lugff49g")),Map.class);
//                    if(ddMap==null||!ddMap.containsKey("regionText")){
//                        continue;
//                    }
//                    List<Map> regionText=UtilMap.getList(ddMap,"regionText");
//                    item.put("textField_m8r5vzl2",UtilMap.getString(regionText.get(0),"zh_CN"));
//                    item.put("textField_m8r5vzl3",UtilMap.getString(regionText.get(1),"zh_CN"));
//                    item.put("textField_m1ajkyj0",UtilMap.getString(khMap,"selectField_m72yft63"));
//                    item.put("textField_m8o4kfcf",UtilMap.getString(khMap,"textField_lv0cahf9"));
//                }
//                formData.putIfAbsent("numberField_ltdyaizp",0);
//                formData.putIfAbsent("numberField_ltdyaizx",0);
//                formData.putIfAbsent("numberField_lv3kj7j2",0);
//                formData.putIfAbsent("numberField_lv0fhmy1",0);
//                String amt= NumberUtil.sub(UtilMap.getString(formData,"numberField_ltdyaizc"),NumberUtil.add(UtilMap.getString(formData,"numberField_ltdyaizp"),UtilMap.getString(formData,"numberField_ltdyaizx")).toString()).toString();
//                Map upMap=UtilMap.map("numberField_m7pzn95k, tableField_lv0mefjq",amt,table);
//                upMap.put("numberField_ltdyaizp",formData.get("numberField_ltdyaizp"));
//                upMap.put("numberField_ltdyaizx",formData.get("numberField_ltdyaizx"));
//                upMap.put("numberField_lv3kj7j2",formData.get("numberField_lv3kj7j2"));
//                upMap.put("numberField_lv0fhmy1",formData.get("numberField_lv0fhmy1"));
                ydClient.operateData(YDParam.builder().formInstanceId(String.valueOf(data.get("formInstanceId"))).updateFormDataJson(JSONObject.toJSONString(upMap))
                        .useLatestVersion(true).build(),  YDConf.FORM_OPERATION.update);
            }
        }
    }

    Map<String,Map> KH_LIST=new  HashMap();

    public Map getData(String name){
        if(KH_LIST.containsKey(name)){
            return KH_LIST.get(name);
        }
        List<Map> datalist=(List) ydClient.queryData(YDParam.builder().formUuid("FORM-4020139BCB3341349EE81F5332085D35C294")
                .searchFieldJson(JSONObject.toJSONString(Arrays.asList(new YDSearch("textField_lr60luaz",name,"textField_lr60luaz", YDSearch.Type.TEXT_FIELD,YDSearch.Operator.EQ))))//精准匹配
                .build(), YDConf.FORM_QUERY.retrieve_search_form).getData();
        if(datalist!=null&&datalist.size()>0){
            KH_LIST.put(name,UtilMap.getMap(datalist.get(0),"formData"));
            return UtilMap.getMap(datalist.get(0),"formData");
        }else return new HashMap<>();
    }

    /***
     * 客户档案省市回刷
     */
    @Test
    public void test4(){
        MDC.put("MDC_KEY_PID","1013");
        YDParam ydParam=YDParam.builder().formUuid("FORM-4020139BCB3341349EE81F5332085D35C294").build();
        float pageSize = (float)YDConf.PAGE_SIZE_LIMIT;
        ydParam.setPageSize(1);
        long totalCount = this.ydClient.queryData(ydParam, YDConf.FORM_QUERY.retrieve_search_form).getTotalCount();
        ydParam.setCurrentPage(1);
        ydParam.setPageSize((int)pageSize);
        for(int page = 1; (double)page <= Math.ceil((double)((float)totalCount / pageSize)); ++page) {
            ydParam.setCurrentPage(page);
            List<Map> datalist=(List)this.ydClient.queryData(ydParam, YDConf.FORM_QUERY.retrieve_search_form).getData();
            for (int i = 0; i < datalist.size(); i++) {
                Map data=datalist.get(i);
                log.info("第{}页，第{}条数据:{}",page,i+1,data.get("formInstanceId"));
                Map formData=UtilMap.getMap(data,"formData");
                if(!PublicUtil.isNull(formData,"textField_m7u2p5n8")){
                    continue;
                }
                Map ddMap=JSONObject.parseObject(String.valueOf(formData.get("addressField_lugff49g")),Map.class);
                if(ddMap==null||!ddMap.containsKey("regionText")){
                    continue;
                }
                List<Map> regionText=UtilMap.getList(ddMap,"regionText");
                Map upMap=UtilMap.map("textField_m7u2p5n8, textField_m7u2p5nd",UtilMap.getString(regionText.get(0),"zh_CN"),UtilMap.getString(regionText.get(1),"zh_CN"));
                ydClient.operateData(YDParam.builder().formInstanceId(String.valueOf(data.get("formInstanceId"))).updateFormDataJson(JSONObject.toJSONString(upMap))
                        .useLatestVersion(true).build(),  YDConf.FORM_OPERATION.update);
            }
        }
    }


    /***
     * 查询审批记录
     */
    @Test
    public void test6(){
        MDC.put("MDC_KEY_PID","1013");
        JSONArray jsonArray=(JSONArray) ydClient.queryData(YDParam.builder().processInstanceId("e3736942-fc06-426c-9000-53fe8c7c56b7").build(),YDConf.FORM_QUERY.retrieve_approval_record).getResult();
        List<String> userIds = new ArrayList<>();
        extractOperatorIds(jsonArray,userIds);
        log.info("{}",userIds);
    }

    private static void extractOperatorIds(JSONArray array, List<String> result) {
        for (Object item : array) {
            JSONObject obj = (JSONObject) item;

            // 提取当前层级的 operatorUserId 或 operator
            String userId = obj.getString("operatorUserId");
            if (userId == null) userId = obj.getString("operator"); // 处理 domainList 中的字段
            if (userId != null) result.add(userId);

            // 递归处理 domainList
            JSONArray domainList = obj.getJSONArray("domainList");
            if (domainList != null && !domainList.isEmpty()) {
                extractOperatorIds(domainList, result);
            }
        }
    }

    @Test
    public void test11() {
        JSONObject json = new JSONObject();
        json.put("timeStamp", 1755163880737L);
        json.put("eventId","80364de251784febb741160244da7912");
        json.put("CorpId","ding321c72787fffc78b35c2f4657eb6378f");
        json.put("StaffId","01150949543132101208");
        json.put("EventType","check_in");
        json.put("EventTime",1755163880737L);
        json.put("BizId","346bb8e7-dde1-4a15-9715-ddd94ebfd306");
        json.put("staffId","01150949543132101208");
        json.put("TimeStamp", 1755163880737L);

        mcYdService.getCheckInData(json);
    }
}
