package com.malk.cloudpure.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.service.aliwork.YDClient;
import com.malk.service.aliwork.YDService;
import com.malk.service.dingtalk.DDClient;
import com.malk.service.dingtalk.DDClient_Contacts;
import com.malk.service.dingtalk.DDClient_Workflow;
import com.malk.utils.UtilDateTime;
import com.malk.utils.UtilList;
import com.malk.utils.UtilMap;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * 错误抛出与拦截详见 CatchException
 */
@Slf4j
@RestController
@RequestMapping("test")
public class TSController {

    @Autowired
    private DDClient ddClient;

    @Autowired
    private DDClient_Contacts ddClient_contacts;

    @Autowired
    private YDService ydService;

    @Autowired
    private YDClient ydClient;

    @SneakyThrows
    @GetMapping("test")
    McR test() {

        //updatePosition("2445432306884832");
//        tianhua618();

//        updateVersion("e6884e9b-fb5a-4e8b-822f-7cfb8ee4bfea");
//        lanyun621();

//        lanyun630();

        _lanyun0724();

        return McR.success();
    }

    // 12.09 蓝云账龄表

    /**
     * 同步开票档案账龄表
     */

    private YDParam.YDParamBuilder _initLYParam() {
        return YDParam.builder()
                .appType("APP_ERBDTFS82HOVBPL3NFH0")
                .systemToken("RRB66F91T97H1WN89QZYC47PKLZO2ZQOUMOQLP");
    }

    /**
     * 蓝云, 同步催款函
     */
    @GetMapping("syncCallLetters")
    public McR syncCallLetters() {
        List<Map> dataList = ydService.queryFormData_all(_initLYParam()
                .formUuid("FORM-EC785A5AB2B9432C892062823EB7C62A9NTL")
                .searchFieldJson(JSON.toJSONString(UtilMap.map("selectField_lvituew9, radioField_m4qrz687", "正常", "否")))
                .build());
        // 更新数据版本, upsert不支持版本更新
//        if (true) {
//            for (Map data : dataList) {
//                ydClient.operateData(_initLYParam()
//                        .formInstanceId(UtilMap.getString(data, "formInstanceId"))
//                        .updateFormDataJson(JSON.toJSONString(UtilMap.empty()))
//                        .useLatestVersion(true)
//                        .build(), YDConf.FORM_OPERATION.delete);
//            }
//            return McR.success();
//        }

        // 公司主体
        List<Map> subjectList = ydService.queryFormData_all(_initLYParam()
                .formUuid("FORM-B1425F3ECC294B858B267A806CB5AEDEFTND")
                .build());
        log.info("同步账龄表数据, {}", dataList.size());
        // 匹配逻辑: 客户 + 蓝云主体【明细按照开票周期】
        Map<String, Map> setMap = new HashMap();
        for (Map data : dataList) {
            String kpgs = UtilMap.getString(data, "selectField_lvc9x4vo");  // 开票公司
            String khmc = UtilMap.getString(data, "selectField_lvdojfui");  // 客户名称
            String unique = kpgs + "_" + khmc;
            Map formData = UtilMap.getMap(setMap, unique); // 累计标识
            if (!setMap.containsKey(unique)) {
                // 主表信息: 由 --> 至, 合计金额
                formData = UtilMap.map("textField_m06ij3z7, textField_m06ij3z8, numberField_m06lmogz", kpgs, khmc, UtilMap.getFloat(data, "numberField_m4qrz685"));
                List<Map> subjects = subjectList.stream().filter(item -> kpgs.equals(UtilMap.getString(item, "textField_lrintpap"))).collect(Collectors.toList()); // 精准匹配
                if (subjects.size() == 0) {
                    continue;
                }
                formData.putAll(UtilMap.map("textField_m06ij3zr, textField_m06ij3zs", kpgs, UtilMap.getString(subjects.get(0), "textField_m4qrp33v")));
                // 付款信息, 指定主体下账号
                List<Map> details = (List<Map>) UtilMap.getList(subjects.get(0), "tableField_luq9ph7m").stream().filter(item -> "是".equals(((Map) item).get("radioField_m4s770ep"))).collect(Collectors.toList());
                if (details.size() > 0) {
                    // 开户行, 银行账号
                    formData.putAll(UtilMap.map("textField_m06ij3zt, textField_m06ij3zu", "textField_lrpq6es0, textField_lrpq6es1, ", details.get(0)));
                }
                // 开票子表: 业务内容-开票内容, 发票号码, 开票时间-开票周期(文本), 项目名称, 金额-未回款金额, 备注-差异说明
                Map sub = UtilMap.map("textField_m06ij3zf, textField_m06ij3zg, textField_m06ij3zh, textField_m06ij3zi, numberField_m06ij3zk, textField_m06ij3zj", "textField_lvdnme0u, textField_lvd8pp35, textField_m25j5gxv, textField_lvdntzul, numberField_m4qrz685, textareaField_m25j5gyc", data);
                sub.put("textField_m06ij3ze", 1); // 序号
                formData.put("tableField_m06ij3zd", UtilList.asList(sub));
            } else {
                List<Map> table = UtilMap.getList(formData, "tableField_m06ij3zd");
                // 开票子表: 业务内容-开票内容, 发票号码, 开票时间-开票周期(文本), 项目名称, 金额-未回款金额, 备注-差异说明
                Map sub = UtilMap.map("textField_m06ij3zf, textField_m06ij3zg, textField_m06ij3zh, textField_m06ij3zi, numberField_m06ij3zk, textField_m06ij3zj", "textField_lvdnme0u, textField_lvd8pp35, textField_m25j5gxv, textField_lvdntzul, numberField_m4qrz685, textareaField_m25j5gyc", data);
                sub.put("textField_m06ij3ze", table.size() + 1); // 序号
                table.add(sub);
                formData.put("tableField_m06ij3zd", table);
                // 累计合计金额
                formData.put("numberField_m06lmogz", UtilMap.getFloat(formData, "numberField_m06lmogz") + UtilMap.getFloat(data, "numberField_m4qrz685"));
            }
            setMap.put(unique, formData);
        }

        log.info("催款函, {}", setMap.size());
        for (String unique : setMap.keySet()) {
            Map formData = UtilMap.getMap(setMap, unique);
            formData.put("textField_m4qxo07x", unique + "_" + UtilMap.getFloat(formData, "numberField_m06lmogz"));
            ydClient.operateData(_initLYParam()
                    .formUuid("FORM-738D89FEC34740EC92B08BF6D7B9470DEQY6")
                    .processCode("TPROC--IMD665A1KDXNJ2V47QQ9UCM9I9F827DEEI60M6")
                    .formDataJson(JSON.toJSONString(formData))
                    .userId("396511732") // 通过宜搭平台发起的，不会有待办, 通过企业账号发送 (system)
                    .build(), YDConf.FORM_OPERATION.start);
        }
        return McR.success();
    }


