package com.malk.huagao.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.malk.huagao.entity.KdYdOutbound;
import com.malk.huagao.entity.KdYdOutboundDetail;
import com.malk.huagao.entity.KdYdReceivable;
import com.malk.huagao.entity.KdYdReceivableDetail;
import com.malk.huagao.mapper.KdYdOutboundDetailMapper;
import com.malk.huagao.mapper.KdYdOutboundMapper;
import com.malk.huagao.mapper.KdYdReceivableDetailMapper;
import com.malk.huagao.mapper.KdYdReceivableMapper;
import com.malk.huagao.service.IKdYdReceivableService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.aliwork.YDClient;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author LQY
 * @since 2025-10-16
 */
@Service
@Slf4j
public class KdYdReceivableServiceImpl extends ServiceImpl<KdYdReceivableMapper, KdYdReceivable> implements IKdYdReceivableService {
    @Autowired
    private YDClient ydClient;
    @Autowired
    private KdYdReceivableMapper kdYdReceivableMapper;
    @Autowired
    private KdYdReceivableDetailMapper kdYdReceivableDetailMapper;

    @Override
    public void insertkdYdReceivable(Map map) {
        MDC.put("MDC_KEY_PID", "1003");
        String formInstId = UtilMap.getString(map, "formInstId");
        DDR_New ddrNew = ydClient.queryData(YDParam.builder()
                .formInstId(formInstId)
                .build(), YDConf.FORM_QUERY.retrieve_id);
        Map formData = ddrNew.getFormData();

        String djlx = UtilMap.getString(formData, "selectField_mg3a0th4");
        long outboundId = UtilMap.getLong(formData, "textField_mgrsdayq");
//            long deliceryId = 6L;
        String kh = UtilMap.getString(formData, "textField_mejmml3k");
        String bb = UtilMap.getString(formData, "selectField_mg3fuqvn");
        String sktj = UtilMap.getString(formData, "selectField_mev13l3r");
        String xsy = UtilMap.getString(formData, "employeeField_mejmtic9").replace("[\"", "").replace("\"]", "").trim();
        String xsbm = UtilMap.getString(formData, "textField_krnn5bmr");
        String xslx = UtilMap.getString(formData, "selectField_mejowmnc");
        String khsx = UtilMap.getString(formData, "selectField_megi74y8");
        String bz = UtilMap.getString(formData, "textareaField_mg3a0tgx");
        String zdzkjestr = UtilMap.getString(formData, "numberField_mejmtica");
        BigDecimal zdzkje = toBigDecimal(zdzkjestr);


        List<Map> tableField = (List<Map>) formData.get("tableField_mf6el3zx");
        KdYdReceivable kdYdReceivable = new KdYdReceivable();
        kdYdReceivable.setDjlx(djlx);
//        kdYdReceivable.setOutboundId(outboundId);
        kdYdReceivable.setBb(bb);
        kdYdReceivable.setKh(kh);
        kdYdReceivable.setSktj(sktj);
        kdYdReceivable.setXsbm(xsbm);
        kdYdReceivable.setXslx(xslx);
        kdYdReceivable.setKhsx(khsx);
        kdYdReceivable.setXsy(xsy);
//        kdYdReceivable.setZdzkje(zdzkje);
        kdYdReceivable.setBz(bz);
        kdYdReceivable.setForminstid(formInstId);
        kdYdReceivableMapper.insert(kdYdReceivable);

        Long id = kdYdReceivable.getId();
        for (Map item : tableField) {
            String wlbm = safeGetString(item, "textField_mf6el3zy");
            String wlmc = safeGetString(item, "textField_mf6el3zz");
            String ggxh = safeGetString(item, "textField_mejmtic5");
            String jjdw = safeGetString(item, "textField_mf6el400");
            String ssxl = safeGetString(item, "selectField_mejnamfm");
            BigDecimal dj = toBigDecimal(safeGetString(item, "numberField_mf6el402"));
            BigDecimal hsdj = toBigDecimal(safeGetString(item, "numberField_mejmticb"));
            BigDecimal sl = toBigDecimal(safeGetString(item, "numberField_mf6el403"));
            BigDecimal se = toBigDecimal(safeGetString(item, "numberField_mf6el406"));
//                BigDecimal je = toBigDecimal(safeGetString(item, "numberField_mg34txh8"));
            BigDecimal jshj = toBigDecimal(safeGetString(item, "numberField_mejmtic7"));
            String kcdw = safeGetString(item, "textField_mf6el409");
            String ph = safeGetString(item, "textField_mf6el408");
            BigDecimal jjsl = toBigDecimal(safeGetString(item, "numberField_mejmtic6"));
            BigDecimal zkl = toBigDecimal(safeGetString(item, "numberField_mf6el404"));
            BigDecimal bhsje = toBigDecimal(safeGetString(item, "numberField_mejmticc"));
            BigDecimal zke = toBigDecimal(safeGetString(item, "numberField_mf6el405"));
            BigDecimal kcsl = toBigDecimal(safeGetString(item, "numberField_mf6el40a"));
            String sfzp = safeGetString(item, "radioField_mejnamfn");
            String gg = safeGetString(item, "textField_mf6el40b");
            BigDecimal tc = toBigDecimal(safeGetString(item, "numberField_mf6el40c"));
            BigDecimal jjjbsl = toBigDecimal(safeGetString(item, "numberField_mf6el407"));
            String jx = safeGetString(item, "textField_mf6el40d");
            KdYdReceivableDetail kdYdReceivableDetail = new KdYdReceivableDetail();
            kdYdReceivableDetail.setReceivableId(id);
            kdYdReceivableDetail.setWlbm(wlbm);
            kdYdReceivableDetail.setWlmc(wlmc);
            kdYdReceivableDetail.setGgxh(ggxh);
            kdYdReceivableDetail.setJjdw(jjdw);
            kdYdReceivableDetail.setSsxl(ssxl);
            kdYdReceivableDetail.setDj(dj);
            kdYdReceivableDetail.setHsdj(hsdj);
            kdYdReceivableDetail.setSl(sl);
            kdYdReceivableDetail.setSe(se);
            kdYdReceivableDetail.setJe(jshj);
            kdYdReceivableDetail.setJjsl(jjsl);
            kdYdReceivableDetail.setZkl(zkl);
            kdYdReceivableDetail.setBhsje(bhsje);
            kdYdReceivableDetail.setZke(zke);
            kdYdReceivableDetail.setKcsl(kcsl);
            kdYdReceivableDetail.setSfzp(sfzp);
            kdYdReceivableDetail.setGg(gg);
            kdYdReceivableDetail.setTc(tc);
            kdYdReceivableDetail.setJjjbsl(jjjbsl);
            kdYdReceivableDetail.setJx(jx);
            kdYdReceivableDetail.setKcdw(kcdw);
            kdYdReceivableDetail.setPh(ph);
            kdYdReceivableDetailMapper.insert(kdYdReceivableDetail);


        }
        ydClient.operateData(
                YDParam.builder()
                        .formInstanceId(formInstId)
                        .updateFormDataJson(JSONObject.toJSONString(UtilMap.map("textField_mgt4w4ip", id)))
                        .useLatestVersion(true).build(), YDConf.FORM_OPERATION.update);
    }


