package com.malk.luyi.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.malk.delegate.McDelegate;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.common.McR;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.aliwork.YDClient;
import com.malk.service.dingtalk.DDClient;
import com.malk.utils.UtilMap;
import com.malk.utils.UtilServlet;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.*;
import java.util.*;

@Slf4j
@RestController
@RequestMapping()
public class KSJCController {
    @Autowired
    private YDClient ydClient;

    @Autowired
    private DDClient dd;

    @Autowired
    private McDelegate mcDelegate;

    @SneakyThrows
    @PostMapping("/JCKQZ")
//集尘根据员工id获取所在考勤组
    McR insetTHXM(HttpServletRequest request) {
        Map data = UtilServlet.getParamMap(request);
        String FormInstanceId = data.get("FormInstanceId").toString();
        String UserId = data.get("UserId").toString();

        if (UserId != "" && FormInstanceId != "") {
            Map rsp = dd.getusergroup(UserId);
            System.out.println("rsp:" + UserId + ":" + FormInstanceId);
            System.out.println("rsp:" + rsp);
            if (rsp != null) {
                JSONObject jsonObject = new JSONObject(rsp);
                String groupId = jsonObject.get("group_id").toString();
                String name = jsonObject.get("name").toString();
                String FORMID = "textField_lyo89dyq, textField_lyo89dyr";
                //获取到考勤组名称和考勤组id后，写入到宜搭
                ydClient.operateData(YDParam.builder()
                        .appType("APP_X89Y00KKTG36B8JYGZVR")
                        .systemToken("QIA66091HJPLRHM3AUFJLCN24CUP2VNMO41XLW4")
                        .formInstanceId(String.valueOf(FormInstanceId))
                        .updateFormDataJson(JSON.toJSONString(UtilMap.map(FORMID, name, groupId)))
                        .build(), YDConf.FORM_OPERATION.update);
            }
            log.info("rsp:" + rsp);
            System.out.println("rsp:" + rsp);
        }
        return McR.success();
    }