    /**
     * 蓝云, 全量同步账龄表 [后续可调整为同步前一天更新数据]
     */
    @GetMapping("syncAgingSchedule")
    public void syncAgingSchedule() {

        List<Map> dataList = ydService.queryFormData_all(_initLYParam()
                .formUuid("FORM-6603375ED27B4D059CBB919C2BEFA44BZVOL")
//                .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_lvdosccc", "KP_2024121301677")))
                .build());

        // 合同业务类型: 日保一次性与小业主一致
        Map compIds = UtilMap.map("大业主, 小业主, 工程订单, 日保一次性", "tableField_lvc9x4vt, tableField_lvdnme13, tableField_lvd8pp44, tableField_lvdnme13");

        // 账龄表主表: 1 开票档案, 合同业务类型, 开票编号
        Map compId_main = UtilMap.map("associationFormField_m25j5gxb, selectField_lvc9x4vn, textField_lvdosccc", "kpdh_gl, selectField_lvc9x4vn, textField_lvdosccc");
        // 账龄表主表: 2 开票公司, 公司编码, 开票类型,
        compId_main.putAll(UtilMap.map("selectField_lvc9x4vo, textField_m065jst5, selectField_lvc9x4vp", "selectField_lvc9x4vo, textField_m065jst5, selectField_lvc9x4vp"));
        // 账龄表主表: 3 项目点名称, 项目点编号, 收款协议
        compId_main.putAll(UtilMap.map("textField_lvdntzul, textField_m25j5gxk, selectField_lvc9x4vq", "textField_m4h15mt7, textField_lvdntzul, selectField_lvc9x4vq"));
        // 账龄表主表: 4 客户名称, 客户编号, 实际开票日期
        compId_main.putAll(UtilMap.map("selectField_lvdojfui, textField_lvdojfuj, dateField_lw5ud9bk", "selectField_lvdojfui, textField_lvdojfuj, dateField_lw5ud9bk"));
        // 账龄表主表: 5 实例ID, 发票号码, 发票状态
        compId_main.putAll(UtilMap.map("textField_m25j5gyi, textField_lvd8pp35, selectField_lvituew9", "formInstanceId, textField_lvd8pp35, selectField_lvituew9"));

        // 账龄表子表: 1 开票周期, 开票周期-文本, 开票内容, 含税单价, 数量, 税率
        List<String> compId_detail = UtilList.asList("dateField_m25j5gxu", "textField_m25j5gxv", "textField_lvdnme0u", "numberField_lvdnme0w", "numberField_lvdnme0x", "numberField_lvdnme0y");
        // 账龄表子表: 2 含税小计, 税额, 无税金额, 差异说明, 已回款金额, 回款周期, 回款周期-文本
        compId_detail.addAll(Arrays.asList("numberField_lvdnme0z", "numberField_lvdnme10", "numberField_lvdnme11", "textareaField_m25j5gyc", "numberField_lvg084l9", "dateField_m0dp1g0e", "textField_m25j5gyh"));
        // 账龄表子表: 匹配来源数据表
        Map compIds_tab = UtilMap.map("tableField_lvc9x4vt, tableField_lvd8pp44, tableField_lvdnme13",
                // 大业主对应子表
                Arrays.asList("dateField_lw5uybgq", "dateField_lw5uybgq_wb", "textField_lvd8pp2t", "numberField_lvd8pp2v", "numberField_lvd8pp2w", "numberField_lvd8pp2x", "numberField_lvd8pp2y", "numberField_lvd8pp2z", "numberField_lvd8pp30", "textField_lvdnme0g", "numberField_lvg084lb", "dateField_m0f55roc", "dateField_m0f55roc_wb"),
                // 工程订单对应子表
                Arrays.asList("dateField_lvd8pp45", "ateField_lvd8pp45_wb", "textField_lvd8pp3w", "numberField_lvd8pp3y", "numberField_lvd8pp3z", "numberField_lvd8pp40", "numberField_lvd8pp41", "numberField_lvd8pp42", "numberField_lvd8pp43", "textField_lvdnme0h", "numberField_lvg084l9", "dateField_m0dp1g0e", "dateField_m0dp1g0e_wb"),
                // 小业主\日报一次性对应子表
                Arrays.asList("dateField_lvdnme0t", "dateField_lvdnme0t_wb", "textField_lvdnme0u", "numberField_lvdnme0w", "numberField_lvdnme0x", "numberField_lvdnme0y", "numberField_lvdnme0z", "numberField_lvdnme10", "numberField_lvdnme11", "textField_lvdnme12", "numberField_lvg084la", "dateField_m0f55roe", "dateField_m0f55roe_wb"));

        // 明细处理为主表记录, 以明细形式写入
        for (Map formData : dataList) {

            String compId_type = UtilMap.getString(compIds, UtilMap.getString(formData, "selectField_lvc9x4vn"));
            List<Map> details = UtilMap.getList(formData, compId_type);
            log.info("账龄表同步, {}, {}, {}", UtilMap.getString(formData, "selectField_lvc9x4vn"), formData.get("formInstanceId"), details.size());
            if (details.isEmpty()) {
                continue;
            }
            // 主表字段匹配 kpdh_gl
            Map dataForm = UtilMap.empty();
            for (Object key : compId_main.keySet()) {
                if ("kpdh_gl".equals(compId_main.get(key))) {
                    dataForm.put(key, YDConf.associationForm("APP_ERBDTFS82HOVBPL3NFH0", "FORM-6603375ED27B4D059CBB919C2BEFA44BZVOL", UtilMap.getString(formData, "formInstanceId"), UtilMap.getString(formData, "textField_lvdosccc"), null, false));
                } else {
                    dataForm.put(key, formData.get(compId_main.get(key)));
                }
            }
            // 子表数据匹配 _wb
            for (Map detail : details) {
                // 唯一条件: 单据编号 + 业务类型 + 开票周期
                String compId_date = (String) UtilMap.getList(compIds_tab, compId_type).get(0);
                long kpzq = UtilMap.getLong(detail, compId_date);
                if (kpzq == 0) {
                    continue;
                }
                List<String> arrCompId = UtilMap.getList(compIds_tab, compId_type);
                for (int i = 0; i < arrCompId.size(); i++) {
                    String key = compId_detail.get(i);
                    if (arrCompId.get(i).contains("dateField_")) {
                        String cId = arrCompId.get(i).replace("_wb", "");
                        if (!detail.containsKey(cId)) {
                            continue;
                        }
                        long tm = UtilMap.getLong(detail, cId);
                        if (tm == 0) {
                            continue;
                        }
                        if (arrCompId.get(i).contains("_wb")) {
                            dataForm.put(key, UtilDateTime.format(new Date(tm), "yyyy-MM"));
                        } else {
                            dataForm.put(key, tm);
                        }
                    } else {
                        dataForm.put(key, detail.get(arrCompId.get(i)));
                    }
                }
                String kpzq_wb = UtilDateTime.format(new Date(kpzq), "yyyy-MM");
                List<Map> searchCondition = Arrays.asList(YDConf.searchCondition_TextFiled("textField_lvdosccc", UtilMap.getString(formData, "textField_lvdosccc"), "eq"),
                        YDConf.searchCondition_TextFiled("selectField_lvc9x4vn", UtilMap.getString(formData, "selectField_lvc9x4vn"), "eq"),
                        YDConf.searchCondition_TextFiled("textField_m25j5gxv", kpzq_wb, "eq"));
                // 回款状态与未回款金额记录, 用于催款函查询
                float figure = UtilMap.getFloat(dataForm, "numberField_lvdnme0z") - UtilMap.getFloat(dataForm, "numberField_lvg084l9");
                dataForm.put("radioField_m4qrz687", figure == 0 ? "是" : "否");
                dataForm.put("numberField_m4qrz685", figure);
                ydClient.operateData(_initLYParam()
                        .searchCondition(JSON.toJSONString(searchCondition))
                        .formUuid("FORM-EC785A5AB2B9432C892062823EB7C62A9NTL")
                        .formDataJson(JSON.toJSONString(dataForm))
                        .build(), YDConf.FORM_OPERATION.upsert_v2);
            }
        }
    }

