package com.malk.kabeiyi.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;


import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.malk.core.McProject;
import com.malk.kabeiyi.config.CBSConstants;
import com.malk.kabeiyi.config.Constants;
import com.malk.kabeiyi.config.YidaConstants;
import com.malk.kabeiyi.entity.OperatingRecordEntity;
import com.malk.kabeiyi.mapper.OperationRecordMapper;
import com.malk.kabeiyi.service.KabeiyiService;
import com.malk.kabeiyi.util.CBSUtil;
import com.malk.kabeiyi.util.RecognizeAllText;
import com.malk.kabeiyi.util.ToSendCBS;
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.DDR;
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.service.dingtalk.DDClient_Workflow;
import com.malk.utils.UtilHttp;
import com.malk.utils.UtilMap;
import com.malk.utils.UtilToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.json.JSONArray;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Slf4j
@Service
public class KabeiyiServiceImpl implements KabeiyiService {
    @Autowired
    private DDClient_Workflow ddClient_workflow;

    @Autowired
    private DDClient ddClient;

    @Autowired
    private YDService ydService;

    @Autowired
    private YDClient ydClient;

    @Autowired
    private YDConf ydConf;
    @Autowired
    private CBSUtil cbsUtil;


    @Autowired
    private DDConf ddConf;
    @Autowired
    private YidaConstants yidaConstants;

    @Value("${tcdingtalk.appKey}")
    private String appKey;

    @Value("${tcdingtalk.appSecret}")
    private String appSecret;

    @Value("${aliwork.accessKeyId}")
    private String accessKeyId;

    @Value("${aliwork.accessKeySecret}")
    private String accessKeySecret;

    @Value("${ocr.filePath}")
    private String filePath;

    @Value("${u8.fromAccount}")
    private String fromAccount;

    @Value("${u8.toAccount}")
    private String toAccount;

    @Value("${u8.appKey}")
    private String u8AppKey;

    @Value("${u8.appSecret}")
    private String u8AppSecret;

    OperationRecordMapper recordMapper;

    //结算方式
    public final static String PAY_TYPE = "JSFS001";

    //审批实例url前缀（卡倍亿）
    private static final String PROC_INST_PREFIX_URL = "https://aflow.dingtalk.com/dingtalk/web/query/pchomepage.htm?from=oflow&op=true&corpid=dingc3a744cb591a7346f2c783f7214b6d69#/plainapproval?procInstId=";

    //宜搭-关联数据（卡倍亿）
    private static final String RELATION = "FORM-230C40137ED94524B4D4C94F8B23A8D2F8PF";

    //审批实例url前缀（特充）
    private static final String PROC_INST_PREFIX_URL2 = "https://aflow.dingtalk.com/dingtalk/web/query/pchomepage.htm?from=oflow&op=true&corpid=ding3ea249a3b5b466d0f2c783f7214b6d69#/plainapproval?procInstId=";

    //宜搭-关联数据（特充）
    private static final String RELATION2 = "FORM-51E17EFB52C14C9CB9E00168FED2BC18LQ6H";

    //问题整改表
    private static final String QUESTION = "FORM-89F515967FF94C62A9031F28EF6000B1YV5Q";

    //问题整改表流程code
    private static final String QUESTION_PROC_CODE = "TPROC--DP5660A1LEXNP1S37P7KU9GCHD5U3HB6C360M5";

    //审核表
    private static final String CHECK = "FORM-F4ED246EADD8427381BC13C4F0FEF7FDYMKJ";

    //审核表流程code
    private static final String CHECK_PROC_CODE = "TPROC--4XC66Y61XWWNZNJKBZD4VAB5BQAJ2YANX160M5";

    //审核计划
    private static final String CHECK_PLAN = "FORM-A9A7991EEB7D41FDAADADB9B1E1750FE0K5K";

    //产品实发
    private static final String PRODUCT_REAL = "FORM-809458EB6D524CF5AE1A91A3492D8B1BZIMN";

    //内部交易客户
    private static final String INTERNAL_CUSTOMER = "FORM-14782CE27EA54D2C94CC5BEF90554E5ALYP7";

    //内部工厂
    private static final String INTERNAL_FACTORY = "FORM-6CD7A1EDE1134AC8B2EE833769595C2EIWQ6";

    //关联表单（卡倍亿）
    private static final Map<String, String> SCHEMA_MAP = new HashMap<>();

    static {
        SCHEMA_MAP.put("工厂用章流程", "1.1、工厂用章流程(除采购营销人事)");
        SCHEMA_MAP.put("中心用章流程", "1.2、中心用章流程（除采购营销人事）");
        SCHEMA_MAP.put("人事专用用章审批流程", "1.3、人事专用用章审批流程");
        SCHEMA_MAP.put("商务部用章申请流程", "1.4、商务部用章申请流程");
        SCHEMA_MAP.put("办公用品采购申请流程", "4.3、办公用品采购申请流程");

        //需传其他值
        //对方单位名称 收入或支出 金额 备注
        SCHEMA_MAP.put("信息化建设用章流程", "1.7、信息化建设用章流程");
        //合同说明 采购物品类型
        SCHEMA_MAP.put("技术中心请购审批流程", "4.10、技术中心请购审批流程");
        //合同总金额 合同说明
        SCHEMA_MAP.put("设备备品备件采购合同审批流程", "4.1b、设备备品备件采购合同审批流程");
        SCHEMA_MAP.put("其他物品采购合同流程", "4.2b、其他物品采购合同流程");
        SCHEMA_MAP.put("设备采购合同审批流程", "4.5c、设备采购合同审批流程");
        SCHEMA_MAP.put("原材料采购合同审批流程", "4.9b、原材料采购合同审批流程");
        SCHEMA_MAP.put("墨西哥采购合同审批流程", "4.13b、墨西哥采购合同审批流程");
    }

    //关联表单（特充）
    private static final Map<String, String> SCHEMA_MAP2 = new HashMap<>();

    static {
        //需传其他值
        //对方单位名称 收入或支出 金额 备注
        SCHEMA_MAP2.put("特充用章流程", "1.2、特充用章流程（除采购营销人事）");

        //合同总金额 合同说明
        SCHEMA_MAP2.put("设备备品备件采购合同审批流程", "4.1b、设备备品备件采购合同审批流程");
        SCHEMA_MAP2.put("其他物品采购合同流程", "4.2b、其他物品采购合同流程");
        SCHEMA_MAP2.put("母排设备采购合同审批流程", "4.5c、母排设备采购合同审批流程");
        SCHEMA_MAP2.put("双铝设备采购合同审批流程", "4.6c、双铝设备采购合同审批流程");

        //合同总金额
        SCHEMA_MAP2.put("原材料采购合同审批流程", "4.9b、原材料采购合同审批流程");

        //文件类别 对方单位名称 收入或支出 金额 用印文件名称 文件份数 加盖何种印章 备注
        SCHEMA_MAP2.put("信息化建设用章流程", "1.7、信息化建设用章流程");
    }

    @Override
    public McR pushProcInstToYD(Map map) {
        MDC.put("MDC_KEY_PID", "1002");

        //审批实例
        String procInstId = String.valueOf(map.get("procInstId"));
        //获取审批实例信息
        Map processInstance = ddClient_workflow.getProcessInstanceId(ddClient.getAccessToken(), procInstId);
        if (Objects.nonNull(processInstance)) {
            Map formData = new HashMap<>();
            String title = String.valueOf(processInstance.get("title"));
            String type = "";
            List<Map> formComponentValues = (List<Map>) processInstance.get("formComponentValues");
            for (String key : SCHEMA_MAP.keySet()) {
                if (title.contains(key)) {
                    type = SCHEMA_MAP.get(key);
                    switch (type) {
                        case "1.7、信息化建设用章流程":
                            for (Map formComponentValue : formComponentValues) {
                                String name = String.valueOf(formComponentValue.get("name"));
                                String value = String.valueOf(formComponentValue.get("value")).equals("null") ? "" : String.valueOf(formComponentValue.get("value"));
                                switch (name) {
                                    case "对方单位名称":
                                        formData.put("textField_lygzlf3j", value);
                                        break;
                                    case "收入或支出":
                                        formData.put("textField_lygzlf3k", value);
                                        break;
                                    case "金额":
                                        formData.put("textField_lygzlf3l", value);
                                        break;
                                    case "备注":
                                        formData.put("textField_lygzlf3m", value);
                                        break;
                                }
                            }
                            break;
                        case "4.1b、设备备品备件采购合同审批流程":
                        case "4.2b、其他物品采购合同流程":
                        case "4.5c、设备采购合同审批流程":
                        case "4.9b、原材料采购合同审批流程":
                        case "4.13b、墨西哥采购合同审批流程":
                            for (Map formComponentValue : formComponentValues) {
                                String name = String.valueOf(formComponentValue.get("name"));
                                switch (name) {
                                    case "合同总金额":
                                        formData.put("numberField_lyf81587", formComponentValue.get("value"));
                                        break;
                                    case "合同说明":
                                        if (Objects.nonNull(formComponentValue.get("value"))) {
                                            formData.put("textField_lyf81588", formComponentValue.get("value"));
                                        }
                                        break;
                                }
                            }
                            break;
                        case "4.10、技术中心请购审批流程":
                            for (Map formComponentValue : formComponentValues) {
                                String name = String.valueOf(formComponentValue.get("name"));
                                switch (name) {
                                    case "采购物品类型":
                                        formData.put("textField_lyibvb98", formComponentValue.get("value"));
                                        break;
                                    case "合同说明":
                                        if (Objects.nonNull(formComponentValue.get("value"))) {
                                            formData.put("textField_lyf81588", formComponentValue.get("value"));
                                        }
                                        break;
                                }
                            }
                            break;
                        default:
                            break;
                    }

                    formData.put("textField_lyf8157x", title);
                    formData.put("selectField_lyf81580", type);

                    Map condition = new HashMap<>();
                    condition.put("textField_lyf81581", PROC_INST_PREFIX_URL + procInstId);
                    //同步到宜搭
                    ydService.upsertFormData(RELATION, condition, formData, null);

                    break;
                }
            }
            return McR.success();
        }

        return McR.errorParam("审批实例不存在！");
    }

    @Override
    public McR pushProcInstToYD2(Map map) {
        MDC.put("MDC_KEY_PID", "1003");

        //审批实例
        String procInstId = String.valueOf(map.get("procInstId"));
        //获取审批实例信息
        Map processInstance = ddClient_workflow.getProcessInstanceId(getTcAccessToken(), procInstId);
        if (Objects.nonNull(processInstance)) {
            Map formData = new HashMap<>();
            String title = String.valueOf(processInstance.get("title"));
            String type = "";
            List<Map> formComponentValues = (List<Map>) processInstance.get("formComponentValues");
            for (String key : SCHEMA_MAP2.keySet()) {
                if (title.contains(key)) {
                    type = SCHEMA_MAP2.get(key);
                    switch (type) {
                        case "1.7、信息化建设用章流程":
                            for (Map formComponentValue : formComponentValues) {
                                String name = String.valueOf(formComponentValue.get("name"));
                                Object value = formComponentValue.get("value");
                                switch (name) {
                                    case "文件类别":
                                        formData.put("textField_lymfq9oa", value);
                                        break;
                                    case "对方单位名称":
                                        formData.put("textField_lygzlf3j", value);
                                        break;
                                    case "收入或支出":
                                        formData.put("textField_lygzlf3k", value);
                                        break;
                                    case "金额（元）":
                                        formData.put("textField_lygzlf3l", value);
                                        break;
                                    case "用印文件名称":
                                        formData.put("textField_lymfq9oc", value);
                                        break;
                                    case "文件份数":
                                        formData.put("numberField_lymfq9od", value);
                                        break;
                                    case "加盖何种印章":
                                        formData.put("textField_lymfq9oe", value);
                                        break;
                                    case "备注":
                                        formData.put("textField_lygzlf3m", value);
                                        break;
                                }
                            }
                            break;

                        case "4.1b、设备备品备件采购合同审批流程":
                        case "4.2b、其他物品采购合同流程":
                        case "4.5c、母排设备采购合同审批流程":
                        case "4.6c、双铝设备采购合同审批流程":
                        case "4.9b、原材料采购合同审批流程":
                            for (Map formComponentValue : formComponentValues) {
                                String name = String.valueOf(formComponentValue.get("name"));
                                switch (name) {
                                    case "合同总金额（元）":
                                    case "合同总金额":
                                        formData.put("numberField_lyf81587", formComponentValue.get("value"));
                                        break;
                                    case "合同说明":
                                        if (Objects.nonNull(formComponentValue.get("value"))) {
                                            formData.put("textField_lyf81588", formComponentValue.get("value"));
                                        }
                                        break;
                                }
                            }
                            break;
                        case "1.2、特充用章流程（除采购营销人事）":
                            for (Map formComponentValue : formComponentValues) {
                                String name = String.valueOf(formComponentValue.get("name"));
                                String value = String.valueOf(formComponentValue.get("value")).equals("null") ? "" : String.valueOf(formComponentValue.get("value"));
                                switch (name) {
                                    case "对方单位名称":
                                        formData.put("textField_lygzlf3j", value);
                                        break;
                                    case "收入或支出":
                                        formData.put("textField_lygzlf3k", value);
                                        break;
                                    case "金额（元）":
                                        formData.put("textField_lygzlf3l", value);
                                        break;
                                    case "备注":
                                        formData.put("textField_lygzlf3m", value);
                                        break;
                                }
                            }
                            break;
                        default:
                            break;
                    }

                    formData.put("textField_lyf8157x", title);
                    formData.put("selectField_lyf81580", type);

                    Map condition = new HashMap<>();
                    condition.put("textField_lyf81581", PROC_INST_PREFIX_URL2 + procInstId);


                    //同步到宜搭
                    ydService.upsertFormData(RELATION2, condition, formData, null);

                    break;
                }
            }
            return McR.success();
        }

        return McR.errorParam("审批实例不存在！");
    }