    @Override
    public Map<String, Object>   insertkdYdReceivable1(Map json) {
        HashMap<String, Object> result = new HashMap<>();

        try {
            MDC.put("MDC_KEY_PID", "1003");
            List<Map<String, Object>> kdYdReceivableDels = UtilMap.getList(json, "data");
            String action = UtilMap.getString(json, "action");
            String table = UtilMap.getString(json, "table");

            // 批量删除处理
            if (!kdYdReceivableDels.isEmpty() && "del".equals(action) && "KD_YD_RECEIVABLE".equals(table)) {
                log.info("开始处理应收单删除操作，共{}条数据", kdYdReceivableDels.size());
                ArrayList<String> deleteList = new ArrayList<>();
                int deleteSuccessCount = 0;

                for (Map<String, Object> item : kdYdReceivableDels) {
                    try {
                        String djbh = String.valueOf(item.get("djbh"));

                        List<Map> list1 = (List<Map>) ydClient.queryData(YDParam.builder()
                                .formUuid("FORM-4E1CE4550339494A9BE5498FB119FF2E9ERU")
                                .searchCondition(JSONObject.toJSONString(UtilMap.map("textField_mg3a0tgs", djbh)))
                                .build(), YDConf.FORM_QUERY.retrieve_list_all).getData();

                        if (list1 != null && !list1.isEmpty()) {
                            for (Map map : list1) {
                                String formInstanceId = UtilMap.getString(map, "formInstanceId");
                                if (formInstanceId != null) {
                                    deleteList.add(formInstanceId);
                                }
                            }
                            deleteSuccessCount++;
                        } else {
                            log.warn("未找到对应的应收单数据: djbh={}", djbh);
                        }

                    } catch (Exception e) {
                        log.error("删除应收单数据查询异常: djbh={}", item.get("djbh"), e);
                    }
                }

                // 执行批量删除
                if (!deleteList.isEmpty()) {
                    try {
                        ydClient.operateData(YDParam.builder()
                                .formUuid("FORM-4E1CE4550339494A9BE5498FB119FF2E9ERU")
                                .formInstanceIdList(deleteList)
                                .build(), YDConf.FORM_OPERATION.delete_batch);
                        log.info("应收单批量删除完成，共删除{}条数据", deleteList.size());
                    } catch (Exception e) {
                        log.error("应收单批量删除操作异常", e);
                    }
                }

                // 返回删除结果
                result.put("code", "200");
                result.put("msg", "删除成功，共删除" + deleteList.size() + "条数据");
                result.put("data", new HashMap<String, Object>() {{
                    put("deletedCount", deleteList.size());
                    put("deletedIds", deleteList);
                }});
                return result;
            } else if ("del".equals(action)) {
                log.info("【应收单删除任务】无需要删除的数据");
                result.put("code", "200");
                result.put("msg", "无需要删除的数据");
                result.put("data", new HashMap<>());
                return result;
            }

            // 同步新增/更新数据
            List<Map<String, Object>> kdYdReceivables = UtilMap.getList(json, "data");
            if (kdYdReceivables.isEmpty()) {
                log.info("【应收单同步任务】无需要同步的数据，结束");
                result.put("code", "200");
                result.put("msg", "无需要同步的数据");
                result.put("data", new HashMap<>());
                return result;
            }

            log.info("【应收单同步任务】开始同步，共{}条数据", kdYdReceivables.size());

            List<Map<String, Object>> operationResults = new ArrayList<>();
            int successCount = 0;
            int failCount = 0;

            for (Map<String, Object> receivableItem : kdYdReceivables) {
                Map<String, Object> singleResult = new HashMap<>();

                try {
                    String djbh = String.valueOf(receivableItem.get("djbh"));
                    List<Map<String, Object>> tableListData = UtilMap.getList(receivableItem, "tableList");
                    List<Map<String, Object>> paymentListData = UtilMap.getList(receivableItem, "paymentList");
//                    String  receivableId = UtilMap.getString(receivableItem, "receivableId");

                    // 检查应收单明细数据是否存在
                    if (tableListData == null || tableListData.isEmpty()) {
                        log.warn("应收单明细数据为空: djbh={}", djbh);
                        singleResult.put("errorMsg", "明细数据为空");
                        singleResult.put("status", "fail");
                        failCount++;
                        operationResults.add(singleResult);
                        continue;
                    }

                    // 处理应收单明细

                    ArrayList<Object> tableList = new ArrayList<>();
                    for (Map<String, Object> detailItem : tableListData) {
                        HashMap<Object, Object> tablemap = new HashMap<>();

                        // 使用辅助方法安全获取和格式化数据
                        tablemap.put("textField_mf6el3zy", String.valueOf(detailItem.get("wlbm")));
                        tablemap.put("textField_mf6el3zz", String.valueOf(detailItem.get("wlmc")));
                        tablemap.put("textField_mejmtic5", String.valueOf(detailItem.get("ggxh")));
                        tablemap.put("textField_mf6el400", String.valueOf(detailItem.get("jjdw")));
                        tablemap.put("textField_mhllijwo", String.valueOf(detailItem.get("ssxl")));
                        tablemap.put("numberField_mf6el402", safeFormatBigDecimal(detailItem.get("dj")));
                        tablemap.put("numberField_mejmticb", safeFormatBigDecimal(detailItem.get("hsdj")));
                        tablemap.put("numberField_mf6el403", safeFormatBigDecimal(detailItem.get("sl")));
                        tablemap.put("numberField_mejmtic7", safeFormatBigDecimal(detailItem.get("jshj1")));
                        tablemap.put("textField_mf6el409", String.valueOf(detailItem.get("kcdw")));
                        tablemap.put("textField_mf6el408", String.valueOf(detailItem.get("ph")));
                        tablemap.put("numberField_mf6el406", safeFormatBigDecimal(detailItem.get("se")));
                        tablemap.put("numberField_mejmtic6", safeFormatBigDecimal(detailItem.get("jjsl")));
                        tablemap.put("numberField_mf6el404", safeFormatBigDecimal(detailItem.get("zkl")));
                        tablemap.put("numberField_mejmticc", safeFormatBigDecimal(detailItem.get("bhsje")));
                        tablemap.put("numberField_mf6el407", safeFormatBigDecimal(detailItem.get("jjjbsl")));
                        tablemap.put("numberField_mf6el40a", safeFormatBigDecimal(detailItem.get("kcsl")));
                        tablemap.put("radioField_mejnamfn", String.valueOf(detailItem.get("sfzp")));
                        tablemap.put("numberField_mf6el40c", safeFormatBigDecimal(detailItem.get("tc")));
                        tablemap.put("textField_mf6el40d", String.valueOf(detailItem.get("jx")));
                        tablemap.put("textField_mf6el40b", String.valueOf(detailItem.get("gg")));
                        tablemap.put("numberField_mf6el405", safeFormatBigDecimal(detailItem.get("zke")));


                        tableList.add(tablemap);
                    }

                    // 处理收款计划
                    ArrayList<Object> tableListPay = new ArrayList<>();
                    if (paymentListData != null && !paymentListData.isEmpty()) {
                        for (Map<String, Object> paymentItem : paymentListData) {
                            HashMap<Object, Object> tablemap1 = new HashMap<>();

                            // 处理日期字段
                            Object endTimeObj = paymentItem.get("endTime");
                            tablemap1.put("dateField_mhiui6v9", safeConvertDateTimeToString(endTimeObj));
                            tablemap1.put("textField_mhiui6va", String.valueOf(paymentItem.get("xsddh")));
                            tablemap1.put("textField_mqt5s81f", String.valueOf(paymentItem.get("uuid")));
                            tablemap1.put("numberField_mhiui6v8", safeFormatBigDecimal(paymentItem.get("ysje")));
                            tablemap1.put("numberField_mrczs2dk", safeFormatBigDecimal(paymentItem.get("wsje")));
                            tablemap1.put("numberField_mhiui6v6", safeFormatBigDecimal(paymentItem.get("ysbl")));
                            tablemap1.put("numberField_mhiui6vb", safeFormatBigDecimal(paymentItem.get("ysjebwb")));
                            tablemap1.put("numberField_mhjy9hzj", safeFormatBigDecimal(paymentItem.get("stkdglje")));
                            tableListPay.add(tablemap1);
                        }
                    }

                    // 查询关联的出库单数据
                    String ckddjbh = String.valueOf(receivableItem.get("ckddjbh"));
                    String ckdformInstanceId = null;
                    String ckdbh = null;

                    if (ckddjbh != null && !"null".equals(ckddjbh) && !ckddjbh.trim().isEmpty()) {
                        try {
                            List<Map> ddlist = (List<Map>) ydClient.queryData(
                                    YDParam.builder()
                                            .formUuid("FORM-AADBCDA8126F41A0ADDEE3353828583192M8")
                                            .searchCondition(JSON.toJSONString(UtilMap.map("textField_mg34txgm", ckddjbh)))
                                            .build(),
                                    YDConf.FORM_QUERY.retrieve_list_all
                            ).getData();

                            if (ddlist != null && !ddlist.isEmpty()) {
                                for (Map<String, Object> khitem : ddlist) {
                                    Map<String, Object> khformData = (Map<String, Object>) khitem.get("formData");
                                    if (khformData != null) {
                                        Object ckddjbhObj = khformData.get("textField_mg34txgm");
                                        String ckddjbhStr = ckddjbhObj != null ? ckddjbhObj.toString() : null;

                                        if (ckddjbh.equals(ckddjbhStr)) {
                                            ckdformInstanceId = (String) khitem.get("formInstanceId");
                                            ckdbh = ckddjbhStr;
                                            break;
                                        }
                                    }
                                }
                            }
                        } catch (Exception e) {
                            log.error("查询出库单数据异常: ckddjbh={}", ckddjbh, e);
                        }
                    }

                    // 构建主表数据
                    HashMap<Object, Object> updateData = new HashMap<>();
                    updateData.put("tableField_mf6el3zx", tableList);

                    // 添加关联表单数据
                    if (ckdbh != null && ckdformInstanceId != null) {
                        updateData.put("associationFormField_mejmtick",
                                Arrays.asList(getysdAss(ckdbh, ckdformInstanceId)));
                    }

                    updateData.put("tableField_mhiui6v5", tableListPay);
                    updateData.put("textField_mg3a0tgs", djbh);
                    updateData.put("textField_mj15q3dk", ckddjbh);
                    updateData.put("selectField_mg3a0th4", String.valueOf(receivableItem.get("djlx")));
                    updateData.put("selectField_mev13l3r", String.valueOf(receivableItem.get("sktj")));

                    // 处理主表日期字段
                    Object endTimeObj1 = receivableItem.get("endTime");
                        updateData.put("dateField_mejmtic3", safeConvertDateTimeToString(endTimeObj1));

                    Object businessTimeObj = receivableItem.get("businessTime");
                        updateData.put("dateField_mejmtic2", safeConvertDateTimeToString(endTimeObj1));
                    updateData.put("numberField_mejmtic8", safeFormatBigDecimal(receivableItem.get("jshj")));
                    updateData.put("textField_mejmml3k", String.valueOf(receivableItem.get("kh")));
                    updateData.put("textField_mhjy9hzh", String.valueOf(receivableItem.get("xsy")));
                    updateData.put("selectField_mejowmnc", String.valueOf(receivableItem.get("xslx")));
                    updateData.put("selectField_megi74y8", String.valueOf(receivableItem.get("khsx")));
                    updateData.put("textField_krnn5bmr", String.valueOf(receivableItem.get("xsbm")));
                    updateData.put("textField_mhjy9hzi", String.valueOf(receivableItem.get("lzlx")));
                    updateData.put("textareaField_mg3a0tgx", String.valueOf(receivableItem.get("bz")));
                    updateData.put("selectField_mg3fuqvn", String.valueOf(receivableItem.get("bb")));

                    // 执行同步操作
                    Object operationResult = ydClient.operateData(YDParam.builder()
                            .formUuid("FORM-4E1CE4550339494A9BE5498FB119FF2E9ERU")
                            .searchCondition(JSONObject.toJSONString(UtilMap.map("textField_mg3a0tgs", djbh)))
                            .noExecuteExpression(false)
                            .formDataJson(JSONObject.toJSONString(updateData))
                            .build(), YDConf.FORM_OPERATION.upsert
                    );

                    // 记录成功结果
                    singleResult.put("operationResult", operationResult);
                    singleResult.put("status", "success");
                    singleResult.put("ckdformInstanceId", ckdformInstanceId);
                    singleResult.put("tableCount", tableList.size());
                    singleResult.put("paymentCount", tableListPay.size());
                    successCount++;

//                    log.info("应收单同步成功: djbh={}, receivableId={}", djbh, receivableId);

                } catch (Exception e) {
                    String djbh = String.valueOf(receivableItem.get("djbh"));
                    log.error("同步应收单数据异常: djbh={}", djbh, e);

                    singleResult.put("djbh", djbh);
                    singleResult.put("errorMsg", e.getMessage());
                    singleResult.put("status", "fail");
                    failCount++;
                }

                operationResults.add(singleResult);
            }

            // 构建返回结果
            Map<String, Object> data = new HashMap<>();
            data.put("operationResults", operationResults);
            data.put("totalCount", kdYdReceivables.size());
            data.put("successCount", successCount);
            data.put("failCount", failCount);

            result.put("code", failCount == 0 ? "200" : "300");
            result.put("msg", "操作完成，成功" + successCount + "条，失败" + failCount + "条");
            result.put("data", data);

            log.info("【应收单同步任务】完成，共处理{}条数据，成功{}条，失败{}条",
                    kdYdReceivables.size(), successCount, failCount);

        } catch (Exception e) {
            log.error("应收单同步任务执行异常", e);
            result.put("code", "500");
            result.put("msg", "系统异常：" + e.getMessage());
            result.put("data", new HashMap<>());
        } finally {
            MDC.remove("MDC_KEY_PID");
        }

        return result;
    }