    // 12.17 JL华南用户加入一分
    @GetMapping("jll/invite")
    public McR JLL_invite() {

        // 授权专属账号允许加入一分组织
//        String token = ddClient.getAccessToken("dingy8h3bgoqsdparydl", "Zshlws58uFmezijH7TAn2LgXvh2qqXUUtpObXJQODlE5SeWAQYmvKbgIX_ona0_t");
//        ddClient_contacts.multiOrgPermissions(token, "dingc54a4bb4def9663f35c2f4657eb6378f", null);

        // 0109 授权专属账号允许加入上海分组织 (华东)
        String token = ddClient.getAccessToken("dingy8h3bgoqsdparydl", "Zshlws58uFmezijH7TAn2LgXvh2qqXUUtpObXJQODlE5SeWAQYmvKbgIX_ona0_t");
        //ddClient_contacts.multiOrgPermissions(token, "dingc54a4bb4def9663f35c2f4657eb6378f", null);
        ddClient_contacts.multiOrgPermissions(token, "ding120e2a852a39a5df35c2f4657eb6378f", null);

        List<Map> dataList = ydService.queryFormData_all(YDParam.builder()
                .appType("APP_GW0W0VPQ0FR53R258J6G")
                .systemToken("WO966N71H84IUHE3AYRISBIWQTIH39K5R1ZRL32")
                .formUuid("FORM-F521892655A047C693B70982B97F8027WZRN")
                .build());
        log.info("用户列表, {}", dataList.size());

//        String ddToken = ddClient.getAccessToken("dingz2yea3codfo8c7lm", "JyytgtZZPmPVKifyiWO34cuQJZp6c99NMEJ7CfPoSVR8WceDRBPlnCU9_Zf1sQKT");
        // 0109 专属钉账号加入上海分, 保留华东原架构
        String ddToken = ddClient.getAccessToken("dingljptjms8t3xdmieo", "oJmnvcLjTKiwRArUqvi5K9lfGyRx1yitkPtrAIvJ_RhWlbrwUZnrF8cMkf94kOxo");
//        dataList = Arrays.asList(dataList.get(0));
        for (Map data : dataList) {
            if (UtilMap.getString(data, "radioField_m3zdctzd").equals("是")) {
                continue;
            }
            String name = UtilMap.getString(data, "textField_p2em9tg") + "（企）";
            //List<Long> deptId = Arrays.asList(UtilMap.getLong(data, "textField_fngklyc"));
//            List<Long> deptId = Arrays.asList(980751899L); // 使用隐藏部门做中转
            List<Long> deptId = Arrays.asList(1L); // 使用隐藏部门做中转
            // userId、姓名、工号、职位、手机号、邮箱
//            Map extInfo = UtilMap.map("userid, job_number, title, email, exclusive_mobile", "textField_disml2c, textField_8en47ss, textField_qasx8rm, textField_vyo7anl, textField_t6o72ey", data);
            Map extInfo = UtilMap.map("userid, job_number, title, exclusive_mobile, email", "textField_disml2c, textField_8en47ss, textField_qasx8rm, textField_t6o72e0y, textField_vyo7anl", data);
            extInfo.put("userid", UtilMap.getString(data, "textField_disml2c"));
//            extInfo.put("userid", UtilMap.getString(data, "textField_disml2c") + "d");
            if (data.containsKey("dateField_m54rr91h") && UtilMap.getLong(data, "dateField_m54rr91h") > 0) {
                extInfo.put("hired_date", UtilMap.getLong(data, "dateField_m54rr91h"));
            }
            Map result = UtilMap.map("radioField_m3zdctzd, textareaField_m3zajr2x", "是", "");
            try {
                ddClient_contacts.inviteExclusiveUser(ddToken, name, deptId, "dingf475a1e690748017acaaa37764f94726", UtilMap.getString(data, "textField_disml2c"), extInfo);
            } catch (McException e) {
                result.put("radioField_m3zdctzd", "否");
                result.put("textareaField_m3zajr2x", e.getMessage());
            }
            ydClient.operateData(YDParam.builder()
                    .appType("APP_GW0W0VPQ0FR53R258J6G")
                    .systemToken("WO966N71H84IUHE3AYRISBIWQTIH39K5R1ZRL32")
                    .formInstanceId(UtilMap.getString(data, "formInstanceId"))
                    .updateFormDataJson(JSON.toJSONString(result))
                    .useLatestVersion(true)
                    .build(), YDConf.FORM_OPERATION.update);
        }


        return McR.success();
    }