    @SneakyThrows
    @PostMapping("/JCpd")
//集尘根据员工id判断今天能不能打卡
    McR insetTHXM_TMER() {
        //获取所有人员
        List<Map> dataList = (List<Map>) ydClient.queryData(YDParam.builder()
                .appType("APP_X89Y00KKTG36B8JYGZVR")
                .systemToken("QIA66091HJPLRHM3AUFJLCN24CUP2VNMO41XLW4")
                .formUuid("FORM-1F9CC98764D84B64AB1B6A04BEB8CA2BIPQ0")
                // .searchFieldJson(JSON.toJSONString(UtilMap.map("serialNumberField_lt1i52jt",data.get("XMBH").toString())))
                .build(), YDConf.FORM_QUERY.retrieve_search_form).getData();
        //循环获得人员
        for (Map formData : dataList) {
            //人员-字段值
            String FormInstanceId = String.valueOf(formData.get("formInstanceId"));//实例id
            String if_pd = String.valueOf(UtilMap.getMap(formData, "formData").get("selectField_lyo6e0gi"));//是否能打卡
            String Ehtid = String.valueOf(UtilMap.getMap(formData, "formData").get("textField_lyo8p27i"));//考勤人ID
            String grup_id = String.valueOf(UtilMap.getMap(formData, "formData").get("textField_lyo89dyr"));//所在考勤组ID
            String panduanzuotian="是";// 是/否    是代表昨天是工作日  否代表不是工作日
            Map rsp = new HashMap<>();//用来接反馈值
            if (if_pd.equals("否")) {//如果为否，校验：1.昨天是否请假  2.昨天是否不用打卡
                // 判断昨天是否请假
                LocalDate yesterday = LocalDate.now().minusDays(1);
                // 构造昨天7点00分的时间
                LocalTime time = LocalTime.of(7, 0);
                //将日期和时间结合
                LocalDateTime yesterdaySevenPm = yesterday.atTime(time);
                // 假设我们使用的是系统默认时区，这里为了演示明确转换到UTC，
                // 但在计算时间戳时，如果不指定时区，默认会使用JVM的时区
                ZonedDateTime zdt = yesterdaySevenPm.atZone(ZoneId.systemDefault());
                // 转换为时间戳（毫秒）
                long timestamp_up = zdt.toInstant().toEpochMilli();
                yesterday = LocalDate.now().minusDays(1);
                time = LocalTime.of(23, 0);
                yesterdaySevenPm = yesterday.atTime(time);
                zdt = yesterdaySevenPm.atZone(ZoneId.systemDefault());
                long timestamp_dp = zdt.toInstant().toEpochMilli();
                rsp = dd.getleavestatus(Ehtid, timestamp_up, timestamp_dp);//获得请假请框
                JSONObject jsonObject = new JSONObject(rsp);
                String leave_status = jsonObject.get("leave_status").toString();
                if (!leave_status.equals("[]") && leave_status != null) {
                    if_pd = "是";
                    panduanzuotian="否";//假期，不做判断
                }
                //判断昨天是否考勤组的休息日
                rsp = dd.getgroupquery(Ehtid, grup_id);
                jsonObject = new JSONObject(rsp);
                if (!jsonObject.get("work_day_list").toString().equals("[]") && jsonObject.get("work_day_list").toString() != null) {//如果是固定班次就判断昨天是不是休息日
                    // 使用逗号分割字符串，得到元素字符串数组
                    String[] elements = jsonObject.get("work_day_list").toString().split(",");
                    LocalDate today = LocalDate.now();
                    LocalDate yesterday_dak = today.minusDays(1);
                    DayOfWeek dayOfWeekYesterday = yesterday_dak.getDayOfWeek();
                    int nums = 10;
                    switch (dayOfWeekYesterday) {
                        case SUNDAY:
                            nums = 0;
                            break;
                        case MONDAY:
                            nums = 1;
                            break;
                        case TUESDAY:
                            nums = 2;
                            break;
                        case WEDNESDAY:
                            nums = 3;
                            break;
                        case THURSDAY:
                            nums = 4;
                            break;
                        case FRIDAY:
                            nums = 5;
                            break;
                        case SATURDAY:
                            nums = 6;
                            break;
                    }
                    ;
                    if (nums != 10) {
                        if (elements[nums].equals("[0") || elements[nums].equals("0") || elements[nums].equals("0]")) {//证明昨天是休息日
                            if_pd = "是";
                            panduanzuotian="否";//不是工作日
                        }
                    }
                }

                System.out.println("work_day_list:" + jsonObject.get("work_day_list").toString());
            }
            if(if_pd.equals("是") && panduanzuotian.equals("是")){//如果能打卡，并且昨天是工作日 则判断昨天有无正常的打卡
                 LocalDate yesterday = LocalDate.now().minusDays(1);
                List<Map> dataList_bgxx = (List<Map>) ydClient.queryData(YDParam.builder()
                        .appType("APP_X89Y00KKTG36B8JYGZVR")
                        .systemToken("QIA66091HJPLRHM3AUFJLCN24CUP2VNMO41XLW4")
                        .formUuid("FORM-0FFD9FC6D55A4D72AB588D38CD3685BFKQDX")
                        .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_lywrs8w8, textField_m062afy7", Ehtid,yesterday)))
                        .instanceStatus("running")
                         .approvedResult("agree")//流程结束时的审批结论agree -> 通过   disagree -> 拒绝
                        .build(), YDConf.FORM_QUERY.retrieve_search_process).getData();
                if (dataList_bgxx.size() > 0) {
                    if_pd="是";
                }else {
                    if_pd="否";
                }

            }

            if (if_pd.equals("是")) {
                //1222310842
                rsp = dd.inset_hr_group("删除", Ehtid, "1222310842");
                //如果能打卡，就把人员加入到考勤组
                rsp = dd.inset_hr_group("新增", Ehtid, grup_id);
                JSONObject jsonObject = new JSONObject(rsp);

            }
            if (if_pd.equals("否")) {
                //如果不能打卡，就把人员踢出考勤组
                rsp = dd.inset_hr_group("删除", Ehtid, grup_id);
                //1222310842
                rsp = dd.inset_hr_group("新增", Ehtid, "1222310842");
            }
            //   执行完加入，把校验状态改成 否
            ydClient.operateData(YDParam.builder()
                    .appType("APP_X89Y00KKTG36B8JYGZVR")
                    .systemToken("QIA66091HJPLRHM3AUFJLCN24CUP2VNMO41XLW4")
                    .formInstanceId(String.valueOf(FormInstanceId))
                    .updateFormDataJson(JSON.toJSONString(UtilMap.map("selectField_lyo6e0gi", "否")))
                    .build(), YDConf.FORM_OPERATION.update);
        }
        return McR.success();
    }

