package com.malk.longyou.Controller;

import com.alibaba.fastjson.JSON;
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.DDConf;
import com.malk.server.dingtalk.DDFormComponentDto;
import com.malk.server.dingtalk.DDR;
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.UtilHttp;
import com.malk.utils.UtilMap;
import com.malk.utils.UtilServlet;
import com.malk.utils.UtilToken;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/longyou")
@EnableAsync
public class lytoOAController {


    @Autowired
    private DDClient_Workflow ddClient_workflow;
    @Autowired
    private YDClient ydClient;

    @Autowired
    private DDClient ddClient;


    @SneakyThrows
    @PostMapping("/insetToOA")
    McR insetXMC(HttpServletRequest request) {

        String mesg = "已完成";
        String getProcesscode="";
        Map data = UtilServlet.getParamMap(request);
        if (data != null) {
            String AppKey = data.get("AppKey").toString();
            String AppSecret = data.get("AppSecret").toString();
            String CorpId = data.get("CorpId").toString();
            String DDFromName = data.get("FromName").toString();
            String DDFromID = data.get("DDFromID").toString();//钉钉表单ID
            String foromuuid = retunYDFROMID(DDFromName);
           String FormInstanceId = data.get("YDfromID").toString();
            if (!AppKey.equals("") && !AppSecret.equals("") && !CorpId.equals("") && !DDFromName.equals("") && !DDFromID.equals("")) {
                try {
                    //通过CorpI查询对应的数据
                    List<Map> dataList_bgxx = (List<Map>) ydClient.queryData(YDParam.builder()
                            .appType("APP_N8M3FKV34PH3KQAXS44M")
                            .systemToken("ULD66N81DQ3T5ZD9BPH3S8JUDVT82L8U04H7MUQD")
                            .formUuid(foromuuid)
                            .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_m7hc1zky", CorpId)))
                            .build(), YDConf.FORM_QUERY.retrieve_search_process).getData();

                    //String formInstanceId = data.get("formInstanceId").toString();


                    mesg+="："+dataList_bgxx.size();
                    if (dataList_bgxx != null && dataList_bgxx.size() > 0) {
                        for (int i = 0; i < dataList_bgxx.size(); i++) {
                            Map formdata = dataList_bgxx.get(i);
                            formdata = (Map) formdata.get("data");
                            //写入OA
                            List<Map> formValues = this.retunMap(formdata, DDFromName);////根据表单名称匹配对应的OA字段映射
                            System.out.println("formValues:" + formValues);
                            String userId = String.valueOf(formdata.get("textField_m7h960t6"));//发起人UserID

                            Map extInfo = UtilMap.map("dept_id", DDConf.TOP_DEPARTMENT);
                            //  Map extInfo = UtilMap.map("dept_id", DDConf.TOP_DEPARTMENT);
                            String processInstanceId = ddClient_workflow.doProcessInstances(this.getAccessToken(AppKey, AppSecret), userId, DDFromID, formValues, extInfo);

                        }
                    }

                } catch (McException e) {

                    mesg = e.getMessage();
                }
                ydClient.operateData(YDParam.builder()
                        .appType("APP_N8M3FKV34PH3KQAXS44M")
                        .systemToken("ULD66N81DQ3T5ZD9BPH3S8JUDVT82L8U04H7MUQD")
                        .formInstanceId(String.valueOf(FormInstanceId)).useLatestVersion(true)
                        .updateFormDataJson(JSON.toJSONString(UtilMap.map("textareaField_m7j6zezs", mesg )))
                        .build(), YDConf.FORM_OPERATION.update);


            }
        }


        return McR.success();
    }

    public static String getAccessToken(String AppKey, String AppSecret) {
        String accessToken = "";
//        if (StringUtils.isNotBlank(accessToken)) return accessToken;
        Map param = new HashMap();
        param.put("appkey", AppKey);
        param.put("appsecret", AppSecret);
        DDR r = (DDR) UtilHttp.doGet("https://oapi.dingtalk.com/gettoken", param, DDR.class);
        log.info("响应token, {}", r.getAccessToken());
        accessToken = r.getAccessToken();
        // token失效自动重置: DD重新调用会重置过期时间
        // UtilToken.put("invalid-token-dingtalk", accessToken, r.getExpiresIn() * 1000L);
        return accessToken;
    }