    // 11.27 JLL用户更新
    @GetMapping("jll/contact")
    public McR JLL_contact() {

        List<Map> dataList = ydService.queryFormData_all(YDParam.builder()
                .appType("APP_GW0W0VPQ0FR53R258J6G")
                .systemToken("WO966N71H84IUHE3AYRISBIWQTIH39K5R1ZRL32")
                .formUuid("FORM-2DD2B036B7DF4DDCA329E19BD5285EEBNCB8")
                .build());
        log.info("用户列表, {}", dataList.size());

        // 更新企业账号信息
        String accessToken = ddClient.getAccessToken("dingy8h3bgoqsdparydl", "Zshlws58uFmezijH7TAn2LgXvh2qqXUUtpObXJQODlE5SeWAQYmvKbgIX_ona0_t");
        dataList.forEach(formData -> {
            if (UtilMap.getString(formData, "radioField_m3zdctzd").equals("是")) {
                return;
            }
            String userId = UtilMap.getString(formData, "textField_m3zajr2t");
            Map userInfo = null;
            Map result = UtilMap.map("radioField_m3zdctzd", "是");
            try {
                userInfo = ddClient_contacts.getUserInfoById(accessToken, userId);
            } catch (McException e) {
                result.put("radioField_m3zdctzd", "是");
                result.put("textareaField_m3zajr2x", e.getMessage());
            }
            if (!Objects.isNull(userInfo)) {
                List<Long> deptIds = (List<Long>) UtilMap.getList(userInfo, "dept_id_list").stream().map(item -> Long.valueOf(String.valueOf(item))).collect(Collectors.toList());
                Map update = UtilMap.map("exclusive_mobile, email", UtilMap.getString(formData, "textField_m3zajr2u"), UtilMap.getString(formData, "textField_m3zajr2v"));
                try {
                    ddClient_contacts.updateUser_dingTalk(accessToken, userId, deptIds, update);
                } catch (McException e) {
                    result.put("radioField_m3zdctzd", "否");
                    result.put("textareaField_m3zajr2x", e.getMessage());
                }
            }
            ydClient.operateData(YDParam.builder()
                    .appType("APP_GW0W0VPQ0FR53R258J6G")
                    .systemToken("WO966N71H84IUHE3AYRISBIWQTIH39K5R1ZRL32")
                    .formInstanceId(UtilMap.getString(formData, "formInstanceId"))
                    .updateFormDataJson(JSON.toJSONString(result))
                    .useLatestVersion(true)
                    .build(), YDConf.FORM_OPERATION.update);
        });
        return McR.success();
    }