    @SneakyThrows
    @PostMapping("/insetHR_kaoqin")
//打卡完成后，立即把员工移进考勤组
    McR insetHR_kaoqin(HttpServletRequest request) {
        Map data = UtilServlet.getParamMap(request);
        String Ehtid = data.get("Ehtid").toString();
        String grup_id = data.get("grup_id").toString();

          Map rsp = dd.inset_hr_group("删除", Ehtid, "1222310842");
          rsp = dd.inset_hr_group("新增", Ehtid, grup_id);
        JSONObject jsonObject = new JSONObject(rsp);
        return McR.success();
    }
    @SneakyThrows
    @PostMapping("/insetJie_Duan")
//根据项目和机台信息维护阶段数据。
    McR insetJie_Duan(HttpServletRequest request) {
        Map data = UtilServlet.getParamMap(request);
        String formInstanceId = data.get("formInstanceId").toString();
        if (!formInstanceId.equals("")) {
            List<Map> dataList_XM = (List<Map>) ydClient.queryData(YDParam.builder()
                    .appType("APP_X89Y00KKTG36B8JYGZVR")
                    .systemToken("QIA66091HJPLRHM3AUFJLCN24CUP2VNMO41XLW4")
                    .formUuid("FORM-A6153EC780554425A1A7451548F9D405PMSN")
                    .searchFieldJson(JSON.toJSONString(UtilMap.map("formInstanceId", formInstanceId)))
                    .build(), YDConf.FORM_QUERY.retrieve_search_form).getData();
            if (dataList_XM != null && dataList_XM.size() > 0) {
                for (Map formData_XM : dataList_XM) {
                    System.out.println("dsfasdf:" + formData_XM.get("formInstanceId").toString());
                    if (formData_XM.get("formInstanceId").toString().equals(formInstanceId)) {
                        String XMMC = String.valueOf(UtilMap.getMap(formData_XM, "formData").get("textField_lx1iumdr"));
                        String XMBH = String.valueOf(UtilMap.getMap(formData_XM, "formData").get("textField_lx1irnyo"));
                        String sdfa = String.valueOf(UtilMap.getMap(formData_XM, "formData").get("tableField_lx1iumdu"));     //textField_ly6lt3dm -> 111右套
                        JSONArray jsonArray = new JSONArray(sdfa);
                        if (jsonArray != null && jsonArray.size() > 0) {
                            for (int i = 0; i < jsonArray.size(); i++) {
                                // 获取每个JSONObject
                                JSONObject jsonObject = jsonArray.getJSONObject(i);
                                // 从JSONObject中获取你需要的字段
                                String JTXX = (String) jsonObject.get("textField_ly6lt3dm");
                                if (!XMBH.equals("") && !XMBH.equals("") && !JTXX.equals("")) {
                                    List<Map> dataList = (List<Map>) ydClient.queryData(YDParam.builder()
                                            .appType("APP_X89Y00KKTG36B8JYGZVR")
                                            .systemToken("QIA66091HJPLRHM3AUFJLCN24CUP2VNMO41XLW4")
                                            .formUuid("FORM-CA8ABC2353B94262BC02D4C5332273EEHRU2")//完成阶段配置
                                            // .searchFieldJson(JSON.toJSONString(UtilMap.map("serialNumberField_lt1i52jt",data.get("XMBH").toString())))
                                            .build(), YDConf.FORM_QUERY.retrieve_search_form).getData();
                                    //循环阶段数据，并写入限制完成表
                                    for (Map formData : dataList) {
                                        String JDMC = String.valueOf(UtilMap.getMap(formData, "formData").get("textField_lx31so5x"));//阶段名称
                                        String LX = String.valueOf(UtilMap.getMap(formData, "formData").get("textField_lxy17mef"));//类型
                                        String ZB = String.valueOf(UtilMap.getMap(formData, "formData").get("numberField_lxsaen1q"));//占比
                                        String ZZB = String.valueOf(UtilMap.getMap(formData, "formData").get("numberField_lxsaen1r"));//占总比
                                        String XH = String.valueOf(UtilMap.getMap(formData, "formData").get("numberField_lx31so5r"));//序号
                                        String ZZBZ = String.valueOf(UtilMap.getMap(formData, "formData").get("numberField_lxy17mee"));//#占总比值
                                        String[] sdfassss = new String[]{String.valueOf(UtilMap.getMap(formData, "formData").get("departmentSelectField_lyy1hoyr_id"))};
                                        String ZD = "textField_m00ovvk4, textField_m00ovvk3, textField_m00wsnjk, textField_lx31so5x, textField_lxy17mef, numberField_lxsaen1q, numberField_lxsaen1r, numberField_lx31so5r, numberField_lxy17mee, radioField_m00ovvk5, departmentSelectField_lyy1hoyr";
                                        if (i>0 && (LX.equals("设计达成率") || LX.equals("电气达成率") || JDMC.equals("下单") || JDMC.equals("询价"))){

                                        }else {
                                            String tquid = ydClient.operateData(YDParam.builder()
                                                    .appType("APP_X89Y00KKTG36B8JYGZVR")
                                                    .systemToken("QIA66091HJPLRHM3AUFJLCN24CUP2VNMO41XLW4")
                                                    .formUuid("FORM-9A3C0361CC6F43E2AEB6F66BA6B4F87DRHP5")
                                                    .formDataJson(JSON.toJSONString(UtilMap.map(ZD, XMBH, XMMC, JTXX, JDMC, LX, ZB, ZZB, XH, ZZBZ, "否", sdfassss[0].toString())))//这里
                                                    .build(), YDConf.FORM_OPERATION.create).toString();////
                                        }


                                    }
                                }
                            }
                        }

                    }
                }
            }
        }
        return McR.success();
    }
    @SneakyThrows
    @PostMapping("/ceshi")
//根据项目和机台信息维护阶段数据。
    McR ceshi(HttpServletRequest request) {

            return McR.success();
        }