    public String retunYDFROMID(String DDFromName) {
        String retunYDFROMID = "";
        if (DDFromName.equals("付款申请")) {
            retunYDFROMID = "FORM-822FDE31D5E149AD9179144C4A8A0010X6HX";
        }
        if (DDFromName.equals("费用报销")) {
            retunYDFROMID = "FORM-C73D2A7BC7FB4114AD3F3053A8D6F7D2FD4A";
        }
        if (DDFromName.equals("用章申请")) {
            retunYDFROMID = "FORM-8CD971E10C57411BB5B1BF02CC25B2E7Q7V5";
        }
        if (DDFromName.equals("维修申请")) {
            retunYDFROMID = "FORM-6424E98828C942A1864AE1882F5C6239CN5J";
        }
        if (DDFromName.equals("出差申请")) {
            retunYDFROMID = "FORM-18599997D2D44B8192945DF5ABDFE6DBRUIZ";
        }
        if (DDFromName.equals("请假申请")) {
            retunYDFROMID = "FORM-DE9CB63A765B4BAF8590B6224736B06EV6CF";
        }
        if (DDFromName.equals("合同审批")) {
            retunYDFROMID = "FORM-3B27A2923B624347822D48827DD27B8750O9";
        }
        return retunYDFROMID;
    }