    // 蓝云 [采购付款更新]
    private void _lanyun0724() {
        List<Map> dataList = ydService.queryFormData_all(YDParam.builder()
                .appType("APP_ERBDTFS82HOVBPL3NFH0")
                .systemToken("RRB66F91T97H1WN89QZYC47PKLZO2ZQOUMOQLP")
                .formUuid("FORM-BF9735C77D224D01B69BC1C517A89755OV4M")
                .build());
        log.info("项目点数据, {}", dataList.size());
        dataList.forEach(formData -> {
            updateVersion(UtilMap.getString(formData, "instanceId"));
        });
    }

    @Autowired
    private DDClient_Workflow ddClient_workflow;

    @PostMapping("tmp")
    public void tmp() {
//        String token = ddClient.getAccessToken("dingfwn4kpmb4g3dy4fj", "OwdkUc9nvBivpwsg0AiaEcyWLtZ678fskqBJwP7B5CQNrycIoyKuWslFTCOOaZG4");

//        ddClient_workflow.getProcessInstanceId(token, "QVxpoRomSfOqOeuUqzwXvQ04851720676197");
//        ddClient_workflow.executeRunningApprove(token, "QVxpoRomSfOqOeuUqzwXvQ04851720676197", "396511732", "87755078200", "agree", "", null);

    }