    @Override
    public McR addQuestionApproval(Map map) {
        MDC.put("MDC_KEY_PID", "1009");

        if (Objects.isNull(map.get("formInstId"))) {
            return McR.errorParam("formInstId不能为空！");
        }
        String formInstId = map.get("formInstId").toString();

        DDR_New ddrNew = ydClient.queryData(YDParam.builder()
                .formInstId(formInstId)
                .build(), YDConf.FORM_QUERY.retrieve_id);
        Map formData = ddrNew.getFormData();

        List<String> reviewerUserIds = (List<String>) formData.get("employeeField_m061zye5_id");//审核人
        String area = formData.get("selectField_m0w4kilf").toString();
        String factory = getString(formData.get("selectField_m3mmsbyd"));
        List<Map> details = (List<Map>) formData.get("tableField_m0kqtqoy");
        String[] yida = McProject.getYida("1009");
        for (Map detail : details) {
            String result = detail.get("radioField_m0nm3des").toString();
            if ("NG".equals(result)) {
                //发起问题整改审批
                Map question = new HashMap();
                question.put("textField_m061zye8", detail.get("textField_m0on13ob"));//审核项目
                question.put("textareaField_m061zye9", detail.get("textField_m0kqtqoz"));//审核方法和标准
                question.put("attachmentField_m061zyep", detail.get("attachmentField_m061zyep"));//问题证据
                question.put("textareaField_m063drgz", detail.get("textareaField_m063drgz"));//问题描述
                question.put("dateField_m061zyev", detail.get("dateField_m061zyev"));//整改截止时间
                question.put("employeeField_m10dns9c", detail.get("employeeField_m10d5uqj_id"));//部门经理
                question.put("selectField_m0w4kilf", area);//审核区域
                question.put("selectField_m3mmsbyd", factory);//工厂

                Map<String, Object> body = new HashMap<>();
                body.put("appType", yida[0]);
                body.put("systemToken", yida[1]);
                body.put("userId", reviewerUserIds.get(0));
                body.put("formUuid", QUESTION);
                body.put("processCode", QUESTION_PROC_CODE);
                body.put("formDataJson", JSONObject.toJSONString(question));

                UtilHttp.doPost("https://api.dingtalk.com/v1.0/yida/processes/instances/start", ddClient.initTokenHeader(), null, body, DDR_New.class);

            }
        }
        return McR.success();
    }

    @Override
    public McR ocr(String downloadUrl, String name, String type) {
        MDC.put("MDC_KEY_PID", "1020");

        //下载宜搭附件
        try {
            String[] yida = McProject.getYida("1020");
            downloadFile(downloadUrl, filePath + name, yida[0], yida[1]);
            log.info("文件下载成功!");
        } catch (IOException e) {
            e.printStackTrace();
            log.info("文件下载失败:{}" + e.getMessage());
        }
        //ocr识别
        try {
            String content = RecognizeAllText.recognizeText(filePath + name, type, accessKeyId, accessKeySecret);
            return McR.success(content);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("识别失败:{}" + e.getMessage());
        }
        return McR.errorUnknown("识别失败！");
    }