    @Override
    public Map<String, Object> insertkdYdpayment(Map json) {

        HashMap<String, Object> result = new HashMap<>();

        try {
            MDC.put("MDC_KEY_PID", "1003");
            List<Map<String, Object>> kdYdPaymentReceiptDels = UtilMap.getList(json, "data");
            String action = UtilMap.getString(json, "action");
            String table = UtilMap.getString(json, "table");

            // 批量删除处理
            if (!kdYdPaymentReceiptDels.isEmpty() && "del".equals(action) && "KD_YD_PAYMENT_RECEIPT".equals(table)) {
                log.info("开始处理收款单删除操作，共{}条数据", kdYdPaymentReceiptDels.size());
                ArrayList<String> deleteList = new ArrayList<>();
                int deleteSuccessCount = 0;

                for (Map<String, Object> item : kdYdPaymentReceiptDels) {
                    try {
                        String djbh = String.valueOf(item.get("djbh"));

                        List<Map> list1 = (List<Map>) ydClient.queryData(YDParam.builder()
                                .formUuid("FORM-0569C06E47074C2981ADEEAFCE083EDAK5AM")
                                .searchCondition(JSONObject.toJSONString(UtilMap.map("textField_mh9woamt", djbh)))
                                .build(), YDConf.FORM_QUERY.retrieve_list_all).getData();

                        if (list1 != null && !list1.isEmpty()) {
                            for (Map map : list1) {
                                String formInstanceId = UtilMap.getString(map, "formInstanceId");
                                if (formInstanceId != null) {
                                    deleteList.add(formInstanceId);
                                }
                            }
                            deleteSuccessCount++;
                        } else {
                            log.warn("未找到对应的收款单数据: djbh={}", djbh);
                        }

                    } catch (Exception e) {
                        log.error("删除收款单数据查询异常: djbh={}", item.get("djbh"), e);
                    }
                }

                // 执行批量删除
                if (!deleteList.isEmpty()) {
                    try {
                        ydClient.operateData(YDParam.builder()
                                .formUuid("FORM-0569C06E47074C2981ADEEAFCE083EDAK5AM")
                                .formInstanceIdList(deleteList)
                                .build(), YDConf.FORM_OPERATION.delete_batch);
                        log.info("收款单批量删除完成，共删除{}条数据", deleteList.size());
                    } catch (Exception e) {
                        log.error("收款单批量删除操作异常", e);
                    }
                }

                // 返回删除结果
                result.put("code", "200");
                result.put("msg", "删除成功，共删除" + deleteList.size() + "条数据");
                result.put("data", new HashMap<String, Object>() {{
                    put("deletedCount", deleteList.size());
                    put("deletedIds", deleteList);
                }});
                return result;
            } else if ("del".equals(action)) {
                log.info("【收款单删除任务】无需要删除的数据");
                result.put("code", "200");
                result.put("msg", "无需要删除的数据");
                result.put("data", new HashMap<>());
                return result;
            }

            // 同步新增/更新数据
            List<Map<String, Object>> kdYdPaymentReceipts = UtilMap.getList(json, "data");
            if (kdYdPaymentReceipts.isEmpty()) {
                log.info("【收款单同步任务】无需要同步的数据，结束");
                result.put("code", "200");
                result.put("msg", "无需要同步的数据");
                result.put("data", new HashMap<>());
                return result;
            }

            log.info("【收款单同步任务】开始同步，共{}条数据", kdYdPaymentReceipts.size());

            List<Map<String, Object>> operationResults = new ArrayList<>();
            int successCount = 0;
            int failCount = 0;

            for (Map<String, Object> paymentItem : kdYdPaymentReceipts) {
                Map<String, Object> singleResult = new HashMap<>();

                try {
                    String djbh = String.valueOf(paymentItem.get("djbh"));
                    List<Map<String, Object>> tableListData = UtilMap.getList(paymentItem, "tableList");
//                    String  paymentReceiptId = UtilMap.getString(paymentItem, "paymentReceiptId");

                    // 检查明细数据是否存在
                    if (tableListData == null || tableListData.isEmpty()) {
                        log.warn("收款单明细数据为空: djbh={}", djbh);
                        singleResult.put("errorMsg", "明细数据为空");
                        singleResult.put("status", "fail");
                        failCount++;
                        operationResults.add(singleResult);
                        continue;
                    }

                    // 处理收款单明细
                    ArrayList<Object> tableList = new ArrayList<>();
                    for (Map<String, Object> detailItem : tableListData) {
                        HashMap<String, String> tablemap = new HashMap<>();
                        tablemap.put("textField_mh9woanr", String.valueOf(detailItem.get("jsfs")));
                        tablemap.put("textField_mh9woans", String.valueOf(detailItem.get("skyt")));
                        tablemap.put("textField_mh9woant", String.valueOf(detailItem.get("ysxmlx")));
                        tablemap.put("textField_mh9woanu", String.valueOf(detailItem.get("ysxsdd")));
                        tablemap.put("numberField_mh9woanv", safeFormatBigDecimalToString(detailItem.get("ysje")));
                        tablemap.put("numberField_mh9woanw", safeFormatBigDecimalToString(detailItem.get("sxf")));
                        tablemap.put("textField_mhmr1ecr", String.valueOf(detailItem.get("cdk")));
                        tablemap.put("textField_mh9woany", String.valueOf(detailItem.get("wfyhzh")));
                        tablemap.put("textField_mh9woao2", String.valueOf(detailItem.get("xsddh")));
                        tablemap.put("textField_mh9woao1", String.valueOf(detailItem.get("fyxm")));
                        tablemap.put("numberField_mh9woanz", safeFormatBigDecimalToString(detailItem.get("ssje")));
                        tablemap.put("numberField_mh9woao0", safeFormatBigDecimalToString(detailItem.get("zhje")));
                        tableList.add(tablemap);
                    }

                    // 查询关联的订单数据
                    String xsddbh = String.valueOf(paymentItem.get("xsddbh"));
                    String ddformInstanceId = null;
                    String ddbh = null;

                    if (xsddbh != null && !"null".equals(xsddbh) && !xsddbh.trim().isEmpty()) {
                        try {
                            log.debug("开始查询订单数据: xsddbh={}", xsddbh);

                            List<Map> ddlist = (List<Map>) ydClient.queryData(
                                    YDParam.builder()
                                            .formUuid("FORM-B62CAE3075CE4098B17BB86C90FFA21C9B7C")
                                            .searchCondition(JSON.toJSONString(UtilMap.map("textField_mjs6fuwo", xsddbh)))
                                            .build(),
                                    YDConf.FORM_QUERY.retrieve_list_all
                            ).getData();

                            if (ddlist != null && !ddlist.isEmpty()) {
                                for (Map<String, Object> khitem : ddlist) {
                                    Map<String, Object> khformData = (Map<String, Object>) khitem.get("formData");
                                    if (khformData != null) {
                                        Object xsddbhObj = khformData.get("textField_mjs6fuwo");
                                        String xsddbhStr = xsddbhObj != null ? xsddbhObj.toString() : null;

                                        if (xsddbh.equals(xsddbhStr)) {
                                            ddformInstanceId = (String) khitem.get("formInstanceId");
                                            ddbh = xsddbhStr;
                                            break;
                                        }
                                    }
                                }
                            }
                        } catch (Exception e) {
                            log.error("查询订单数据异常: xsddbh={}", xsddbh, e);
                        }
                    }

                    // 构建更新数据
                    HashMap<Object, Object> updateMap = new HashMap<>();
                    updateMap.put("tableField_mh9woanl", tableList);

                    // 添加关联表单数据
                    if (ddbh != null && ddformInstanceId != null) {
                        updateMap.put("associationFormField_mh9woamy",
                                Arrays.asList(getddAss(ddbh, ddformInstanceId)));
                    }

                    // 添加主表字段
                    updateMap.put("textField_mh9woanm", String.valueOf(paymentItem.get("djlx")));
                    updateMap.put("textField_mh9woann", String.valueOf(paymentItem.get("fkdwlx")));
                    updateMap.put("textField_mh9woamt", djbh);
                    updateMap.put("textField_mh9woamz", String.valueOf(paymentItem.get("skgld")));
                    updateMap.put("textField_mh9woano", String.valueOf(paymentItem.get("bb")));
                    updateMap.put("textField_mqt5wtda", xsddbh);

                    // 处理日期字段
                    Object ywrqObj = paymentItem.get("ywrq");
                                updateMap.put("dateField_mh9woan5", safeConvertDateTimeToString(ywrqObj));


                    updateMap.put("textField_mh9woanp", String.valueOf(paymentItem.get("wldwlx")));
                    updateMap.put("textField_mh9woanq", String.valueOf(paymentItem.get("wldw")));
                    updateMap.put("numberField_mh9woanc", safeFormatBigDecimalToString(paymentItem.get("ysje")));
                    updateMap.put("numberField_mh9woand", safeFormatBigDecimalToString(paymentItem.get("ssje")));
                    updateMap.put("textField_mhjxv2tf", String.valueOf(paymentItem.get("xsy")));
                    updateMap.put("textField_mhjxv2tg", String.valueOf(paymentItem.get("xsbm")));
                    updateMap.put("textareaField_mh9woank", String.valueOf(paymentItem.get("bz")));

                    // 执行同步操作
                    Object operationResult = ydClient.operateData(YDParam.builder()
                            .formUuid("FORM-0569C06E47074C2981ADEEAFCE083EDAK5AM")
                            .appType("APP_VQDMMWS6OR1VHL8VMFD3")
                            .systemToken("XE766X81JHKXK4Z27SYOI86CPCLQ3J1LV7ODMH2")
                            .noExecuteExpression(false)
                            .searchCondition(JSONObject.toJSONString(UtilMap.map("textField_mh9woamt", djbh)))
                            .formDataJson(JSONObject.toJSONString(updateMap))
                            .build(), YDConf.FORM_OPERATION.upsert);

                    // 记录成功结果
                    singleResult.put("operationResult", operationResult);
                    singleResult.put("status", "success");
                    singleResult.put("ddformInstanceId", ddformInstanceId);
                    successCount++;

//                    log.info("收款单同步成功: djbh={}, paymentReceiptId={}", djbh, paymentReceiptId);

                } catch (Exception e) {
                    String djbh = String.valueOf(paymentItem.get("djbh"));
                    log.error("同步收款单数据异常: djbh={}", djbh, e);

                    singleResult.put("djbh", djbh);
                    singleResult.put("errorMsg", e.getMessage());
                    singleResult.put("status", "fail");
                    failCount++;
                }

                operationResults.add(singleResult);
            }

            // 构建返回结果
            Map<String, Object> data = new HashMap<>();
            data.put("operationResults", operationResults);
            data.put("totalCount", kdYdPaymentReceipts.size());
            data.put("successCount", successCount);
            data.put("failCount", failCount);

            result.put("code", failCount == 0 ? "200" : "300");
            result.put("msg", "操作完成，成功" + successCount + "条，失败" + failCount + "条");
            result.put("data", data);

            log.info("【收款单同步任务】完成，共处理{}条数据，成功{}条，失败{}条",
                    kdYdPaymentReceipts.size(), successCount, failCount);

        } catch (Exception e) {
            log.error("收款单同步任务执行异常", e);
            result.put("code", "500");
            result.put("msg", "系统异常：" + e.getMessage());
            result.put("data", new HashMap<>());
        } finally {
            MDC.remove("MDC_KEY_PID");
        }

        return result;
    }
    private String safeConvertDateTimeToString(Object dateTime) {
        try {
            if (dateTime instanceof LocalDateTime) {
                return String.valueOf(((LocalDateTime) dateTime)
                        .atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
            }
            if (dateTime instanceof Date) return String.valueOf(((Date) dateTime).getTime());
            if (dateTime instanceof Long) return String.valueOf(dateTime);
            if (dateTime instanceof Integer) {
                long t = ((Integer) dateTime).longValue();
                return String.valueOf(t < 10000000000L ? t * 1000L : t);
            }
            if (dateTime instanceof String) {
                String s = ((String) dateTime).trim();
                if (s.matches("\\d+")) {
                    return String.valueOf(s.length() == 10 ? Long.parseLong(s) * 1000L : Long.parseLong(s));
                }
            }
            return "";
        } catch (Exception e) { return ""; }
    }
    // 辅助方法 - 安全格式化 BigDecimal 为字符串（保留2位小数）
    private String safeFormatBigDecimalToString(Object value) {
        if (value == null) {
            return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP).toString();
        }
        try {
            if (value instanceof BigDecimal) {
                return ((BigDecimal) value).setScale(2, RoundingMode.HALF_UP).toString();
            } else if (value instanceof Number) {
                return BigDecimal.valueOf(((Number) value).doubleValue())
                        .setScale(2, RoundingMode.HALF_UP).toString();
            } else if (value instanceof String) {
                String strVal = ((String) value).trim();
                if (strVal.isEmpty() || "null".equalsIgnoreCase(strVal)) {
                    return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP).toString();
                }
                return new BigDecimal(strVal).setScale(2, RoundingMode.HALF_UP).toString();
            }
            return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP).toString();
        } catch (Exception e) {
            log.warn("格式化BigDecimal数据异常: value={}", value, e);
            return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP).toString();
        }
    }

    // 获取订单关联数据
    private Object getddAss(String title, String id) {
        return UtilMap.map("appType, formUuid, formType, instanceId, title, subTitle", "APP_VQDMMWS6OR1VHL8VMFD3", "FORM-B62CAE3075CE4098B17BB86C90FFA21C9B7C", "receipt", id, title, "");
    }

    // 辅助方法 - 安全格式化 BigDecimal 数据（保留2位小数）
    private BigDecimal safeFormatBigDecimal(Object value) {
        if (value == null) {
            return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        }
        try {
            if (value instanceof BigDecimal) {
                return ((BigDecimal) value).setScale(2, RoundingMode.HALF_UP);
            } else if (value instanceof Number) {
                return BigDecimal.valueOf(((Number) value).doubleValue()).setScale(2, RoundingMode.HALF_UP);
            } else if (value instanceof String) {
                String strVal = ((String) value).trim();
                if (strVal.isEmpty() || "null".equalsIgnoreCase(strVal)) {
                    return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
                }
                return new BigDecimal(strVal).setScale(2, RoundingMode.HALF_UP);
            }
            return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        } catch (Exception e) {
            log.warn("格式化BigDecimal数据异常: value={}", value, e);
            return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        }
    }

    // 获取应收单关联数据
    private Object getysdAss(String title, String id) {
        return UtilMap.map("appType, formUuid, formType, instanceId, title, subTitle", "APP_VQDMMWS6OR1VHL8VMFD3", "FORM-AADBCDA8126F41A0ADDEE3353828583192M8", "receipt", id, title, "");
    }

    private static LocalDateTime parseTimestamp(String timestampStr) {
        if (timestampStr == null || timestampStr.trim().isEmpty()) return null;
        try {
            long timestamp = Long.parseLong(timestampStr.trim());
            return LocalDateTime.ofInstant(
                    Instant.ofEpochMilli(timestamp),
                    ZoneId.systemDefault()
            );
        } catch (NumberFormatException e) {
            return null;
        }
    }

    private static int parseInt(String str, int defaultValue) {
        if (str == null || str.trim().isEmpty()) {
            return defaultValue;
        }
        try {
            return Integer.parseInt(str.trim());
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }

    private String safeGetString(Map formData, String key) {
        Object val = formData.get(key);
        return val == null ? "" : String.valueOf(val);
    }

    public static BigDecimal toBigDecimal(String str) {
        if (str == null || str.trim().isEmpty()) {
            return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        }
        try {
            return new BigDecimal(str.trim())
                    .setScale(2, RoundingMode.HALF_UP);
        } catch (NumberFormatException e) {
            // 返回默认值而不是抛出异常，避免程序中断
            return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        }
    }

    /**
     * 重载方法，支持Number类型输入
     */
    public static BigDecimal toBigDecimal(Number number) {
        if (number == null) {
            return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        }
        return new BigDecimal(number.toString())
                .setScale(2, RoundingMode.HALF_UP);
    }
}