    public List<Map> retunMap(Map formdata, String DDFromName) {
        List<Map> formValues = new ArrayList<>();
        if (DDFromName.equals("付款申请")) {
            Map ruleForm = new HashMap<>();
            ruleForm.put("selectField_kifm5he2", "供应商");
            ruleForm.put("selectField_kifejog7", "合同编号");
            ruleForm.put("numberField_kifu6j7b", "应付款金额");
            ruleForm.put("numberField_kifu6j7c", "累计已付金额");
            ruleForm.put("numberField_kifm5he6", "本次付款金额");
            ruleForm.put("numberField_kifu6j7i", "剩余金额");
            ruleForm.put("selectField_kifu6j7d", "付款方式");
            ruleForm.put("FKSJ", "付款日期");
            ruleForm.put("selectField_kifvqp9o", "发票情况");
            ruleForm.put("textField_kifvqp9p", "发票号");
            ruleForm.put("textareaField_kifnhkh4", "备注");
            Map ruleDetail = UtilMap.map("tableField_kiela8ug", UtilMap.map("selectField_kir7e0nt, textField_kir7e0nu, textField_kir7e0nv, numberField_kiela8ua, numberField_kir7e0nw, numberField_kifm5he5, numberField_kifu6j7h", "合同编号付款项, 合同付款项, 付款条件, 应付金额, 已付款金额, 本次付款金额, 剩余未付款金额"));
            ruleForm.put("tableField_kiela8ug", "付款明细");
            if (!formdata.get("dateField_kifgfgw5").equals("")) {
                long timestamp = (long) formdata.get("dateField_kifgfgw5"); // 例如：2021-10-01 00:00:00 UTC
                Instant instant = Instant.ofEpochMilli(timestamp);
                LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                String formattedDate = localDateTime.format(formatter);
                formdata.put("FKSJ", formattedDate);//付款日期传年月日格式
            }
            formValues = DDFormComponentDto.formatComponentValues(formdata, ruleForm, ruleDetail);
        }
        if (DDFromName.equals("费用报销")) {
            Map ruleForm = new HashMap<>();
            ruleForm.put("textField_m7hhnc3y", "申请人");
            ruleForm.put("textField_m7hhnc3z", "收款人");
            ruleForm.put("selectField_lmoighxc", "收款银行");
            ruleForm.put("textField_lmoighx2", "收款账号");
            ruleForm.put("numberField_lmoighxm", "报销总金额");
            ruleForm.put("textareaField_lmoighxr", "备注");
            Map ruleDetail = UtilMap.map("tableField_lmoighxh", UtilMap.map("selectField_lmoighxi, numberField_lmoighxj, textField_lmoighxl", "报销类别, 报销金额, 报销详细说明"));
            ruleForm.put("tableField_lmoighxh", "报销明细");
            formValues = DDFormComponentDto.formatComponentValues(formdata, ruleForm, ruleDetail);
        }
        if (DDFromName.equals("用章申请")) {
            Map ruleForm = new HashMap<>();
            ruleForm.put("textField_lmoa5kbv", "用章文件名称");
            ruleForm.put("numberField_lmoa5kbx", "文件份数");
            ruleForm.put("selectField_lmoa5kbz", "文件类别");
            ruleForm.put("selectField_lmoa5kc0", "加盖何种印章");
            ruleForm.put("textField_lmoa5kc1", "印章名称");
            ruleForm.put("textareaField_lmoa5kc2", "备注");

            formValues = DDFormComponentDto.formatComponentValues(formdata, ruleForm, null);
        }
        if (DDFromName.equals("维修申请")) {
            Map ruleForm = new HashMap<>();
            if (!formdata.get("dateField_lmo9uy7r").equals("")) {
                long timestamp = (long) formdata.get("dateField_lmo9uy7r"); // 例如：2021-10-01 00:00:00 UTC
                Instant instant = Instant.ofEpochMilli(timestamp);
                LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                String formattedDate = localDateTime.format(formatter);
                formdata.put("BXRQ", formattedDate);//报修日期传年月日格式
            }
            ruleForm.put("BXRQ", "报修日期");
            ruleForm.put("textField_m7iwejtd", "报修设备");
            ruleForm.put("textField_lmo9uy7t", "设备编号");
            ruleForm.put("textareaField_lmo9uy7u", "故障描述");

            formValues = DDFormComponentDto.formatComponentValues(formdata, ruleForm, null);
        }
        if (DDFromName.equals("出差申请")) {
            Map ruleForm = new HashMap<>();
            ruleForm.put("textField_m7iwfo5s", "出差类型");
            ruleForm.put("textField_m18xg91s", "出差事由");
            ruleForm.put("textField_m7h98l0c", "出发地");
            ruleForm.put("textField_m7h98l0d", "目的地");
            ruleForm.put("textField_m7h81iwu", "客户名称");
            ruleForm.put("textareaField_m18xg91v", "备注说明");

            formValues = DDFormComponentDto.formatComponentValues(formdata, ruleForm, null);
        }
        if (DDFromName.equals("请假申请")) {
            Map ruleForm = new HashMap<>();
            ruleForm.put("textField_m7iwhoeb", "请假类别");
            ruleForm.put("textField_m7hj640c", "开始时间");
            ruleForm.put("textField_m7hj640d", "结束时间");
            ruleForm.put("textareaField_kx5ti61t", "请假事由");
            ruleForm.put("numberField_kx5usnal", "请假时长");


            formValues = DDFormComponentDto.formatComponentValues(formdata, ruleForm, null);
        }
        if (DDFromName.equals("合同审批")) {
            Map ruleForm = new HashMap<>();
            ruleForm.put("textField_m1elynjm", "合同名称");
            ruleForm.put("textField_m7iwjki4", "合同类型");
            ruleForm.put("textareaField_m1elynjq", "合同内容概述");
            ruleForm.put("numberField_m1elynjs", "合同标的");
            Map ruleDetail = UtilMap.map("tableField_m1elynk0", UtilMap.map("textField_m7iwjki5, textField_m1elynk2, textField_m1elynka, textField_m1elynkc", "类型, 单位名称, 联系人, 联系方式"));
            ruleForm.put("tableField_m1elynk0", "相对方管理");
            ruleDetail.put("tableField_m1elynkg", UtilMap.map("textField_m7iwjki6, numberField_m1elynkk, textField_m1elynkm", "款项类型, 付款金额, 付款说明"));
            ruleForm.put("tableField_m1elynkg", "合同付款方式");
            formValues = DDFormComponentDto.formatComponentValues(formdata, ruleForm, ruleDetail);

        }
        return formValues;
    }
}