    public void downloadFile(String fileURL, String savePath, String appType, String systemToken) throws IOException {
        //若是宜搭附件url 则需获得附件临时免登地址
        Map<String, Object> param = new HashMap<>();
        param.put("systemToken", systemToken);
        param.put("userId", ddConf.getOperator());
        param.put("fileUrl", fileURL);
        fileURL = ((DDR_New) UtilHttp.doGet("https://api.dingtalk.com/v1.0/yida/apps/temporaryUrls/" + appType, ddClient.initTokenHeader(), param, DDR_New.class)).getResult().toString();

        URL url = new URL(fileURL);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        int responseCode = httpConn.getResponseCode();

        // 检查HTTP响应代码是否为200
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream inputStream = httpConn.getInputStream();
            FileOutputStream outputStream = new FileOutputStream(savePath);

            byte[] buffer = new byte[4096];
            int bytesRead = -1;

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            outputStream.close();
            inputStream.close();
        } else {
            System.out.println("无法下载文件。HTTP响应代码: " + responseCode);
        }
        httpConn.disconnect();
    }

    @Override
    public McR addPlanApproval(Map map) {
        MDC.put("MDC_KEY_PID", "1009");

        if (Objects.isNull(map.get("formInstId"))) {
            return McR.errorParam("formInstId不能为空！");
        }
        String formInstId = map.get("formInstId").toString();

        DDR_New ddrNew = ydClient.queryData(YDParam.builder()
                .formInstId(formInstId)
                .build(), YDConf.FORM_QUERY.retrieve_id);
        //计划制定人
        Map originator = ddrNew.getOriginator();
        String planUserId = originator.get("userId").toString();

        Map formData = ddrNew.getFormData();
        //审核人
        List<String> reviewerUserIds = (List<String>) formData.get("employeeField_m061zye5_id");
        //频次
        String frequency = formData.get("selectField_m0koxj7g").toString();
        //下次自动发起审核日期
        long nextTime = (long) formData.get("dateField_m0nbpasq");
        Date nextDate = new Date(nextTime);

        //上次自动发起审核日期
        Date lastTime = nextDate;
        //审核截至日期
        Date endDate = new Date();
        switch (frequency) {
            case "每周":
                endDate = DateUtils.addDays(nextDate, 6);
                nextDate = DateUtils.addDays(nextDate, 7);
                break;
            case "每两周":
                endDate = DateUtils.addDays(nextDate, 13);
                nextDate = DateUtils.addDays(nextDate, 14);
                break;
            case "每月":
                endDate = DateUtils.addDays(DateUtils.addMonths(nextDate, 1), -1);
                nextDate = DateUtils.addMonths(nextDate, 1);
                break;
            case "每季度":
                endDate = DateUtils.addDays(DateUtils.addMonths(nextDate, 3), -1);
                nextDate = DateUtils.addMonths(nextDate, 3);
                break;
            case "一次":
                endDate = new Date((long) formData.get("dateField_m0oqbh48"));
                nextDate = null;
                break;
            default:
                break;
        }
        //获取所有子表明细（大于50条）
        List<Map> details = getInnerTable(CHECK_PLAN, formInstId, "tableField_m0kqtqoy", 1, 50);
        formData.put("tableField_m0kqtqoy", details);
        //每个审批人发起审批
        for (String reviewerUserId : reviewerUserIds) {
            //根据userId获取部门id
            Map body = new HashMap<>();
            body.put("userid", reviewerUserId);

            DDR_New ddrNew1 = (DDR_New) UtilHttp.doPost("https://oapi.dingtalk.com/topapi/v2/department/listparentbyuser", null, ddClient.initTokenParams(), body, DDR_New.class);
            Map result = (Map) ddrNew1.getResult();
            List<Map> parentList = (List<Map>) result.get("parent_list");
            List<Long> parentDeptIdList = (List<Long>) parentList.get(0).get("parent_dept_id_list");
            String deptId = parentDeptIdList.get(0) + "";
            formData.put("departmentSelectField_m0c3qbjn", new String[]{deptId});
            formData.put("dateField_m061zye7", endDate.getTime());
            formData.put("employeeField_m061zye5", new String[]{reviewerUserId});
            //发起审批
            String[] yida = McProject.getYida("1009");
            Map<String, Object> body2 = new HashMap<>();

            body2.put("appType", yida[0]);
            body2.put("systemToken", yida[1]);
            body2.put("userId", planUserId);
            body2.put("formUuid", CHECK);
            body2.put("processCode", CHECK_PROC_CODE);
            body2.put("formDataJson", JSONObject.toJSONString(formData));

            UtilHttp.doPost("https://api.dingtalk.com/v1.0/yida/processes/instances/start", ddClient.initTokenHeader(), null, body2, DDR_New.class);
        }

        //更新审核计划下次发起审批时间及上次发起审批时间
        formData.put("dateField_m0nbpasw", lastTime);
        formData.put("dateField_m0nbpasq", nextDate);
        formData.put("employeeField_m061zye5", reviewerUserIds);
        ydClient.operateData(YDParam.builder()
                .formInstId(formInstId)
                .updateFormDataJson(JSON.toJSONString(formData))
                .build(), YDConf.FORM_OPERATION.update);

        return McR.success();
    }

    private List<Map> getInnerTable(String formUuid, String formInstId, String tableField, int pageNumber, int pageSize) {
        List<Map> details = new ArrayList<>();
        DDR_New ddrNew = new DDR_New();

        do {
            ddrNew = ydClient.queryData(YDParam.builder()
                    .formUuid(formUuid)
                    .formInstId(formInstId)
                    .tableFieldId(tableField)
                    .pageNumber(pageNumber)
                    .pageSize(pageSize)
                    .build(), YDConf.FORM_QUERY.retrieve_details);
            details.addAll((List<Map>) ddrNew.getData());
            pageNumber++;
        } while (ddrNew.getTotalCount() > pageSize * ddrNew.getPageNumber());

        return details;
    }

    @Override
    @Async
    public McR getSaleoutInfo() {
        //现在时间戳
        long beginTime = System.currentTimeMillis();

        MDC.put("MDC_KEY_PID", "1019");

        //内部交易客户
        DDR_New ddrNew = ydClient.queryData(YDParam.builder()
                .formUuid(INTERNAL_CUSTOMER)
                .build(), YDConf.FORM_QUERY.retrieve_list);
        List<Map> data = (List<Map>) ddrNew.getData();

        Set<String> cusCodes = new HashSet<>();
        for (Map map : data) {
            Map formData = (Map) map.get("formData");
            cusCodes.add(getString(formData.get("textField_m1g1tp7i")));
        }

        //数据源对应工厂
        Map<Integer, String> factory = new HashMap<>();
        DDR_New ddrNew2 = ydClient.queryData(YDParam.builder()
                .formUuid(INTERNAL_FACTORY)
                .build(), YDConf.FORM_QUERY.retrieve_list);
        List<Map> data2 = (List<Map>) ddrNew2.getData();
        for (Map map : data2) {
            Map formData = (Map) map.get("formData");
            int dqNumber = (int) formData.get("numberField_m1fvucmc");//数据源序号
            String factoryName = getString(formData.get("textField_m1fvucmd"));//工厂名称
            factory.put(dqNumber, factoryName);
        }
        List<Map> errorList = new ArrayList<>();

        //同步当月内的数据 upsert
        DateTime dateTime = DateUtil.offsetDay(new Date(), -1);
        String yesterday = dateTime.toString("yyyy-MM-dd");

        DateTime beginOfMonth = DateUtil.beginOfMonth(DateUtil.lastMonth());
        String beginOfMonthString = beginOfMonth.toString("yyyy-MM-dd");

        /*String beginOfMonthString = "2025-06-25";

        String yesterday = "2025-06-25";*/
        for (Integer dsSequence : factory.keySet()) {
            /*if (dsSequence != 8){
                continue;
            }*/

            List<String> errorCodes = new ArrayList<>();

            //存放存货名称、编码
            Map<String, String> inventory = new HashMap<>();

            Map<String, Object> param = new HashMap<>();
            param.put("from_account", fromAccount);
            param.put("to_account", toAccount);
            param.put("app_key", u8AppKey);
            param.put("token", getU8Token());
            param.put("page_index", 1);
            param.put("rows_per_page", 50);
            param.put("ds_sequence", dsSequence);
            param.put("date_begin", beginOfMonthString);
            param.put("date_end", yesterday);

            Map<String, Object> map = get("https://api.yonyouup.com/api/saleoutlist/batch_get", param, null);
            if (!getString(map.get("errcode")).equals("0")) {
                log.error("获取销售出库单列表失败:{}", map.get("errmsg"));
                continue;
            }
            if (!map.get("page_count").equals("1")) {
                Integer rowCount = Integer.valueOf(map.get("row_count").toString());
                param.put("rows_per_page", rowCount);
                map = get("https://api.yonyouup.com/api/saleoutlist/batch_get", param, null);
            }
            List<Map> saleoutList = (List<Map>) map.get("saleoutlist");

            for (Map saleout : saleoutList) {
                //查询单个出库单详情
                String id = getString(saleout.get("code"));

                /*if (!id.equals("0000009439")){
                    continue;
                }*/

                Map<String, Object> param2 = new HashMap<>();
                param2.put("from_account", fromAccount);
                param2.put("to_account", fromAccount);
                param2.put("app_key", u8AppKey);
                param2.put("token", getU8Token());
                param2.put("id", id);
                param2.put("ds_sequence", dsSequence);

                Map<String, Object> map2 = new HashMap<>();

                int i1 = 1;
                boolean flag1 = false;
                while (i1 <= 5 && !flag1) {
                    try {
                        map2 = get("https://api.yonyouup.com/api/saleout/get", param2, null);
                        flag1 = true;
                    } catch (Exception e) {
                        log.error("获取出库单详情失败:{}, 重试次数:{}", e.getMessage(), i1);
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException ex) {
                            throw new RuntimeException(ex);
                        }
                        i1++;
                    }
                }
                if (i1 > 5) {
                    log.error("获取出库单详情失败");
                    errorCodes.add(id);
                    continue;
                }


                Map saleout2 = (Map) map2.get("saleout");

                Map formData = new HashMap();
                //若为内部交易客户，则不同步
                String cusCode = getString(saleout2.get("customercode"));
                if (cusCodes.contains(cusCode)) {
                    continue;
                }
                if (!getString(saleout2.get("warehousename")).contains("成品") || getString(saleout2.get("warehousename")).contains("外购")) {
                    continue;
                }

                formData.put("textField_m18nvp87", getString(saleout2.get("code")));//出库单号
                formData.put("textField_m18qfuj0", getString(saleout2.get("saletypename")));//销售类型
                formData.put("textField_m18nvp8c", getString(saleout2.get("businesscode")));//业务单号
                formData.put("textField_m5nnwiv1", getString(saleout2.get("warehousename")));//仓库名称
                formData.put("dateField_m18nvp7x", DateUtil.parseDate(getString(saleout2.get("date"))).getTime());//单据日期
                formData.put("textField_mbu5nao3", getWeekRange(getString(saleout2.get("date"))));//发货周
                formData.put("textField_mbu5nao5", saleout2.get("date").toString().substring(0, 4));//年份
                formData.put("dateField_m5nnwiuw", Objects.nonNull(saleout2.get("auditdate")) ? DateUtil.parseDate(getString(saleout2.get("auditdate"))).getTime() : null);//审核日期
                formData.put("textField_m18nvp7y", getString(saleout2.get("customername")));//客户名称
                formData.put("textField_m18nvp7z", getString(saleout2.get("departmentname")));//部门
                formData.put("textField_m1er3scl", factory.get(dsSequence));//工厂名称
                formData.put("textField_m18nvp81", getString(saleout2.get("maker")));//制单人
                formData.put("textField_m18nvp80", getString(saleout2.get("handler")));//审核人
                formData.put("textareaField_m5nnwiur", getString(saleout2.get("memory")));//备注

                formData.put("numberField_m18wkih7", dsSequence);//数据源序号
                formData.put("selectField_m7b8j9uj", "实发");//类型

                AtomicReference<Double> totalQuantity = new AtomicReference<>(0d);
                AtomicReference<Double> totalCost = new AtomicReference<>(0d);

                List<Map> entry = (List<Map>) saleout2.get("entry");

                //collect拆分成五个list  每个list长度为500
                List<List<Map>> collectList = new ArrayList<>();
                for (int i = 0; i < entry.size(); i += 500) {
                    collectList.add(entry.subList(i, Math.min(i + 500, entry.size())));
                }

                if (collectList.size() > 5) {
                    log.error("出库单:{} 出库明细超过2500个, 请检查", id);
                    errorCodes.add(id + "出库明细超过2500");
                }

                //是否退线
                boolean isReject = false;

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

                //出库明细
                List<Map> list1 = new ArrayList();

                for (Map item : collectList.get(0)) {
                    if (Objects.isNull(formData.get("textField_m219zpzf"))) {
                        formData.put("textField_m219zpzf", getString(item.get("free1")));//客户码  出库主表没有客户码，取明细的客户码
                    }
                    if (Objects.isNull(formData.get("textField_m5nnwiv7"))) {
                        formData.put("textField_m5nnwiv7", getString(item.get("ordercode")));//销售订单号
                    }

                    Map detail = new HashMap();
                    detail.put("textField_m22mkwzk", getString(item.get("define29")));//客户存货码
                    detail.put("textField_mbu5naoj", getString(item.get("inventorycode")));//存货编码
                    detail.put("textField_mc1emzfr", getInventoryName(getString(item.get("inventorycode")), dsSequence, inventory));//存货名称
                    detail.put("textField_m21b1bhg", getString(item.get("free2")));//产品颜色
                    detail.put("textField_mbu5naoa", getString(item.get("define28")));//条码
                    detail.put("textField_m18nvp8f", getString(item.get("cmassunitname")));//单位

                    if (Objects.nonNull(item.get("quantity")) && isNumber(getString(item.get("quantity")))) {
                        if (getString((item.get("quantity"))).contains("-")) {
                            isReject = true;
                            break;
                        } else {
                            detail.put("numberField_m18nvp8h", getString(item.get("quantity")));//发货数量
                        }
                    } else {
                        continue;
                    }

                    totalQuantity.updateAndGet(v -> new Double((double) (v + Double.parseDouble(getString(item.get("quantity"))))));

                    String price = getString(item.get("price"));
                    String cost = getString(item.get("cost"));

                    try {
                        double numericValue = Double.parseDouble(price);

                        //单价为0时查询存货价目表
                        if (numericValue == 0d) {
                            String inventorycode = getString(item.get("inventorycode"));

                            if (inventoryPrice.containsKey(inventorycode)) {
                                price = inventoryPrice.get(inventorycode);
                            } else {
                                price = getInventoryPrice(factory.get(dsSequence), getString(item.get("free1")), getString(saleout2.get("date")), getString(item.get("inventorycode")));

                                inventoryPrice.put(getString(item.get("inventorycode")), price);
                            }

                            if (!"0".equals(price)) {
                                cost = Double.parseDouble(price) * Double.parseDouble(getString(item.get("quantity"))) + "";
                                detail.put("numberField_m18nvp8k", price);//单价
                                detail.put("numberField_m18nvp8m", cost);//金额
                            }
                        } else {
                            detail.put("numberField_m18nvp8k", price);//单价
                            detail.put("numberField_m18nvp8m", cost);//金额
                        }

                        String finalCost = cost;
                        totalCost.updateAndGet(v -> new Double((double) (v + Double.parseDouble(finalCost))));
                    } catch (NumberFormatException e) {
                        System.out.println("字符串不是有效的数值: " + price);
                    }

                   /* if (Objects.nonNull(item.get("price")) && isNumber(getString(item.get("price")))){
                        detail.put("numberField_m18nvp8k", getString(item.get("price")));//单价
                    }

                    if (Objects.nonNull(item.get("cost")) && isNumber(getString(item.get("cost")))){
                        detail.put("numberField_m18nvp8m", getString(item.get("cost")));//金额

                        totalCost.updateAndGet(v -> new Double((double) (v + Double.parseDouble(getString(item.get("cost"))))));
                    }*/

                    list1.add(detail);
                }

                List<Map> list2 = new ArrayList<>();
                if (collectList.size() > 1) {
                    for (Map item : collectList.get(1)) {
                        Map detail = new HashMap();
                        detail.put("textField_m2j0wj8o", getString(item.get("define29")));//客户存货码
                        detail.put("textField_mbu5naol", getString(item.get("inventorycode")));//存货编码
                        detail.put("textField_mc1emzft", getInventoryName(getString(item.get("inventorycode")), dsSequence, inventory));//存货名称
                        detail.put("textField_m2j0wj8q", getString(item.get("free2")));//产品颜色
                        detail.put("textField_mbu5naoc", getString(item.get("define28")));//条码
                        detail.put("textField_m2j0wj8r", getString(item.get("cinvm_unit")));//单位

                        if (Objects.nonNull(item.get("quantity")) && isNumber(getString(item.get("quantity")))) {
                            if (getString((item.get("quantity"))).contains("-")) {
                                isReject = true;
                                break;
                            } else {
                                detail.put("numberField_m2j0wj8s", getString(item.get("quantity")));//发货数量
                            }
                        } else {
                            continue;
                        }

                        totalQuantity.updateAndGet(v -> new Double((double) (v + Double.parseDouble(getString(item.get("quantity"))))));

                        String price = getString(item.get("price"));
                        String cost = getString(item.get("cost"));

                        try {
                            double numericValue = Double.parseDouble(price);

                            //单价为0时查询存货价目表
                            if (numericValue == 0d) {
                                String inventorycode = getString(item.get("inventorycode"));

                                if (inventoryPrice.containsKey(inventorycode)) {
                                    price = inventoryPrice.get(inventorycode);
                                } else {
                                    price = getInventoryPrice(factory.get(dsSequence), getString(item.get("free1")), getString(saleout2.get("date")), getString(item.get("inventorycode")));

                                    inventoryPrice.put(getString(item.get("inventorycode")), price);
                                }

                                if (!"0".equals(price)) {
                                    cost = Double.parseDouble(price) * Double.parseDouble(getString(item.get("quantity"))) + "";
                                    detail.put("numberField_m2j0wj8v", price);//单价
                                    detail.put("numberField_m2j0wj8w", cost);//金额
                                }
                            } else {
                                detail.put("numberField_m2j0wj8v", price);//单价
                                detail.put("numberField_m2j0wj8w", cost);//金额
                            }

                            String finalCost = cost;
                            totalCost.updateAndGet(v -> new Double((double) (v + Double.parseDouble(finalCost))));
                        } catch (NumberFormatException e) {
                            System.out.println("字符串不是有效的数值: " + price);
                        }

                        /*if (Objects.nonNull(item.get("price")) && isNumber(getString(item.get("price")))){
                            detail.put("numberField_m2j0wj8v", getString(item.get("price")));//单价
                        }

                        if (Objects.nonNull(item.get("cost")) && isNumber(getString(item.get("cost")))){
                            detail.put("numberField_m2j0wj8w", getString(item.get("cost")));//金额

                            totalCost.updateAndGet(v -> new Double((double) (v + Double.parseDouble(getString(item.get("cost"))))));
                        }*/

                        list2.add(detail);
                    }
                }

                List<Map> list3 = new ArrayList<>();
                if (collectList.size() > 2) {
                    for (Map item : collectList.get(2)) {
                        Map detail = new HashMap();
                        detail.put("textField_m2j0wj93", getString(item.get("define29")));//客户存货码
                        detail.put("textField_mbu5naon", getString(item.get("inventorycode")));//存货编码
                        detail.put("textField_mc1emzfv", getInventoryName(getString(item.get("inventorycode")), dsSequence, inventory));//存货名称
                        detail.put("textField_m2j0wj95", getString(item.get("free2")));//产品颜色
                        detail.put("textField_mbu5naoe", getString(item.get("define28")));//条码
                        detail.put("textField_m2j0wj96", getString(item.get("cinvm_unit")));//单位

                        if (Objects.nonNull(item.get("quantity")) && isNumber(getString(item.get("quantity")))) {
                            if (getString((item.get("quantity"))).contains("-")) {
                                isReject = true;
                                break;
                            } else {
                                detail.put("numberField_m2j0wj97", getString(item.get("quantity")));//发货数量
                            }
                        } else {
                            continue;
                        }

                        totalQuantity.updateAndGet(v -> new Double((double) (v + Double.parseDouble(getString(item.get("quantity"))))));

                        String price = getString(item.get("price"));
                        String cost = getString(item.get("cost"));

                        try {
                            double numericValue = Double.parseDouble(price);

                            //单价为0时查询存货价目表
                            if (numericValue == 0d) {
                                String inventorycode = getString(item.get("inventorycode"));

                                if (inventoryPrice.containsKey(inventorycode)) {
                                    price = inventoryPrice.get(inventorycode);
                                } else {
                                    price = getInventoryPrice(factory.get(dsSequence), getString(item.get("free1")), getString(saleout2.get("date")), getString(item.get("inventorycode")));

                                    inventoryPrice.put(getString(item.get("inventorycode")), price);
                                }

                                if (!"0".equals(price)) {
                                    cost = Double.parseDouble(price) * Double.parseDouble(getString(item.get("quantity"))) + "";
                                    detail.put("numberField_m2j0wj9a", price);//单价
                                    detail.put("numberField_m2j0wj9b", cost);//金额
                                }
                            } else {
                                detail.put("numberField_m2j0wj9a", price);//单价
                                detail.put("numberField_m2j0wj9b", cost);//金额
                            }

                            String finalCost = cost;
                            totalCost.updateAndGet(v -> new Double((double) (v + Double.parseDouble(finalCost))));
                        } catch (NumberFormatException e) {
                            System.out.println("字符串不是有效的数值: " + price);
                        }

                        /*if (Objects.nonNull(item.get("price")) && isNumber(getString(item.get("price")))){
                            detail.put("numberField_m2j0wj9a", getString(item.get("price")));//单价
                        }

                        if (Objects.nonNull(item.get("cost")) && isNumber(getString(item.get("cost")))){
                            detail.put("numberField_m2j0wj9b", getString(item.get("cost")));//金额

                            totalCost.updateAndGet(v -> new Double((double) (v + Double.parseDouble(getString(item.get("cost"))))));
                        }*/

                        list3.add(detail);
                    }
                }

                List<Map> list4 = new ArrayList<>();
                if (collectList.size() > 3) {
                    for (Map item : collectList.get(3)) {
                        Map detail = new HashMap();
                        detail.put("textField_m4cfhc70", getString(item.get("define29")));//客户存货码
                        detail.put("textField_mbu5naop", getString(item.get("inventorycode")));//存货编码
                        detail.put("textField_mc1emzfx", getInventoryName(getString(item.get("inventorycode")), dsSequence, inventory));//存货名称
                        detail.put("textField_m4cfhc72", getString(item.get("free2")));//产品颜色
                        detail.put("textField_mbu5naog", getString(item.get("define28")));//条码
                        detail.put("textField_m4cfhc73", getString(item.get("cinvm_unit")));//单位

                        if (Objects.nonNull(item.get("quantity")) && isNumber(getString(item.get("quantity")))) {
                            if (getString((item.get("quantity"))).contains("-")) {
                                isReject = true;
                                break;
                            } else {
                                detail.put("numberField_m4cfhc74", getString(item.get("quantity")));//发货数量
                            }
                        } else {
                            continue;
                        }

                        totalQuantity.updateAndGet(v -> new Double((double) (v + Double.parseDouble(getString(item.get("quantity"))))));

                        String price = getString(item.get("price"));
                        String cost = getString(item.get("cost"));

                        try {
                            double numericValue = Double.parseDouble(price);

                            //单价为0时查询存货价目表
                            if (numericValue == 0d) {
                                String inventorycode = getString(item.get("inventorycode"));

                                if (inventoryPrice.containsKey(inventorycode)) {
                                    price = inventoryPrice.get(inventorycode);
                                } else {
                                    price = getInventoryPrice(factory.get(dsSequence), getString(item.get("free1")), getString(saleout2.get("date")), getString(item.get("inventorycode")));

                                    inventoryPrice.put(getString(item.get("inventorycode")), price);
                                }

                                if (!"0".equals(price)) {
                                    cost = Double.parseDouble(price) * Double.parseDouble(getString(item.get("quantity"))) + "";
                                    detail.put("numberField_m4cfhc77", price);//单价
                                    detail.put("numberField_m4cfhc78", cost);//金额
                                }
                            } else {
                                detail.put("numberField_m4cfhc77", price);//单价
                                detail.put("numberField_m4cfhc78", cost);//金额
                            }

                            String finalCost = cost;
                            totalCost.updateAndGet(v -> new Double((double) (v + Double.parseDouble(finalCost))));
                        } catch (NumberFormatException e) {
                            System.out.println("字符串不是有效的数值: " + price);
                        }

                        /*if (Objects.nonNull(item.get("price")) && isNumber(getString(item.get("price")))){
                            detail.put("numberField_m4cfhc77", getString(item.get("price")));//单价
                        }

                        if (Objects.nonNull(item.get("cost")) && isNumber(getString(item.get("cost")))){
                            detail.put("numberField_m4cfhc78", getString(item.get("cost")));//金额

                            totalCost.updateAndGet(v -> new Double((double) (v + Double.parseDouble(getString(item.get("cost"))))));
                        }*/

                        list4.add(detail);
                    }
                }

                List<Map> list5 = new ArrayList<>();
                if (collectList.size() > 4) {
                    for (Map item : collectList.get(4)) {
                        Map detail = new HashMap();
                        detail.put("textField_m4cfhc7f", getString(item.get("define29")));//客户存货码
                        detail.put("textField_mbu5naor", getString(item.get("inventorycode")));//存货编码
                        detail.put("textField_mc1emzfz", getInventoryName(getString(item.get("inventorycode")), dsSequence, inventory));//存货名称
                        detail.put("textField_m4cfhc7h", getString(item.get("free2")));//产品颜色
                        detail.put("textField_mbu5naoi", getString(item.get("define28")));//条码
                        detail.put("textField_m4cfhc7i", getString(item.get("cinvm_unit")));//单位

                        if (Objects.nonNull(item.get("quantity")) && isNumber(getString(item.get("quantity")))) {
                            if (getString((item.get("quantity"))).contains("-")) {
                                isReject = true;
                                break;
                            } else {
                                detail.put("numberField_m4cfhc7j", getString(item.get("quantity")));//发货数量
                            }
                        } else {
                            continue;
                        }

                        totalQuantity.updateAndGet(v -> new Double((double) (v + Double.parseDouble(getString(item.get("quantity"))))));

                        String price = getString(item.get("price"));
                        String cost = getString(item.get("cost"));

                        try {
                            double numericValue = Double.parseDouble(price);

                            //单价为0时查询存货价目表
                            if (numericValue == 0d) {
                                String inventorycode = getString(item.get("inventorycode"));

                                if (inventoryPrice.containsKey(inventorycode)) {
                                    price = inventoryPrice.get(inventorycode);
                                } else {
                                    price = getInventoryPrice(factory.get(dsSequence), getString(item.get("free1")), getString(saleout2.get("date")), getString(item.get("inventorycode")));

                                    inventoryPrice.put(getString(item.get("inventorycode")), price);
                                }

                                if (!"0".equals(price)) {
                                    cost = Double.parseDouble(price) * Double.parseDouble(getString(item.get("quantity"))) + "";
                                    detail.put("numberField_m4cfhc7m", price);//单价
                                    detail.put("numberField_m4cfhc7n", cost);//金额
                                }
                            } else {
                                detail.put("numberField_m4cfhc7m", price);//单价
                                detail.put("numberField_m4cfhc7n", cost);//金额
                            }

                            String finalCost = cost;
                            totalCost.updateAndGet(v -> new Double((double) (v + Double.parseDouble(finalCost))));
                        } catch (NumberFormatException e) {
                            System.out.println("字符串不是有效的数值: " + price);
                        }

                        /*if (Objects.nonNull(item.get("price")) && isNumber(getString(item.get("price")))){
                            detail.put("numberField_m4cfhc7m", getString(item.get("price")));//单价
                        }

                        if (Objects.nonNull(item.get("cost")) && isNumber(getString(item.get("cost")))){
                            detail.put("numberField_m4cfhc7n", getString(item.get("cost")));//金额

                            totalCost.updateAndGet(v -> new Double((double) (v + Double.parseDouble(getString(item.get("cost"))))));
                        }*/

                        list5.add(detail);
                    }
                }

                if (isReject) {
                    continue;
                }

                formData.put("tableField_m18nvp82", list1);
                formData.put("tableField_m2j0wj90", list2);
                formData.put("tableField_m2j0wj9f", list3);
                formData.put("tableField_m4cfhc7c", list4);
                formData.put("tableField_m4cfhc7r", list5);

                formData.put("numberField_mbu92ncy", totalQuantity.get());//发货数量合计
                formData.put("numberField_mbu92nd0", totalCost.get());//发货金额合计

                //精准匹配
                List<Map> jsonString = new ArrayList<>();
                jsonString.add(UtilMap.map("key, value, type, operator, componentName", "textField_m18nvp87", getString(saleout2.get("code")), "TEXT", "eq", "TextField"));
                jsonString.add(UtilMap.map("key, value, type, operator, componentName", "numberField_m18wkih7", new int[]{dsSequence, dsSequence}, "DOUBLE", "between", "NumberField"));

                String searchCondition = JSONObject.toJSONString(jsonString);
                int i = 1;
                boolean flag = false;
                while (i <= 5 && !flag) {
                    try {
                        ydClient.operateData(YDParam.builder()
                                .formUuid(PRODUCT_REAL)
//                                .searchCondition(JSON.toJSONString(UtilMap.map("textField_m18nvp87, numberField_m18wkih7",getString(consignment2.get("code")),dsSequence)))//模糊查询
                                .searchCondition(searchCondition)//精准查询
                                .formDataJson(JSON.toJSONString(formData))
                                .build(), YDConf.FORM_OPERATION.upsert);
                        flag = true;
                    } catch (McException e) {
                        if (e.getMessage().contains("The request has failed due to a temporary failure of the server.")) {
                            log.error("upsert失败，尝试次数:{}", i);
                            i++;
                            try {
                                Thread.sleep(3000);
                            } catch (InterruptedException ex) {
                                throw new RuntimeException(ex);
                            }
                        } else {
                            log.error("upsert，失败原因:{}", e.getMessage());
                            errorCodes.add(id);
                            flag = true;
                        }
                    } catch (Exception e) {
                        log.error("出库单:{} 同步失败 失败原因:{}", getString(saleout2.get("code")), e.getMessage());
                        errorCodes.add(id);
                        flag = true;
                    }
                }
                if (i > 5) {
                    errorCodes.add(id);
                    log.error("出库单:{} 同步失败 失败原因:{}", getString(saleout2.get("code")), "重试次数过多");
                }
            }

            Map error = new HashMap();
            error.put("ds_sequence", dsSequence);
            error.put("error_count", errorCodes.size());
            //errorCodes逗号分隔
            error.put("errcodes", errorCodes.stream().collect(Collectors.joining(",")));
            errorList.add(error);

        }
        long endTime = System.currentTimeMillis();
        double time = (endTime - beginTime) / 1000.0;
        log.info("同步完成，耗时:{}秒", time);
        log.info("同步失败列表: {}", errorList);

        //记录失败日志
        Map<String, Object> formData = new HashMap<>();
        formData.put("dateField_m21oifwi", beginTime);
        formData.put("dateField_m21oifwp", endTime);
        formData.put("numberField_m21oifwo", time);
        //换行分隔errorList
        String errorStr = errorList.stream().map(item -> {
            String s = "数据源序号:" + item.get("ds_sequence") + ",错误数量:" + item.get("error_count") + ",发货单codes:" + item.get("errcodes");
            return s;
        }).collect(Collectors.joining("\n"));
        formData.put("textareaField_m21oifwj", errorStr);
        ydClient.operateData(YDParam.builder()
                .formUuid("FORM-F297D439FFF747ACB26DEA940850CD9B13LM")
                .formDataJson(JSON.toJSONString(formData))
                .build(), YDConf.FORM_OPERATION.create);
        return McR.success();
    }

    public String getInventoryPrice(String factory, String customerCode, String dateStr, String inventoryCode) {
        String price = "0";
        List<Map> searchCondition = new ArrayList<>();
        searchCondition.add(UtilMap.map("key, value, type, operator, componentName", "selectField_mc36onxf", factory, "TEXT", "eq", "TextField"));//工厂
        searchCondition.add(UtilMap.map("key, value, type, operator, componentName", "selectField_mc36onxg", customerCode, "TEXT", "eq", "TextField"));//客户码

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 解析日期字符串为 LocalDate
        LocalDate date = LocalDate.parse(dateStr, formatter);

        // 获取当天的起始时间（00:00:00）
        LocalDateTime startOfDay = date.atStartOfDay();
        // 获取当天的结束时间（23:59:59）
        LocalDateTime endOfDay = date.atTime(23, 59, 59);

        // 转换为时间戳（假设使用系统默认时区）
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime startZonedDateTime = startOfDay.atZone(zoneId);
        ZonedDateTime endZonedDateTime = endOfDay.atZone(zoneId);

        long startTimestamp = startZonedDateTime.toInstant().toEpochMilli();
        long endTimestamp = endZonedDateTime.toInstant().toEpochMilli();

        searchCondition.add(UtilMap.map("key, value, type, operator, componentName", "dateField_mc36onxh", Arrays.asList(startTimestamp, endTimestamp), "DOUBLE", "between", "DateField"));//出库时间
        searchCondition.add(UtilMap.map("key, value, type, operator, componentName", "textField_mc36onxm", inventoryCode, "TEXT", "eq", "TextField"));//存货编码

        List<Map> priceData = (List<Map>) ydClient.queryData(YDParam.builder()
                .formUuid("FORM-934F1DF0B6C34535B81102F0CEFB6C1FR55N")
                .searchCondition(JSONObject.toJSONString(searchCondition))
                .pageSize(1)
                .build(), YDConf.FORM_QUERY.retrieve_list).getData();

        if (priceData.size() == 1) {
            price = getString(((Map) priceData.get(0).get("formData")).get("numberField_mc36onxj"));
        }

        return price;
    }

    public String getInventoryName(String inventoryCode, int dsSequence, Map<String, String> inventory) {
        if (inventory.containsKey(inventoryCode)) {
            return inventory.get(inventoryCode);
        }

        Map<String, Object> param3 = new HashMap<>();
        param3.put("from_account", fromAccount);
        param3.put("to_account", fromAccount);
        param3.put("app_key", u8AppKey);
        param3.put("token", getU8Token());
        param3.put("id", inventoryCode);
        param3.put("ds_sequence", dsSequence);

        Map<String, Object> map3 = get("https://api.yonyouup.com/api/inventory/get", param3, null);

        Map inventoryInfo = (Map) map3.get("inventory");

        String inventoryName = getString(inventoryInfo.get("name"));

        inventory.put(inventoryCode, inventoryName);

        return inventoryName;
    }

    @Override
    public McR testInnerTable() {
        MDC.put("MDC_KEY_PID", "1019");

        Map updateFormData = new HashMap();
        List<Map> details = new ArrayList<>();

        for (int i = 0; i < 1000; i++) {
            Map detail = new HashMap();
            detail.put("textField_m2b95sh3", i + "");
            details.add(detail);
        }

        updateFormData.put("tableField_m2b95sh2", details);
        updateFormData.put("textField_m2b95sh5", "4");

        List<Map> jsonString = new ArrayList<>();
        jsonString.add(UtilMap.map("key, value, type, operator, componentName", "textField_m2b95sh5", "1", "TEXT", "eq", "TextField"));
        String searchCondition = JSONObject.toJSONString(jsonString);

        ydClient.operateData(YDParam.builder()
                .searchCondition(searchCondition)
                .formUuid("FORM-05AFA58A7DC4495C82AD23717C90A608JQ1F")
                .formDataJson(JSON.toJSONString(updateFormData))
//                        .updateFormDataJson(JSON.toJSONString(updateFormData))
                .build(), YDConf.FORM_OPERATION.upsert);


        return null;
    }

    @Override
    public void addVoucher(Map map) {
        MDC.put("MDC_KEY_PID", "1002");
        if (Objects.isNull(map.get("formInstId"))) {
            log.info("formInstId不能为空！");
            return;
        }
        String formInstId = map.get("formInstId").toString();

        DDR_New ddrNew = ydClient.queryData(YDParam.builder()
                .formInstId(formInstId)
                .build(), YDConf.FORM_QUERY.retrieve_id);
        Map formData = ddrNew.getFormData();
        String type = formData.get("selectField_m2sdpe2p").toString();
        int dsSequence = (int) formData.get("numberField_m2o5b8sh");
        String createUser = ((Map) ddrNew.getOriginator().get("name")).get("nameInChinese").toString();

        Map data = new HashMap();
        switch (type) {
            case "资金审批流程":
                data = process131(formData, dsSequence, createUser);
                break;
            case "采购部专用资金审批":
                data = process136(formData, dsSequence, createUser);
                break;

//            case "信息化建设专用资金审批":data = process138(formData,dsSequence,createUser);break;//20241112 暂时不推送13.8
            default:
                break;
        }

        //获取交易号
        Map tradeParam = new HashMap();
        tradeParam.put("from_account", fromAccount);
        tradeParam.put("app_key", u8AppKey);
        tradeParam.put("token", getU8Token());
        Map<String, Object> tradeMap = get("https://api.yonyouup.com/system/tradeid", tradeParam, null);
        Map trade = (Map) tradeMap.get("trade");
        String tradeId = getString(trade.get("id"));


        //推送凭证
        Map<String, Object> pushParam = new HashMap<>();
        pushParam.put("from_account", fromAccount);
        pushParam.put("to_account", toAccount);
        pushParam.put("app_key", u8AppKey);
        pushParam.put("token", getU8Token());
        pushParam.put("tradeid", tradeId);
        pushParam.put("sync", 1);
        pushParam.put("ds_sequence", dsSequence);

        Map result = post("https://api.yonyouup.com/api/voucher/add", pushParam, null, data);

        if (!"0".equals(result.get("errcode").toString())) {
            log.info("推送凭证失败:{}", result.get("errmsg").toString());
            throw new RuntimeException("推送凭证失败:" + result.get("errmsg").toString());
        }
    }

    private Map process138(Map formData, int dsSequence, String createUser) {
        String schPayAccount = getString(formData.get("selectField_lxydz0ub"));//付款方账号

        String revName = getString(formData.get("textField_lxwwvggc"));//收款人名称

        String company = getString(formData.get("selectField_lxwwvggb"));//公司抬头

        String purpose = getString(formData.get("textField_lxwwvggy"));//付款理由

        String summary = revName + "/" + purpose;//摘要

        String deptName = getString(formData.get("textField_m2sekyf7"));//部门

        String currency = getString(formData.get("textField_m2sekyfi"));//币种

        List<String> sepVoucherCompany = Arrays.asList("宁波卡倍亿电气技术股份有限公司", "宁波卡倍亿新材料科技有限公司", "宁波卡倍亿铜线有限公司", "湖北卡倍亿电气技术有限公司");

        String voucherType = sepVoucherCompany.contains(company) ? "付" : "记";//凭证类型

        String applyAmount = getString(formData.get("numberField_lxwwvggi"));//本次支付金额（元）

        String producer = createUser;//制单人

        //获取供应商信息
        Map<String, Object> supplierParam = new HashMap<>();
        supplierParam.put("from_account", fromAccount);
        supplierParam.put("to_account", toAccount);
        supplierParam.put("app_key", u8AppKey);
        supplierParam.put("token", getU8Token());
        supplierParam.put("page_index", 1);
        supplierParam.put("rows_per_page", 50);
        supplierParam.put("ds_sequence", dsSequence);
        supplierParam.put("name", revName);

        Map<String, Object> supplierMap = get("https://api.yonyouup.com/api/vendor/batch_get", supplierParam, null);
        if (!"0".equals(supplierMap.get("errcode").toString())) {
            log.info("获取供应商信息失败:{},{}", supplierMap.get("errmsg").toString(), revName);
            throw new RuntimeException("获取供应商信息失败:" + supplierMap.get("errmsg").toString() + "," + revName);
        }
        List<Map> vendorList = (List<Map>) supplierMap.get("vendor");
        String supplierCode = getString(vendorList.get(0).get("code"));

        //获取部门信息
        Map<String, Object> deptParam = new HashMap<>();
        deptParam.put("from_account", fromAccount);
        deptParam.put("to_account", toAccount);
        deptParam.put("app_key", u8AppKey);
        deptParam.put("token", getU8Token());
        deptParam.put("page_index", 1);
        deptParam.put("rows_per_page", 50);
        deptParam.put("ds_sequence", dsSequence);
        deptParam.put("name", deptName);

        Map<String, Object> deptMap = get("https://api.yonyouup.com/api/department/batch_get", deptParam, null);
        if (!"0".equals(deptMap.get("errcode").toString())) {
            log.info("获取部门信息失败:{},{}", deptMap.get("errmsg").toString(), deptName);
            throw new RuntimeException("获取部门信息失败:" + deptMap.get("errmsg").toString() + "," + deptName);
        }
        List<Map> deptList = (List<Map>) deptMap.get("department");
        String deptCode = getString(deptList.get(0).get("code"));

        Map resultMap = new HashMap();
        Map topInfoMap = new HashMap();

        //记账类型
        topInfoMap.put("voucher_type", voucherType);
        topInfoMap.put("enter", producer);  //制单人

        //credit entry信息   贷方
        Map infoMap = new HashMap();

        Map<String, Object> subjectParam = new HashMap<>();
        subjectParam.put("from_account", fromAccount);
        subjectParam.put("to_account", toAccount);
        subjectParam.put("app_key", u8AppKey);
        subjectParam.put("token", getU8Token());
        subjectParam.put("page_index", 1);
        subjectParam.put("rows_per_page", 50);
        subjectParam.put("ds_sequence", dsSequence);
        subjectParam.put("name", schPayAccount);

        Map<String, Object> subjectMap = get("https://api.yonyouup.com/api/code/batch_get", subjectParam, null);
        if (!"0".equals(subjectMap.get("errcode").toString())) {
            log.info("获取科目信息失败:{},{}", supplierMap.get("errmsg").toString(), schPayAccount);
            throw new RuntimeException("获取科目信息失败:" + supplierMap.get("errmsg").toString() + "," + schPayAccount);
        }
        List<Map> subjectList = (List<Map>) subjectMap.get("code");
        String subjectCode = getString(subjectList.get(0).get("code"));

        //贷方科目编码
        infoMap.put("account_code", subjectCode);
        //摘要
        infoMap.put("abstract", summary);
        //币种
        infoMap.put("currency", currency);

        //本币借方发生额*与本币贷方发生额不能同时为空
        infoMap.put("natural_credit_currency", applyAmount);

        List<Map> creditCashFlowList = new ArrayList<>();
        Map creditCashFlow = new HashMap();
        //币种
        creditCashFlow.put("cexch_name", currency);
        //本币借方发生额*与本币贷方发生额不能同时为空
        creditCashFlow.put("natural_credit_currency", applyAmount);
        //凭证类别字
        creditCashFlow.put("csign", voucherType);
        //科目编码 - 根据CBS 方，实际打款账户和公司来确定
        creditCashFlow.put("ccode", subjectCode);
        //贷方金额
        creditCashFlow.put("mc", applyAmount);
/*        //现金项目
        creditCashFlow.put("cCashItem", cashItem);
        //现金项目
        creditCashFlow.put("cash_item", cashItem);*/
        creditCashFlow.put("iyear", LocalDate.now().getYear());
        creditCashFlow.put("RowGuid", UUID.randomUUID().toString());

        creditCashFlowList.add(creditCashFlow);

        infoMap.put("cash_flow", creditCashFlowList);

        Map credit = new HashMap();
        credit.put("entry", infoMap);
        log.info("贷方credit:{}", credit);

        //debit entry信息   借方
        Map debit = new HashMap();
        List<Map> entryMapList = new ArrayList<>();
        List<Map> details = (List<Map>) formData.get("tableField_lyiffepf");
        String taxesSummary = ""; // 税金摘要
        for (Map detail : details) {

            String remark = getString(detail.get("textField_lyiffepn"));//备注
            String payType = "其他";//支付类型

            taxesSummary = revName + "/" + remark;

            BigDecimal taxesAmount = new BigDecimal(getString(detail.get("numberField_m38g47en")));//金额

            Map entryMap = new HashMap();

            //科目编号
            entryMap.put("account_code", "110110");//科目：其他  类型：资产
            //摘要
            entryMap.put("abstract", taxesSummary);
            //本币贷方发生额*与本币借方发生额不能同时为空
            entryMap.put("natural_debit_currency", taxesAmount);

            Map auxiliaryMap = new HashMap();
            auxiliaryMap.put("dept_id", deptCode);//部门
            auxiliaryMap.put("supplier_id", supplierCode);//供应商
            entryMap.put("auxiliary", auxiliaryMap);

            entryMapList.add(entryMap);
        }

        debit.put("entry", entryMapList);
        log.info("借方debit:{}", debit);

        topInfoMap.put("debit", debit);
        topInfoMap.put("credit", credit);
        resultMap.put("voucher", topInfoMap);
        log.info("voucher:{}", resultMap);

        return resultMap;
    }

    private Map process136(Map formData, int dsSequence, String createUser) {
        String schPayAccount = getString(formData.get("selectField_lxydz0ub"));//付款方账号

        String revName = getString(formData.get("textField_lxwwvggc"));//收款人名称

        String company = getString(formData.get("selectField_lxwwvggb"));//公司抬头

        String purpose = getString(formData.get("textField_lxwwvggy"));//付款理由

        String summary = revName + "/" + purpose;//摘要

        String deptName = getString(formData.get("textField_m2sekyf7"));//部门

        String currency = getString(formData.get("textField_m2sekyfi"));//币种

        List<String> sepVoucherCompany = Arrays.asList("宁波卡倍亿电气技术股份有限公司", "宁波卡倍亿新材料科技有限公司", "宁波卡倍亿铜线有限公司", "湖北卡倍亿电气技术有限公司");

        String voucherType = sepVoucherCompany.contains(company) ? "付" : "记";//凭证类型

        String applyAmount = getString(formData.get("numberField_lxwwvggi"));//本次支付金额（元）

        String producer = createUser;//制单人

        String cashItem = getString(formData.get("textField_m2sekyfg"));//现金项目

        //获取供应商信息
        Map<String, Object> supplierParam = new HashMap<>();
        supplierParam.put("from_account", fromAccount);
        supplierParam.put("to_account", toAccount);
        supplierParam.put("app_key", u8AppKey);
        supplierParam.put("token", getU8Token());
        supplierParam.put("page_index", 1);
        supplierParam.put("rows_per_page", 50);
        supplierParam.put("ds_sequence", dsSequence);
        supplierParam.put("name", revName);

        Map<String, Object> supplierMap = get("https://api.yonyouup.com/api/vendor/batch_get", supplierParam, null);
        if (!"0".equals(supplierMap.get("errcode").toString())) {
            log.info("获取供应商信息失败:{},{}", supplierMap.get("errmsg").toString(), revName);
            throw new RuntimeException("获取供应商信息失败:" + supplierMap.get("errmsg").toString() + "," + revName);
        }
        List<Map> vendorList = (List<Map>) supplierMap.get("vendor");
        String supplierCode = getString(vendorList.get(0).get("code"));

        //获取部门信息
        Map<String, Object> deptParam = new HashMap<>();
        deptParam.put("from_account", fromAccount);
        deptParam.put("to_account", toAccount);
        deptParam.put("app_key", u8AppKey);
        deptParam.put("token", getU8Token());
        deptParam.put("page_index", 1);
        deptParam.put("rows_per_page", 50);
        deptParam.put("ds_sequence", dsSequence);
        deptParam.put("name", deptName);

        Map<String, Object> deptMap = get("https://api.yonyouup.com/api/department/batch_get", deptParam, null);
        if (!"0".equals(deptMap.get("errcode").toString())) {
            log.info("获取部门信息失败:{},{}", deptMap.get("errmsg").toString(), deptName);
            throw new RuntimeException("获取部门信息失败:" + deptMap.get("errmsg").toString() + "," + deptName);
        }
        List<Map> deptList = (List<Map>) deptMap.get("department");
        String deptCode = getString(deptList.get(0).get("code"));

        Map resultMap = new HashMap();
        Map topInfoMap = new HashMap();

        //记账类型
        topInfoMap.put("voucher_type", voucherType);
        topInfoMap.put("enter", producer);  //制单人

        //credit entry信息   贷方
        Map infoMap = new HashMap();

        Map<String, Object> subjectParam = new HashMap<>();
        subjectParam.put("from_account", fromAccount);
        subjectParam.put("to_account", toAccount);
        subjectParam.put("app_key", u8AppKey);
        subjectParam.put("token", getU8Token());
        subjectParam.put("page_index", 1);
        subjectParam.put("rows_per_page", 50);
        subjectParam.put("ds_sequence", dsSequence);
        subjectParam.put("name", schPayAccount);

        Map<String, Object> subjectMap = get("https://api.yonyouup.com/api/code/batch_get", subjectParam, null);
        if (!"0".equals(subjectMap.get("errcode").toString())) {
            log.info("获取科目信息失败:{},{}", supplierMap.get("errmsg").toString(), schPayAccount);
            throw new RuntimeException("获取科目信息失败:" + supplierMap.get("errmsg").toString() + "," + schPayAccount);
        }
        List<Map> subjectList = (List<Map>) subjectMap.get("code");
        String subjectCode = getString(subjectList.get(0).get("code"));

        //贷方科目编码
        infoMap.put("account_code", subjectCode);
        //摘要
        infoMap.put("abstract", summary);
        //币种
        infoMap.put("currency", currency);

        //本币借方发生额*与本币贷方发生额不能同时为空
        infoMap.put("natural_credit_currency", applyAmount);

        List<Map> creditCashFlowList = new ArrayList<>();
        Map creditCashFlow = new HashMap();
        //币种
        creditCashFlow.put("cexch_name", currency);
        //本币借方发生额*与本币贷方发生额不能同时为空
        creditCashFlow.put("natural_credit_currency", applyAmount);
        //凭证类别字
        creditCashFlow.put("csign", voucherType);
        //科目编码 - 根据CBS 方，实际打款账户和公司来确定
        creditCashFlow.put("ccode", subjectCode);
        //贷方金额
        creditCashFlow.put("mc", applyAmount);
        //现金项目
        creditCashFlow.put("cCashItem", cashItem);
        //现金项目
        creditCashFlow.put("cash_item", cashItem);
        creditCashFlow.put("iyear", LocalDate.now().getYear());
        creditCashFlow.put("RowGuid", UUID.randomUUID().toString());

        creditCashFlowList.add(creditCashFlow);

        infoMap.put("cash_flow", creditCashFlowList);

        Map credit = new HashMap();
        credit.put("entry", infoMap);
        log.info("贷方credit:{}", credit);

        //debit entry信息   借方
        Map debit = new HashMap();
        List<Map> entryMapList = new ArrayList<>();
        List<Map> details = (List<Map>) formData.get("tableField_lxwwvggl");
        String taxesSummary = ""; // 税金摘要
        for (Map detail : details) {

            String productName = getString(detail.get("textField_lxwwvggm"));//货物或劳务名称
            String payType = getString(detail.get("selectField_m2sekyfa")).split("-")[0].split("\\（")[0];//支付类型

            taxesSummary = revName + "/" + productName;

            BigDecimal taxesAmount = new BigDecimal(getString(detail.get("numberField_lxwwvggo")));//金额

            Map entryMap = new HashMap();
            //科目编号
            subjectParam.put("name", payType);
            subjectMap = get("https://api.yonyouup.com/api/code/batch_get", subjectParam, null);

            if (!"0".equals(subjectMap.get("errcode").toString())) {
                log.info("获取科目信息失败:{},{}", supplierMap.get("errmsg").toString(), productName);
                throw new RuntimeException("获取科目信息失败:" + supplierMap.get("errmsg").toString() + "," + productName);
            }
            subjectList = (List<Map>) subjectMap.get("code");
            subjectCode = getString(subjectList.get(0).get("code"));
            //科目编号
            entryMap.put("account_code", subjectCode);
            //摘要
            entryMap.put("abstract", taxesSummary);
            //本币贷方发生额*与本币借方发生额不能同时为空
            entryMap.put("natural_debit_currency", taxesAmount);

            Map auxiliaryMap = new HashMap();
            auxiliaryMap.put("dept_id", deptCode);//部门
            auxiliaryMap.put("supplier_id", supplierCode);//供应商
            entryMap.put("auxiliary", auxiliaryMap);

            entryMapList.add(entryMap);
        }

        debit.put("entry", entryMapList);
        log.info("借方debit:{}", debit);

        topInfoMap.put("debit", debit);
        topInfoMap.put("credit", credit);
        resultMap.put("voucher", topInfoMap);
        log.info("voucher:{}", resultMap);

        return resultMap;
    }

    private Map process131(Map formData, int dsSequence, String createUser) {
        String schPayAccount = getString(formData.get("selectField_lxydz0ub"));//付款方账号

        String revName = getString(formData.get("textField_lxwwvggc"));//收款人名称

        String company = getString(formData.get("selectField_lxwwvggb"));//公司抬头

        String purpose = getString(formData.get("textField_lxydz0ug"));//用途

        String summary = revName + "/" + purpose;//摘要

        String deptName = getString(formData.get("textField_m2sekyf7"));//部门

        String currency = getString(formData.get("textField_m2sekyfi"));//币种

        List<String> sepVoucherCompany = Arrays.asList("宁波卡倍亿电气技术股份有限公司", "宁波卡倍亿新材料科技有限公司", "宁波卡倍亿铜线有限公司", "湖北卡倍亿电气技术有限公司");

        String voucherType = sepVoucherCompany.contains(company) ? "付" : "记";//凭证类型

        String applyAmount = getString(formData.get("numberField_lxwwvggi"));//本次支付金额（元）

        String producer = createUser;//制单人

        String cashItem = getString(formData.get("textField_m2sekyfg"));//现金项目

        //获取供应商信息
        Map<String, Object> supplierParam = new HashMap<>();
        supplierParam.put("from_account", fromAccount);
        supplierParam.put("to_account", toAccount);
        supplierParam.put("app_key", u8AppKey);
        supplierParam.put("token", getU8Token());
        supplierParam.put("page_index", 1);
        supplierParam.put("rows_per_page", 50);
        supplierParam.put("ds_sequence", dsSequence);
        supplierParam.put("name", revName);

        Map<String, Object> supplierMap = get("https://api.yonyouup.com/api/vendor/batch_get", supplierParam, null);
        if (!"0".equals(supplierMap.get("errcode").toString())) {
            log.info("获取供应商信息失败:{},{}", supplierMap.get("errmsg").toString(), revName);
            throw new RuntimeException("获取供应商信息失败:" + supplierMap.get("errmsg").toString() + "," + revName);
        }
        List<Map> vendorList = (List<Map>) supplierMap.get("vendor");
        String supplierCode = getString(vendorList.get(0).get("code"));

        //获取部门信息
        Map<String, Object> deptParam = new HashMap<>();
        deptParam.put("from_account", fromAccount);
        deptParam.put("to_account", toAccount);
        deptParam.put("app_key", u8AppKey);
        deptParam.put("token", getU8Token());
        deptParam.put("page_index", 1);
        deptParam.put("rows_per_page", 50);
        deptParam.put("ds_sequence", dsSequence);
        deptParam.put("name", deptName);

        Map<String, Object> deptMap = get("https://api.yonyouup.com/api/department/batch_get", deptParam, null);
        if (!"0".equals(deptMap.get("errcode").toString())) {
            log.info("获取部门信息失败:{},{}", deptMap.get("errmsg").toString(), deptName);
            throw new RuntimeException("获取部门信息失败:" + deptMap.get("errmsg").toString() + "," + deptName);
        }
        List<Map> deptList = (List<Map>) deptMap.get("department");
        String deptCode = getString(deptList.get(0).get("code"));

        Map resultMap = new HashMap();
        Map topInfoMap = new HashMap();

        //记账类型
        topInfoMap.put("voucher_type", voucherType);
        topInfoMap.put("enter", producer);  //制单人

        //credit entry信息   贷方
        Map infoMap = new HashMap();

        Map<String, Object> subjectParam = new HashMap<>();
        subjectParam.put("from_account", fromAccount);
        subjectParam.put("to_account", toAccount);
        subjectParam.put("app_key", u8AppKey);
        subjectParam.put("token", getU8Token());
        subjectParam.put("page_index", 1);
        subjectParam.put("rows_per_page", 50);
        subjectParam.put("ds_sequence", dsSequence);
        subjectParam.put("name", schPayAccount);

        Map<String, Object> subjectMap = get("https://api.yonyouup.com/api/code/batch_get", subjectParam, null);
        if (!"0".equals(subjectMap.get("errcode").toString())) {
            log.info("获取科目信息失败:{},{}", supplierMap.get("errmsg").toString(), schPayAccount);
            throw new RuntimeException("获取科目信息失败:" + supplierMap.get("errmsg").toString() + "," + schPayAccount);
        }
        List<Map> subjectList = (List<Map>) subjectMap.get("code");
        String subjectCode = getString(subjectList.get(0).get("code"));

        //贷方科目编码
        infoMap.put("account_code", subjectCode);
        //摘要
        infoMap.put("abstract", summary);
        //币种
        infoMap.put("currency", currency);

        //本币借方发生额*与本币贷方发生额不能同时为空
        infoMap.put("natural_credit_currency", applyAmount);

        Map auxiliary = new HashMap();

//        //项目档案-现流编号
        auxiliary.put("item_class", "05");
        infoMap.put("auxiliary", auxiliary);

        List<Map> creditCashFlowList = new ArrayList<>();
        Map creditCashFlow = new HashMap();
        //币种
        creditCashFlow.put("cexch_name", currency);
        //本币借方发生额*与本币贷方发生额不能同时为空
        creditCashFlow.put("natural_credit_currency", applyAmount);
        //凭证类别字
        creditCashFlow.put("csign", voucherType);

        creditCashFlow.put("ccode", subjectCode);
        //贷方金额
        creditCashFlow.put("mc", applyAmount);
        //现金项目
        creditCashFlow.put("cCashItem", cashItem);
        //现金项目
        creditCashFlow.put("cash_item", cashItem);
        creditCashFlow.put("iyear", LocalDate.now().getYear());
        creditCashFlow.put("RowGuid", UUID.randomUUID().toString());

        creditCashFlowList.add(creditCashFlow);
        infoMap.put("cash_flow", creditCashFlowList);

        Map credit = new HashMap();
        credit.put("entry", infoMap);
        log.info("贷方credit:{}", credit);
        //debit entry信息   借方
        Map debit = new HashMap();
        List<Map> entryMapList = new ArrayList<>();
        List<Map> details = (List<Map>) formData.get("tableField_lxwwvggl");
        BigDecimal taxesSum = BigDecimal.ZERO; // 税金总计
        String taxesSummary = ""; // 税金摘要
        for (Map detail : details) {
            String productName = getString(detail.get("textField_lxwwvggm"));//货物或劳务名称
            String payType = getString(detail.get("selectField_m2sekyfa")).split("-")[0].split("\\（")[0];//支付类型

            taxesSummary = revName + "/" + productName;

            BigDecimal taxesAmount = new BigDecimal(getString(detail.get("numberField_lxwwvggo")));//金额

            BigDecimal taxes = new BigDecimal(getString(detail.get("numberField_m2sekyf8")));//税金金额

            taxesSum = taxesSum.add(taxes);
            Map entryMap = new HashMap();
            //科目编号
            subjectParam.put("name", payType);
            subjectMap = get("https://api.yonyouup.com/api/code/batch_get", subjectParam, null);

            if (!"0".equals(subjectMap.get("errcode").toString())) {
                log.info("获取科目信息失败:{},{}", supplierMap.get("errmsg").toString(), productName);
                throw new RuntimeException("获取科目信息失败:" + supplierMap.get("errmsg").toString() + "," + productName);
            }
            subjectList = (List<Map>) subjectMap.get("code");
            subjectCode = getString(subjectList.get(0).get("code"));
            entryMap.put("account_code", subjectCode);

            //摘要
            entryMap.put("abstract", revName + "/" + productName);

            //本币贷方发生额*与本币借方发生额不能同时为空
            entryMap.put("natural_debit_currency", taxesAmount.subtract(taxes).toPlainString());

            Map auxiliaryMap = new HashMap();
            auxiliaryMap.put("dept_id", deptCode);//部门
            auxiliaryMap.put("supplier_id", supplierCode);//供应商
            entryMap.put("auxiliary", auxiliaryMap);

            entryMapList.add(entryMap);
        }
        // 添加税金科目
        if (taxesSum.compareTo(BigDecimal.ZERO) == 1) { // 税金总和大于0
            Map entryMap = new HashMap();

            subjectParam.put("name", "进项税额");
            subjectMap = get("https://api.yonyouup.com/api/code/batch_get", subjectParam, null);
            if (!"0".equals(subjectMap.get("errcode").toString())) {
                log.info("获取科目信息失败:{},{}", supplierMap.get("errmsg").toString(), "进项税额");
                throw new RuntimeException("获取科目信息失败:" + supplierMap.get("errmsg").toString() + "," + "进项税额");
            }
            subjectList = (List<Map>) subjectMap.get("code");
            subjectCode = getString(subjectList.get(0).get("code"));

            //科目编号
            entryMap.put("account_code", subjectCode); // 税金
            //摘要
            entryMap.put("abstract", taxesSummary);
            //本币贷方发生额*与本币借方发生额不能同时为空
            entryMap.put("natural_debit_currency", taxesSum.toPlainString());

            Map auxiliaryMap = new HashMap();
            auxiliaryMap.put("dept_id", deptCode);//部门
            auxiliaryMap.put("supplier_id", supplierCode);//供应商
            entryMap.put("auxiliary", auxiliaryMap);
            entryMapList.add(entryMap);
        }
        debit.put("entry", entryMapList);
        log.info("借方debit:{}", debit);

        topInfoMap.put("debit", debit);
        topInfoMap.put("credit", credit);
        resultMap.put("voucher", topInfoMap);
        log.info("voucher:{}", resultMap);

        return resultMap;
    }

    /**
     * 封装GET请求
     *
     * @param url     请求的URL
     * @param params  请求参数
     * @param headers 请求头
     * @return 响应内容
     */
    public static Map<String, Object> get(String url, Map<String, Object> params, Map<String, String> headers) {
        log.info("GET 请求url:{}, 请求参数:{}, 请求头:{}", url, params, headers);
        HttpRequest get = HttpUtil.createGet(url);
        if (params != null) {
            get.form(params);
        }

        if (headers != null) {
            get.addHeaders(headers);
        }
        HttpResponse response = get.execute();

        Map<String, Object> result = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            result = objectMapper.readValue(response.body(), new TypeReference<Map<String, Object>>() {
            });
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        log.info("响应结果: {}", result);
        return result;
    }

    /**
     * 封装POST请求
     *
     * @param url     请求的URL
     * @param params  请求参数
     * @param headers 请求头
     * @param body    请求体
     * @return 响应内容
     */
    public static Map<String, Object> post(String url, Map<String, Object> params, Map<String, String> headers, Map<String, Object> body) {
        log.info("POST 请求url:{}, 请求参数:{}, 请求头:{}, 请求体:{}", url, params, headers, body);

        String newUrl = url;
        StringBuffer param = new StringBuffer();
        for (String key : params.keySet()) {
            param.append(key + "=" + params.get(key).toString() + "&");
        }
        String paramStr = param.toString();
        paramStr = paramStr.substring(0, paramStr.length() - 1);
        if (newUrl.indexOf("?") >= 0) {
            newUrl += "&" + paramStr;
        } else {
            newUrl += "?" + paramStr;
        }


        HttpRequest request = HttpUtil.createPost(newUrl);
        /*if (params != null) {
            request.form(params);
        }*/
        if (headers != null) {
            request.addHeaders(headers);
        }
        if (body != null) {
            request.body(JSONUtil.toJsonStr(body), "application/json");
        }
        HttpResponse response = request.execute();
//        Map<String,Object> result = JSONUtil.toBean(response.body(), Map.class);
        Map<String, Object> result = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            result = objectMapper.readValue(response.body(), new TypeReference<Map<String, Object>>() {
            });
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        log.info("响应结果: {}", result);
        return result;
    }

    private String getU8Token() {
        String accessToken = UtilToken.get("u8-token");
        if (StringUtils.isNotBlank(accessToken)) {
            return accessToken;
        } else {
            Map<String, Object> param = new HashMap<>();
            param.put("from_account", fromAccount);
            param.put("app_key", u8AppKey);
            param.put("app_secret", u8AppSecret);

            Map<String, Object> result = get("https://api.yonyouup.com/system/token", param, null);
            Map token = (Map) result.get("token");
            String id = token.get("id").toString();
            log.info("u响应token, {}", id);
            UtilToken.put("u8-token", id, (int) token.get("expiresIn") * 1000L);

            return id;
        }
    }


    private String getString(Object obj) {
        return obj == null ? "" : obj.toString();
    }

    public String getTcAccessToken() {
        String accessToken = UtilToken.get("tc-invalid-token-dingtalk");
        if (StringUtils.isNotBlank(accessToken)) {
            return accessToken;
        } else {
            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();
            UtilToken.put("tc-invalid-token-dingtalk", accessToken, (long) r.getExpiresIn() * 1000L);
            return accessToken;
        }
    }

    @Override
    public String getWeekRange(String dateStr) {
        //获取所属周（每周六-下周五）
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date = LocalDate.parse(dateStr, inputFormatter);
        LocalDate startOfWeek;
        // 获取该周的周六（开始日期）
        startOfWeek = date.with(TemporalAdjusters.previousOrSame(DayOfWeek.SATURDAY));
        // 获取该周的周五（结束日期）
        LocalDate endOfWeek = startOfWeek.plusDays(6);

        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("MM.dd");

        return startOfWeek.format(outputFormatter) + "-" + endOfWeek.format(outputFormatter);
    }



    public boolean isNumber(String str) {
        try {
            Double.parseDouble(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    @Override
    public void puchCBS(Map map) {
        MDC.put("MDC_KEY_PID", "1002");
        if (Objects.isNull(map.get("formInstId"))) {
            log.info("formInstId不能为空！");
            return;
        }
        String formInstId = map.get("formInstId").toString();
        DDR_New ddrNew = ydClient.queryData(YDParam.builder()
                .formInstId(formInstId)
                .build(), YDConf.FORM_QUERY.retrieve_id);
        Map formData = ddrNew.getFormData();
        String type = formData.get(yidaConstants.getType()).toString();
        int dsSequence = (int) formData.get(yidaConstants.getDsSequence());
        String createUser = ((Map) ddrNew.getOriginator().get("name")).get("nameInChinese").toString();

//        Map data = new HashMap();
        switch (type) {
//            case "资金审批流程":
//                data = process131(formData, dsSequence, createUser);
//                break;
//            暂时只用采购付款
            case "采购部专用资金审批":
                purchaseToCbs(formData, dsSequence, createUser, formInstId);
                break;
            default:
                break;
        }


    }



    private Map purchaseToCbs(Map formData, int dsSequence, String createUser,String formInstId) {
        Map instMap = new HashMap();//单条推送消息
        List<Map> instMaps = new ArrayList<>();
        List<Map> itemMaps = new ArrayList<>();
        Map sendParam = new HashMap<>();
        Map itemMap = new HashMap<>();
        String title =createUser+"发起的"+UtilMap.getString(formData, yidaConstants.getType());//审批单标题
        String company = UtilMap.getString(formData, yidaConstants.getCompany());//公司抬头
        String schPayAccount = UtilMap.getString(formData, yidaConstants.getSchPayAccount());//付款账号
        String revName = UtilMap.getString(formData, yidaConstants.getRevName());//收款人名称
        String revAccount = UtilMap.getString(formData, yidaConstants.getRevAccount());//收款人账号
        String revBankName = UtilMap.getString(formData, yidaConstants.getRevBankName());//收方开户行
        String revCnapsCode = UtilMap.getString(formData, yidaConstants.getRevCnapsCode());//收方联行号
        String deptName = UtilMap.getString(formData, yidaConstants.getDeptName());//申请部门名称
        String orderCode = UtilMap.getString(formData, yidaConstants.getOrderCode());//合同（订单）名称编号
        String createUserName = createUser;//创建人名称
        String purpose = UtilMap.getString(formData, yidaConstants.getOrderCode());//付款理由
        List<Map> details = (List<Map>) formData.get("tableField_lxwwvggl");

        String pushddUserId = "";//推送消息的人员钉钉ID;如果是湖北公司填 邬丽红。惠州工厂选 曹建芳，其他推送出纳。
        instMap.put("currency", UtilMap.getString(formData, yidaConstants.getCurrency()));//Y	币种));
        instMap.put("erpApplyNum",  UtilMap.getString(formData, "serialNumberField_mhirnl56"));//Y	ERP方唯一编码，不能重复提交
        LocalDate expectTime = Instant.ofEpochMilli((Long) formData.get(yidaConstants.getExpectTime())).atZone(ZoneId.of("Asia/Shanghai")).toLocalDate();
        instMap.put("expectTime",expectTime);//N	期望支付日期
        instMap.put("payType", Constants.PAY_TYPE);//Y	结算方式
        instMap.put("purpose", purpose);//Y	用途
        instMap.put("remark", "约定付款日期：" +expectTime );//N	备注- 放科目信息
        instMap.put("revAccount", revAccount);//Y	收款人账号
        instMap.put("revBankName", revBankName);//Y	收方开户行
        instMap.put("revCnapsCode", revCnapsCode);//N	收方联行号
        instMap.put("revName", revName);//Y	收款人名称
        instMap.put("company", company);//所属公司
        instMap.put("schPayAccount", schPayAccount);//N	付款账号
        instMap.put("displayUnitCode", UtilMap.getString(formData, yidaConstants.getDisplayUnitCode()));//N	单位编码（前端展示）
        instMap.put("summary", revName + "/" + purpose);//N	摘要
        instMap.put("applicatName", revName);//报销人/客户名称
        instMap.put("applyAmount", UtilMap.getString(formData, yidaConstants.getApplyAmount()));//Y	申请金额
        instMap.put("deptName", deptName);//报销部门
        instMap.put("createUserName", createUserName);//创建人
        instMap.put("orderCode", orderCode);//合同（订单）名称编号
        switch (company) {
            case "湖北卡倍亿电气技术有限公司":
                pushddUserId = "17053211829435311";//邬丽红
                break;
            case "惠州卡倍亿电气技术有限公司":
                pushddUserId = "16478233143628393";//曹建芳
                break;
            default:
                pushddUserId = "193247096439759670";//出纳
                break;
        }
        instMap.put("erpExtend1", pushddUserId);//erp备用字段，钉钉ID 号，如果是湖北公司填 邬丽红。惠州工厂选 曹建芳，其他推送出纳。
        //循环处理明细
        for (Map detail : details) {
            log.info("item={}", detail);
            itemMap = new HashMap<>();
            String productName = getString(detail.get("textField_lxwwvggm"));
            BigDecimal taxesAmount = new BigDecimal(getString(detail.get("numberField_lxwwvggo")));//金额
            String payType = getString(detail.get("selectField_mhoirjv5"));//支付类型
//            JSONArray json = new JSONArray(payType);
//            String subjectName = json.getJSONObject(0).getString("title");
            itemMap.put("singleAmount", taxesAmount);//金额
            itemMap.put("singleSubjectName", payType);//科目
            itemMap.put("digest", revName + "/" + productName);//摘要
            itemMaps.add(itemMap);
        }
        instMap.put("details", itemMaps);//费用明细
        instMaps.add(instMap);
        log.info("当前推送的审批单为：【{}】。推送内容为：{}", title, instMaps);
        sendParam.put("reqBOS", instMaps);
        OperatingRecordEntity entity = new OperatingRecordEntity();
        entity.setProducer(UtilMap.getString(formData, yidaConstants.getProducter()));//制单人
        entity.setDebit(revName);//收款方
        entity.setCredit(company);//付款方
        entity.setName(title);
        entity.setErpApplyNum(formInstId);//ERP方唯一编码，不能重复提交
        entity.setContent(JSON.toJSONString(instMap));
        entity.setType("6");//1：资金审批；2：员工费用报销；3：差旅费报销；4：往来款付款；6：采购专用资金审批；7：其他付款单；8:现金收款单；11：票据收款单；12：票据付款单
        entity.setPid(formInstId);
        cbsUtil.erpImport(sendParam, entity);
        return null;
    }

    @Override
    public void schedulePaymentCBSToU8(OperatingRecordEntity entity) {
        //获取cbs付款排程单
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("erpApplyNum", entity.getErpApplyNum());
            String url = CBSConstants.ADDRESS+"/openapi/payment/openapi/v1/erp-query";
            JSONObject jsonObject = ToSendCBS.toSend(url, map);
            //{"msg":"ok","code":"0","data":[{"revAccount":"755915678910202","purpose":"用途","busNum":"FK202406130009","revName":"企业网银新20161078","revBankName":"招商银行深圳分行","schPayAccount":"755915711310102","applyAmount":8.00,"applyUser":"U777608077749891072","payType":"JSFS001","unitCode":"UC230911000001","statusName":"已付款","currency":"10","payBankType":"CMB","extContent":{},"paymentSchedulingApplyResDTOS":[{"revAccount":"755915678910202","busNum":"PA00039224061300016","payAccountSeq":"ACT0000000015","procStatus":"2","unitCode":"0001,00010002,000101,000102,0002,A0001,MK0002,MK0003,MK0004,MK0005,MK0006,MK0010,MK0012,MK0014,MK0015,MK0016,MK0017,MK0018,MK0019,MK0020,MK0025,MK0026,MK0027,MK0028,MK0029,MK0030,MK0031,MK0032,MK0033,MK0034,MK0036,MK0038,MK0039,MK0040,MK0041,MK0042,MK0043,MK0044,MK0045,MK0046,MK0047,MK0048,MK0049,MK0050,MK0051,MK0052,MK0053,MK0054,MK0055,MK8888,UC230719000001,UC230719000002,UC230911000001,UC230912000001,UC231213000001,UC231213000002,UC240119000001,UC240607000001,UC240607000002,ZDC2022,ZHD","inputType":"0","id":1446039455399941,"payBankType":"CMB","busType":"202","bankInterfaceType":"CMBZL","accountFlag":"0","createByName":"周慧丹","unitName":"宁波分行测试环境,周晗,宁波分行演示环境01,宁波分行演示环境02,汪金宇,胡钱波测试单位,中国实业宁波分公司,中国实业天津分公司,中国实业浙江分公司,中国实业广东分公司,中国实业深圳分公司,中国实业东莞分公司,中国实业广州分公司,中国实业北京分公司,中国实业山东分公司,中国实业贵州分公司,中国实业广西分公司,中国实业甘肃分公司,中国实业四川分公司,中国实业成都分公司,中国实业湖南分公司,中国实业株洲分公司,中国实业衡阳分公司,中国实业长沙分公司,中国实业湖北分公司,中国实业云南分公司,中国实业新疆分公司,中国实业江西分公司,中国实业河北分公司,中国实业唐山分公司,中国实业承德分公司,中国实业福建分公司,中国实业福州物流分公司,中国实业厦门物流分公司,中国实业莆田物流分公司,中国实业江苏分公司,中国实业南京分公司,中国实业无锡分公司,中国实业苏州分公司,中国实业常州分公司,中国实业徐州分公司,中国实业扬州分公司,中国实业南通分公司,中国实业河南分公司,中国实业郑州分公司,中国实业洛阳分公司,中国实业开封分公司,中国实业南阳分公司,中国实业周口分公司,中国实业新能源公司,招行汇出汇款付款账户,招行汇出汇款收款账户,宁波分行ERP对接1,宁波分行ERP对接3,杰博人力测试,均胜汽车安全系统（临港）有限公司,浙江润禾有机硅新材料有限公司,宁波博威2,宁波博威,周大厨集团,宁波分行ERP对接2","payOrgName":"宁波分行ERP对接1","revProvince":"广东省","operaterOrgCode":"0001,00010002,000101,000102,0002,A0001,MK0002,MK0003,MK0004,MK0005,MK0006,MK0010,MK0012,MK0014,MK0015,MK0016,MK0017,MK0018,MK0019,MK0020,MK0025,MK0026,MK0027,MK0028,MK0029,MK0030,MK0031,MK0032,MK0033,MK0034,MK0036,MK0038,MK0039,MK0040,MK0041,MK0042,MK0043,MK0044,MK0045,MK0046,MK0047,MK0048,MK0049,MK0050,MK0051,MK0052,MK0053,MK0054,MK0055,MK8888,UC230719000001,UC230719000002,UC230911000001,UC230912000001,UC231213000001,UC231213000002,UC240119000001,UC240607000001,UC240607000002,ZDC2022,ZHD","referenceNum":"202406131845000047012","bankExtend2":"104","displayUnitCode":"0001,00010002,000101,000102,0002,A0001,MK0002,MK0003,MK0004,MK0005,MK0006,MK0010,MK0012,MK0014,MK0015,MK0016,MK0017,MK0018,MK0019,MK0020,MK0025,MK0026,MK0027,MK0028,MK0029,MK0030,MK0031,MK0032,MK0033,MK0034,MK0036,MK0038,MK0039,MK0040,MK0041,MK0042,MK0043,MK0044,MK0045,MK0046,MK0047,MK0048,MK0049,MK0050,MK0051,MK0052,MK0053,MK0054,MK0055,MK8888,HCHKFK,HCHKSK,1000,0020,JBRL01,580,ZHD001,30001,12001,ZDC2022,02","payAccountName":"企业网银新20161392","revBankType":"CMB","status":"4","purpose":"用途","cityFlag":"0","bankExtend6":"54","revBankName":"招商银行深圳分行","revCity":"深圳市","operaterOrgName":"宁波分行测试环境,周晗,宁波分行演示环境01,宁波分行演示环境02,汪金宇,胡钱波测试单位,中国实业宁波分公司,中国实业天津分公司,中国实业浙江分公司,中国实业广东分公司,中国实业深圳分公司,中国实业东莞分公司,中国实业广州分公司,中国实业北京分公司,中国实业山东分公司,中国实业贵州分公司,中国实业广西分公司,中国实业甘肃分公司,中国实业四川分公司,中国实业成都分公司,中国实业湖南分公司,中国实业株洲分公司,中国实业衡阳分公司,中国实业长沙分公司,中国实业湖北分公司,中国实业云南分公司,中国实业新疆分公司,中国实业江西分公司,中国实业河北分公司,中国实业唐山分公司,中国实业承德分公司,中国实业福建分公司,中国实业福州物流分公司,中国实业厦门物流分公司,中国实业莆田物流分公司,中国实业江苏分公司,中国实业南京分公司,中国实业无锡分公司,中国实业苏州分公司,中国实业常州分公司,中国实业徐州分公司,中国实业扬州分公司,中国实业南通分公司,中国实业河南分公司,中国实业郑州分公司,中国实业洛阳分公司,中国实业开封分公司,中国实业南阳分公司,中国实业周口分公司,中国实业新能源公司,招行汇出汇款付款账户,招行汇出汇款收款账户,宁波分行ERP对接1,宁波分行ERP对接3,杰博人力测试,均胜汽车安全系统（临港）有限公司,浙江润禾有机硅新材料有限公司,宁波博威2,宁波博威,周大厨集团,宁波分行ERP对接2","isDeleted":0,"projectCode":"NB000392","urgentTag":"0","currency":"10","summary":"费用项目","amount":8.00,"updateTime":1718276202000,"procInstId":"1446039456022536","revAccountName":"企业网银新20161078","payAccount":"755915711310102","payBankName":"招商银行深圳分行","cnapsCode":"308584000013","bankVersion":"U","errorMsg":"银行处理成功","createBy":"U726177183173128192","createTime":1718276134000,"payOrgCode":"UC230911000001","payChannel":"1","payStatus":"g","payDate":1718276202000}],"summary":"费用项目","unitName":"宁波分行ERP对接1","revCnapsCode":"308584000013","applyUserName":"ERP对接","unpaidAmount":0.00,"createTime":1718275599000,"erpApplyNum":"202406131845000047012","transitAmount":0.00,"displayUnitCode":"1000","payAccountName":"企业网银新20161392","paidAmount":8.00,"status":"7"}]}
//            "status":"7" "statusName":"已付款"
            if ("0".equals(jsonObject.getString("code")) && "7".equals(JSONObject.parseObject(jsonObject.getJSONArray("data").get(0).toString()).getString("status"))) {
                log.info("存在需要推送是数据jsonObject：{}", jsonObject.getString("data"));
                //更新数据数据状态
                entity.setResContent(jsonObject.toJSONString());
                entity.setStatus("3");
                recordMapper.updateById(entity);
                //开始把凭证推送U8
                insertU8(entity);
            } else {
                log.info("本订单无需推送-erpApplyNum：{}", entity.getErpApplyNum());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
//    ==============================等待U9切换，凭证推送U9==========================
    public void insertU8(OperatingRecordEntity entity) {
        return;
    }





}