    // 蓝云
    private void updateVersion(String formInstId) {
        ydClient.operateData(YDParam.builder()
                .appType("APP_ERBDTFS82HOVBPL3NFH0")
                .systemToken("RRB66F91T97H1WN89QZYC47PKLZO2ZQOUMOQLP")
                .formInstanceId(formInstId)
                .updateFormDataJson(JSON.toJSONString(new HashMap<>()))
                .useLatestVersion(true)
                .build(), YDConf.FORM_OPERATION.update);

    }

    /// 630 蓝云项目点数据更新
    private void lanyun630() {


        List<Map> dataList = ydService.queryFormData_all(YDParam.builder()
                .appType("APP_ERBDTFS82HOVBPL3NFH0")
                .systemToken("RRB66F91T97H1WN89QZYC47PKLZO2ZQOUMOQLP")
                .formUuid("FORM-97BA6C6C8C50416A9E5854F2F4B5C3F3R4WC")
//                .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_lrr3rg6h", "XM00363")))
                .build());
        log.info("项目点数据, {}", dataList.size());
        dataList.forEach(formData -> {
            List<Map> details = UtilMap.getList(formData, "tableField_lrru2tnq");
//            details = details.stream().filter(item -> UtilMap.isNotBlankString(item, "dateField_lrru2tnr")).collect(Collectors.toList());
            // 数据格式化
//            details.forEach(row -> {
//                row.put("textField_luh0k82j", UtilDateTime.format(new Date(UtilMap.getLong(row, "dateField_lrru2tnr")), "yyyy-MM"));
//            }
//            });
//            Collections.sort(details, Comparator.comparingLong(o -> UtilMap.getLong(o, "dateField_lrru2tnr")));

            // 查找当月数据
            LocalDateTime currentDate = UtilDateTime.firstDayOfLastMonth(LocalDateTime.now());
            Optional optional = details.stream().filter(item -> UtilDateTime.getLocalDateTimeTimeStamp(currentDate) == UtilMap.getLong(item, "dateField_lrru2tnr")).findAny();
            log.info("上个月数据, {}, {}", currentDate, optional);
            if (!optional.isPresent() || StringUtils.isNotBlank(UtilMap.getString((Map) optional.get(), "numberField_lrru2tnz"))) {
                return;
            }

            LocalDateTime lastMonthDate = UtilDateTime.firstDayOfLastMonth(currentDate);
            Map currentRow = (Map) optional.get();
            optional = details.stream().filter(item -> UtilDateTime.getLocalDateTimeTimeStamp(lastMonthDate) == UtilMap.getLong(item, "dateField_lrru2tnr")).findAny();
            log.info("上上月数据, {}, {}", lastMonthDate, optional);

            float price;
            if (!optional.isPresent() || StringUtils.isBlank(UtilMap.getString((Map) optional.get(), "numberField_lrru2tnz"))) {
                price = UtilMap.getFloat(currentRow, "numberField_lrru2tns");
                currentRow.put("numberField_lrru2tnz", price); // 取本月收入定额
            } else {
                price = UtilMap.getFloat((Map) optional.get(), "numberField_lrru2tnz");
                currentRow.put("numberField_lrru2tnz", price); // 取上月收入预估
            }
            price += UtilMap.getFloat(formData, "numberField_lutjev0u");
            log.info("price, {}", price);
            // 合计初始化
//            price = details.stream().map(item -> UtilMap.getFloat(item, "numberField_lrru2tnz")).collect(Collectors.toList()).stream().reduce(0f, (acc, cur) -> acc + cur);
            ydClient.operateData(YDParam.builder()
                    .appType("APP_ERBDTFS82HOVBPL3NFH0")
                    .systemToken("RRB66F91T97H1WN89QZYC47PKLZO2ZQOUMOQLP")
                    .formInstanceId(UtilMap.getString(formData, "formInstanceId"))
//                    .useLatestVersion(true)
                    .updateFormDataJson(JSON.toJSONString(UtilMap.map("tableField_lrru2tnq, numberField_lutjev0u", details, price)))
                    .build(), YDConf.FORM_OPERATION.update);
        });
    }