    @SneakyThrows
    @PostMapping("/upload")
//集尘根据员工id上传打卡记录
    McR insetupload (HttpServletRequest request) {

        Map data = UtilServlet.getParamMap(request);
        String userid = data.get("userid").toString();
        String device_name = data.get("device_name").toString();
        String device_id = data.get("device_id").toString();
        String user_check_time = data.get("user_check_time").toString();
        dd.updateuploadss(userid, device_name,device_id,user_check_time);
        return McR.success();
    }
    @SneakyThrows
    @GetMapping("/cs")
//根据项目-写入设计阶段数据
    public McR insetTHXM_TMER1() {

        List<Map> dataList = (List<Map>) ydClient.queryData(YDParam.builder()
                .appType("APP_X89Y00KKTG36B8JYGZVR")
                .systemToken("QIA66091HJPLRHM3AUFJLCN24CUP2VNMO41XLW4")
                .formUuid("FORM-A6153EC780554425A1A7451548F9D405PMSN")
                .build(), YDConf.FORM_QUERY.retrieve_search_form).getData();
        for (Map formData : dataList) {
            String SFSJJD = String.valueOf(UtilMap.getMap(formData, "formData").get("selectField_m024f7ot"));//是否设计进度

            String SJJD = String.valueOf(UtilMap.getMap(formData, "formData").get("numberField_m024f7os"));//设计进度

            String SJYWCJD = String.valueOf(UtilMap.getMap(formData, "formData").get("numberField_m024f7ou")); //设计已完成进度

            String XMBH = String.valueOf(UtilMap.getMap(formData, "formData").get("textField_lx1irnyo")); //项目编号

            try {

                // 将字符串转换为数字

                Double designProgress = Double.parseDouble(SJJD);

                Double completedDesignProgress = Double.parseDouble(SJYWCJD);

                // 检查条件是否满足

                if ("是".equals(SFSJJD) && designProgress > completedDesignProgress) {

                    // 构建查询参数

                    JSONObject searchCondition = new JSONObject();

                    searchCondition.put("textField_lx1irnyo", XMBH);

                    List<Map> list1 = (List<Map>) ydClient.queryData(

                            YDParam.builder()

                                    .appType("APP_X89Y00KKTG36B8JYGZVR")

                                    .systemToken("QIA66091HJPLRHM3AUFJLCN24CUP2VNMO41XLW4")

                                    .formUuid("FORM-F43D52E34FCE429582DD351FDFF54F08HM12")

                                    .searchCondition(JSON.toJSONString(searchCondition))

                                    .build(),

                            YDConf.FORM_QUERY.retrieve_list).getData();

                    if (!list1.isEmpty()) {

                        Map map = list1.get(0);

                        JSONObject jsonObject = new JSONObject(map.get("formData"));

                        String instanceId = (String) jsonObject.get("textField_lx1irnyo");

                        List<Map> dataList_bgxx = (List<Map>) ydClient.queryData(YDParam.builder()

                                .appType("APP_X89Y00KKTG36B8JYGZVR")

                                .systemToken("QIA66091HJPLRHM3AUFJLCN24CUP2VNMO41XLW4")

                                .formUuid("FORM-F64808AC9EEB468789B94DA8C9B55FDEFNI7")

                                .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_lx1irnyo", instanceId)))

                                .instanceStatus("RUNNING")

//                                .approvedResult("agree")

                                .build(), YDConf.FORM_QUERY.retrieve_search_process).getData();

                        //如果有数据，则跳过，否则新建流程

                        if (dataList_bgxx!=null && dataList_bgxx.size()>0){

                            log.info("dataList_bgxx:{}", dataList_bgxx);

                            continue;

                        }else {

                            List<Map> list2 = (List<Map>) ydClient.queryData(YDParam.builder()

                                    .formUuid("FORM-A6153EC780554425A1A7451548F9D405PMSN")

                                    .appType("APP_X89Y00KKTG36B8JYGZVR")

                                    .systemToken("QIA66091HJPLRHM3AUFJLCN24CUP2VNMO41XLW4")

                                    .searchCondition(

                                            com.alibaba.fastjson.JSONObject.toJSONString(UtilMap.map("textField_lx1irnyo",instanceId))

                                    ).build(), YDConf.FORM_QUERY.retrieve_list).getData();

                            if(list2!=null){

                                Map formData2 = (Map) list2.get(0).get("formData");

                                String formInstanceId = String.valueOf(list2.get(0).get("formInstanceId"));

                                String khmcjsonString = formData2.get("associationFormField_lx1iumdq_id").toString();

                                String sbmcjsonString = formData2.get("associationFormField_lx1iumds_id").toString();

                                String XMH= String.valueOf(formData2.get("textField_lx1irnyo"));//项目号

                                String khmcTitle = getTitle(khmcjsonString);//客户名称

                                String sbmcTitle = getTitle(sbmcjsonString);//设备名称

                                String XMMC= String.valueOf(formData2.get("textField_lx1iumdr"));//项目名称

                                String  XMJL = String.valueOf(formData2.get("employeeField_lx1iumdt_id"));//项目经理

                                String  SJXMFZR = String.valueOf(formData2.get("employeeField_lyy2gpfq_id"));//设计项目负责人

                                String jsonArray = SJXMFZR.replace("'", "\"");

                                JSONArray element = new JSONArray(jsonArray);

                                // 获取数组中的第一个元素

                                String userId = String.valueOf(element.get(0));

                                String  ZD="associationFormField_lxipi7ri, textField_lx1irnyo, textField_lxipi7rj, textField_lxipi7rk, employeeField_lx1iumdt, employeeField_lz251up0, textField_lxis9v4x";



                                ydClient.operateData(YDParam.builder()

                                        .appType("APP_X89Y00KKTG36B8JYGZVR")

                                        .systemToken("QIA66091HJPLRHM3AUFJLCN24CUP2VNMO41XLW4")

                                        .formUuid("FORM-F64808AC9EEB468789B94DA8C9B55FDEFNI7")

                                        .userId(userId)

                                        .formDataJson(JSON.toJSONString(UtilMap.map(ZD, getAss(XMMC,formInstanceId), XMH, khmcTitle, sbmcTitle, XMJL, SJXMFZR, XMMC)))

                                        .build(), YDConf.FORM_OPERATION.start).toString();////

                            }

                        }

                    } else {

                        System.out.println("没有找到符合条件的记录。");

                    }

                }

            } catch (NumberFormatException e) {

                System.err.println("无法解析进度值：" + e.getMessage());

            }

        }

        return McR.success("success");

    }

    private Object getAss(String title,String id){

        return Arrays.asList(UtilMap.map("appType, formUuid, formType, instanceId, title, subTitle","APP_X89Y00KKTG36B8JYGZVR","FORM-A6153EC780554425A1A7451548F9D405PMSN","receipt",id,title,""));

    }



    private String getTitle(String jsonString){

        String supplierJsonString = StringEscapeUtils.unescapeJava(jsonString.substring(1, jsonString.length() - 1));//新供应商（关联表单）

        List<Map> supplier =(List<Map>) com.alibaba.fastjson.JSONArray.parse(supplierJsonString);

        String title = String.valueOf(supplier.get(0).get("title"));

        return title;

    }



}