    /// 6.21 蓝云数据版本问题
    private void lanyun621() {

        List<Map> dataList = ydService.queryFormData_all(YDParam.builder()
                .appType("APP_ERBDTFS82HOVBPL3NFH0")
                .systemToken("RRB66F91T97H1WN89QZYC47PKLZO2ZQOUMOQLP")
                .formUuid("FORM-5A6C8B23015F44949F66543E5E684F5EF3SK")
                .build());
        dataList.forEach(item -> {
            updatePosition(UtilMap.getString(item, "textField_lxjl5kwm"));
            ydClient.operateData(YDParam.builder()
                    .appType("APP_ERBDTFS82HOVBPL3NFH0")
                    .systemToken("RRB66F91T97H1WN89QZYC47PKLZO2ZQOUMOQLP")
                    .formInstanceId(UtilMap.getString(item, "formInstanceId"))
                    .useLatestVersion(true)
                    .updateFormDataJson(JSON.toJSONString(new HashMap<>()))
                    .build(), YDConf.FORM_OPERATION.update);
        });
    }

    /// 6.18 苏州天华更新部门职位
    private void tianhua618() {
        List<Map> dataList = ydService.queryFormData_all(YDParam.builder()
                .appType("APP_GW0W0VPQ0FR53R258J6G")
                .systemToken("WO966N71H84IUHE3AYRISBIWQTIH39K5R1ZRL32")
                .formUuid("FORM-120A6337A2034F4FB0E44949DB05C3BE5FTC")
                .build());
        dataList.forEach(item -> {
            updatePosition(UtilMap.getString(item, "textField_lxjl5kwm"));
            ydClient.operateData(YDParam.builder()
                    .appType("APP_GW0W0VPQ0FR53R258J6G")
                    .systemToken("WO966N71H84IUHE3AYRISBIWQTIH39K5R1ZRL32")
                    .formInstanceId(UtilMap.getString(item, "formInstanceId"))
                    .build(), YDConf.FORM_OPERATION.delete);
        });
    }

    private void updatePosition(String userId) {
        String token = ddClient.getAccessToken("ding4h80bxhmsujcmkad", "gO9i1LvoExN3ozhKbJ6ZzZhHgvAXEfUfwJMJvYyaP0H5zt5jk2zhiWQLXQMCz9yd");
        Map userInfo = null;
        try {
            userInfo = ddClient_contacts.getUserInfoById(token, userId);
        } catch (McException e) {
            log.error(e.getMessage(), e);
            return;
        }
        String title = UtilMap.getString(userInfo, "title");
        if (StringUtils.isBlank(title)) {
            log.info("更新异常, {}, {}", userInfo);
            return;
        }
        List<Long> deptIds = (List<Long>) UtilMap.getList(userInfo, "dept_id_list").stream().map(item -> Long.parseLong(String.valueOf(item))).collect(Collectors.toList());
        List<Map> titles = deptIds.stream().map(dept_id -> UtilMap.map("dept_id, title", dept_id, title)).collect(Collectors.toList());
        ddClient_contacts.updateUser_dingTalk(token, userId, deptIds, UtilMap.map("dept_title_list", titles));
    }

}


