package com.malk.huagao.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.malk.huagao.entity.KdYdDelivery;
import com.malk.huagao.entity.KdYdDeliveryDetail;
import com.malk.huagao.entity.KdYdTransfer;
import com.malk.huagao.entity.KdYdTransferDetail;
import com.malk.huagao.mapper.*;
import com.malk.huagao.service.IKdYdTransferService;
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.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author LQY
 * @since 2025-11-12
 */
@Service
@Slf4j
public class KdYdTransferServiceImpl extends ServiceImpl<KdYdTransferMapper, KdYdTransfer> implements IKdYdTransferService {
    @Autowired
    private YDClient ydClient;
    @Autowired
    private KdYdTransferMapper kdYdTransferMapper;
    @Autowired
    private KdYdTransferDetailMapper kdYdTransferDetailMapper;

    @Override
    public void insertTransfer(Map map) {
        MDC.put("MDC_KEY_PID", "1003");
        String formInstId = UtilMap.getString(map, "formInstId");
        String type = UtilMap.getString(map, "type");

        if ("3".equals(type)) {
            String bm = UtilMap.getString(map, "bm");
            KdYdTransfer kdYdTransfer = new KdYdTransfer();
            kdYdTransfer.setOperationType("3");
            kdYdTransfer.setSyncStatus("0");
            kdYdTransferMapper.update(kdYdTransfer, new LambdaQueryWrapper<KdYdTransfer>().eq(KdYdTransfer::getDjbh, bm));
            return; // 或者根据你的业务逻辑返回相应的结果
        }
        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_mhubzsa5");
        LocalDateTime rq = parseTimestamp(UtilMap.getString(formData, "dateField_mhubzsab"));
        String kh = UtilMap.getString(formData, "textField_mhubzsas");
        String dchzlx = UtilMap.getString(formData, "selectField_mhubzsa7");
        String djbh = UtilMap.getString(formData, "serialNumberField_mhubzsa4");
        String ywlx = UtilMap.getString(formData, "textField_mhubzsa6");
        String xsy = UtilMap.getString(formData, "employeeField_mhubzsa8").replace("[\"", "").replace("\"]", "").trim();
        String dcbm = UtilMap.getString(formData, "departmentSelectField_mhubzsae").replace("[\"", "").replace("\"]", "").trim();
        String drbm = UtilMap.getString(formData, "departmentSelectField_mhubzsad").replace("[\"", "").replace("\"]", "").trim();
        String drhzlx = UtilMap.getString(formData, "selectField_mhubzsa9");
        String dbfx = UtilMap.getString(formData, "selectField_mhubzsaa");
        String dbdlx = UtilMap.getString(formData, "selectField_mhubzsac");
        String dchz = UtilMap.getString(formData, "textField_mhubzsat");
        String hdfs = UtilMap.getString(formData, "selectField_mhubzsah");
        String ysfs = UtilMap.getString(formData, "selectField_mhubzsai");
        String kdgs = UtilMap.getString(formData, "selectField_mhubzsar");
        String fkfs = UtilMap.getString(formData, "selectField_mhubzsag");

        List<Map> tableField = (List<Map>) formData.get("tableField_mhubzsau");
        KdYdTransfer kdYdTransfer = new KdYdTransfer();
        kdYdTransfer.setDjlx(djlx);
        kdYdTransfer.setRq(rq);
        kdYdTransfer.setKh(kh);
        kdYdTransfer.setDjbh(djbh);
        kdYdTransfer.setSyncStatus("0");
        kdYdTransfer.setOperationType("1");
        kdYdTransfer.setYsfs(ysfs);
        kdYdTransfer.setHdfs(hdfs);
        kdYdTransfer.setKdgs(kdgs);
        kdYdTransfer.setFkfs(fkfs);
        kdYdTransfer.setDchzlx(dchzlx);
        kdYdTransfer.setDchz(dchz);
        kdYdTransfer.setDchzlx(dchzlx);
        kdYdTransfer.setDbfx(dbfx);
        kdYdTransfer.setDbdlx(dbdlx);
        kdYdTransfer.setDcbm(dcbm);
        kdYdTransfer.setDrbm(drbm);
        kdYdTransfer.setDrhzlx(drhzlx);
        kdYdTransfer.setYwlx(ywlx);
        kdYdTransfer.setCgy(xsy);

        if ("2".equals(type)) {
            kdYdTransfer.setOperationType(type);
            kdYdTransferMapper.update(kdYdTransfer, new LambdaQueryWrapper<KdYdTransfer>().eq(KdYdTransfer::getDjbh, djbh));
        } else {
            kdYdTransferMapper.insert(kdYdTransfer);
        }

        Long id = kdYdTransfer.getId();
        int count = 1;
        for (Map item : tableField) {
            String wlbm = safeGetString(item, "textField_mhubzsav");
            String wlmc = safeGetString(item, "textField_mhubzsaw");
            String ggxh = safeGetString(item, "textField_mhubzsax");
            String dw = safeGetString(item, "textField_mhubzsay");
            int dbsl = parseInt(safeGetString(item, "numberField_mhubzsaz"), 0); // 如果为空或格式错误，返回 0
            String ph = safeGetString(item, "textField_mhubzsb0");
            String dcck = safeGetString(item, "textField_mhubzsb1");
            String dcckzt = safeGetString(item, "textField_mhubzsb5");
            String dccw = safeGetString(item, "textField_mhubzsb2");
            String drck = safeGetString(item, "textField_mhubzsb3");
            String drckzt = safeGetString(item, "textField_mhubzsb6");
            String drcw = safeGetString(item, "textField_mhubzsb4");
            KdYdTransferDetail kdYdTransferDetail = new KdYdTransferDetail();
            kdYdTransferDetail.setTransferId(id);
            kdYdTransferDetail.setWlbm(wlbm);
            kdYdTransferDetail.setWlmc(wlmc);
            kdYdTransferDetail.setGgxh(ggxh);
            kdYdTransferDetail.setDetailId(count);
            kdYdTransferDetail.setGgxh(ggxh);
            kdYdTransferDetail.setDw(dw);
            kdYdTransferDetail.setDbsl(dbsl);
            kdYdTransferDetail.setPh(ph);
            kdYdTransferDetail.setDcck(dcck);
            kdYdTransferDetail.setDcckzt(dcckzt);
            kdYdTransferDetail.setDccw(dccw);
            kdYdTransferDetail.setDrck(drck);
            kdYdTransferDetail.setDrckzt(drckzt);
            kdYdTransferDetail.setDrcw(drcw);
            kdYdTransferDetail.setSyncStatus("0");
            kdYdTransferDetail.setOperationType("1");
            if ("2".equals(type) || "3".equals(type)) {
                kdYdTransferDetail.setOperationType(type);
                kdYdTransferDetailMapper.update(kdYdTransferDetail, new LambdaQueryWrapper<KdYdTransferDetail>()
                        .eq(KdYdTransferDetail::getWlbm, wlbm)
                        .eq(KdYdTransferDetail::getTransferId, id));
            } else {
                kdYdTransferDetailMapper.insert(kdYdTransferDetail);
            }

            count++;
//save(kdYdDeliveryDetail);
        }
//        ydClient.operateData(
//                YDParam.builder()
//                        .formInstanceId(formInstId)
//                        .updateFormDataJson(JSONObject.toJSONString(UtilMap.map("textField_mgrqnxmm", id)))
//                        .useLatestVersion(true).build(), YDConf.FORM_OPERATION.update);
    }

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

        try {
            MDC.put("MDC_KEY_PID", "1003"); // 设置不同的 PID 以便区分日志
            List<Map<String, Object>> kdYdTransferDels = UtilMap.getList(json, "data");
            String action = UtilMap.getString(json, "action");
            String table = UtilMap.getString(json, "table");

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

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

                        List<Map> list1 = (List<Map>) ydClient.queryData(YDParam.builder()
                                .formUuid("FORM-F1B2BA2AF310476C88F4756F4DB50667VXDR")
                                .searchCondition(JSONObject.toJSONString(UtilMap.map("textField_miptelgc", 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-F1B2BA2AF310476C88F4756F4DB50667VXDR")
                                .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>> kdYdTransfers = UtilMap.getList(json, "data");
            if (kdYdTransfers.isEmpty()) {
                log.info("【调拨单同步任务】无需要同步的数据，结束");
                result.put("code", "200");
                result.put("msg", "无需要同步的数据");
                result.put("data", new HashMap<>());
                return result;
            }

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

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

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

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

                    // 检查明细数据是否存在
                    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<>();
                    List<Map<String, Object>> tableListxlh = new ArrayList<>();

                    // 处理明细数据
                    for (Map<String, Object> detailItem : tableListData) {
                        HashMap<String, String> tablemap = new HashMap<>();
                        tablemap.put("textField_mhubzsav", String.valueOf(detailItem.get("wlbm")));
                        tablemap.put("textField_mhubzsaw", String.valueOf(detailItem.get("wlmc")));
                        tablemap.put("textField_mqudgs70", String.valueOf(detailItem.get("jx")));
                        tablemap.put("textField_mhubzsax", String.valueOf(detailItem.get("ggxh")));
                        tablemap.put("textField_mhubzsay", String.valueOf(detailItem.get("dw")));
                        tablemap.put("textareaField_mjshnw4c", String.valueOf(detailItem.get("kddh")));
                        tablemap.put("numberField_mhubzsaz", safeConvertBigDecimalToString(detailItem.get("dbsl")));
                        tablemap.put("textField_mhubzsb0", String.valueOf(detailItem.get("ph")));
                        tablemap.put("textField_mhubzsb1", String.valueOf(detailItem.get("dcck")));
                        tablemap.put("textField_mhubzsb5", String.valueOf(detailItem.get("dcckzt")));
                        tablemap.put("textField_mhubzsb2", String.valueOf(detailItem.get("dccw")));
                        tablemap.put("textField_mhubzsb3", String.valueOf(detailItem.get("drck")));
                        tablemap.put("textField_mhubzsb6", String.valueOf(detailItem.get("drckzt")));
                        tablemap.put("textField_mhubzsb4", String.valueOf(detailItem.get("drcw")));

                        // 处理序列号明细
                        String xlhjh = String.valueOf(detailItem.get("xlh"));
                        if (xlhjh != null && !xlhjh.trim().isEmpty() && !"null".equals(xlhjh)) {
                            List<Map<String, Object>> currentXlhList = Arrays.stream(xlhjh.split(","))
                                    .map(String::trim)
                                    .filter(item -> !item.isEmpty())
                                    .map(item -> {
                                        Map<String, Object> xlhMap = new HashMap<>();
                                        xlhMap.put("textField_mf6a0h6w", item);
                                        xlhMap.put("textField_mjqst61l", String.valueOf(detailItem.get("wlbm")));
                                        xlhMap.put("textField_mjqst61m", String.valueOf(detailItem.get("ggxh")));
                                        return xlhMap;
                                    })
                                    .collect(Collectors.toList());

                            tableListxlh.addAll(currentXlhList);
                            tableList.add(tablemap);
                        }
                    }

                    // 查询关联表单数据
                    String xsddbh = String.valueOf(transferItem.get("ddbh"));
                    String fhtzdbh = String.valueOf(transferItem.get("fhtzdbh"));
                    String ddformInstanceId = null;
                    String fhdformInstanceId = null;
                    String ddbh = null;
                    String fhdbh = null;
                    String jydate = null;
                    String ghrq = null;
                    String jyyy = null;
                    String jtyy = null;
                    String xsy = null;
                    String khxypj = null;
                    String fj = null;

                    try {
                        log.debug("开始查询订单数据: xsddbh={}", xsddbh);

                        // 查询订单数据
                        if (xsddbh != null && !"null".equals(xsddbh) && !xsddbh.trim().isEmpty()) {
                            List<Map<String, Object>> ddlist = (List<Map<String, Object>>) 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) continue;

                                    Object serialObj = khformData.get("textField_mjs6fuwo");
                                    String serialStr = serialObj != null ? serialObj.toString() : null;

                                    if (xsddbh.equals(serialStr)) {
                                        ddformInstanceId = safeToString(khitem.get("formInstanceId"));
                                        ddbh = serialStr;
                                        jydate = safeToString(khformData.get("dateField_mdya1lom"));
                                        ghrq = safeToString(khformData.get("dateField_meqpbxsj"));
                                        jyyy = safeToString(khformData.get("multiSelectField_meqpbxsc"));
                                        jtyy = safeToString(khformData.get("textareaField_meqpbxsd"));
                                        khxypj = safeToString(khformData.get("selectField_mewirdx4"));
                                        xsy = safeToString(khformData.get("employeeField_mejowmng_id"));
                                        fj = safeToString(khformData.get("attachmentField_mfoqcctz"));
                                        break;
                                    }
                                }
                            }
                        }

                        // 查询发货单数据
                        if (fhtzdbh != null && !"null".equals(fhtzdbh) && !fhtzdbh.trim().isEmpty()) {
                            List<Map<String, Object>> fhdlist = (List<Map<String, Object>>) ydClient.queryData(
                                    YDParam.builder()
                                            .formUuid("FORM-FAE2575E112644ED914CAB4FEC9309F32AVR")
                                            .searchCondition(JSON.toJSONString(UtilMap.map("serialNumberField_mheazm7w", fhtzdbh)))
                                            .build(),
                                    YDConf.FORM_QUERY.retrieve_list_all
                            ).getData();

                            if (fhdlist != null && !fhdlist.isEmpty()) {
                                for (Map<String, Object> fhditem : fhdlist) {
                                    Map<String, Object> fhdformData = (Map<String, Object>) fhditem.get("formData");
                                    if (fhdformData == null) continue;

                                    Object serialObj = fhdformData.get("serialNumberField_mheazm7w");
                                    String serialStr = serialObj != null ? serialObj.toString() : null;

                                    if (fhtzdbh.equals(serialStr)) {
                                        fhdformInstanceId = safeToString(fhditem.get("formInstanceId"));
                                        fhdbh = serialStr;
                                        break;
                                    }
                                }
                            }
                        }

                    } catch (Exception e) {
                        log.error("查询关联表单数据异常: xsddbh={}, fhtzdbh={}", xsddbh, fhtzdbh, e);
                    }

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

                    // 添加关联表单数据
                    if (ddbh != null && ddformInstanceId != null) {
                        updateMap.put("associationFormField_mhubzsaf",
                                Collections.singletonList(getddAss(ddbh, ddformInstanceId)));
                    }
                    if (fhdbh != null && fhdformInstanceId != null) {
                        updateMap.put("associationFormField_mjzervdt",
                                Collections.singletonList(getfhdAss(fhdbh, fhdformInstanceId)));
                    }

                    // 添加订单相关字段（如果所有字段都存在）
                    if (jydate != null && ghrq != null && jyyy != null && jtyy != null
                            && xsy != null && khxypj != null) {
                        updateMap.put("dateField_mdya1lom", jydate);
                        updateMap.put("dateField_meqpbxsj", ghrq);
                        updateMap.put("multiSelectField_meqpbxsc", jyyy);
                        updateMap.put("textareaField_meqpbxsd", jtyy);
                        updateMap.put("employeeField_mejowmng", xsy);
                        updateMap.put("selectField_mewirdx4", khxypj);
                        updateMap.put("attachmentField_mfoqcctz", fj);
                    }

                    // 添加主表字段
                    updateMap.put("textField_mjzervdu", fhtzdbh);
                    updateMap.put("textField_miquh5zj", ddformInstanceId);
                    updateMap.put("selectField_mhubzsa5", String.valueOf(transferItem.get("djlx")));
                    updateMap.put("textField_mhubzsas", String.valueOf(transferItem.get("kh")));
                    updateMap.put("textField_miptelgh", String.valueOf(transferItem.get("ddbh")));
                    updateMap.put("textField_miptelgc", djbh);
                    updateMap.put("textField_miptelgd", String.valueOf(transferItem.get("cgy")));
                    updateMap.put("selectField_mhubzsa7", String.valueOf(transferItem.get("dchzlx")));
                    updateMap.put("textField_mhubzsa6", String.valueOf(transferItem.get("ywlx")));
                    // 处理日期字段
                    Object rq = transferItem.get("rq");
                            updateMap.put("dateField_mhubzsab", safeConvertDateTimeToString(rq));
                    updateMap.put("selectField_mhubzsa9", String.valueOf(transferItem.get("drhzlx")));
                    updateMap.put("selectField_mhubzsaa", String.valueOf(transferItem.get("dbfx")));
                    updateMap.put("selectField_mhubzsac", String.valueOf(transferItem.get("dbdlx")));
                    updateMap.put("textField_miptelge", String.valueOf(transferItem.get("dcbm")));
                    updateMap.put("textField_miptelgf", String.valueOf(transferItem.get("dchz")));
                    updateMap.put("textField_miptelgg", String.valueOf(transferItem.get("drbm")));
                    updateMap.put("selectField_mhubzsah", String.valueOf(transferItem.get("hdfs")));
                    updateMap.put("selectField_mhubzsai", String.valueOf(transferItem.get("ysfs")));
                    updateMap.put("selectField_mhubzsar", String.valueOf(transferItem.get("kdgs")));
                    updateMap.put("selectField_mhubzsag", String.valueOf(transferItem.get("fkfs")));

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

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

                    log.info("调拨单同步成功: djbh={}, transferId={}", djbh, transferId);

                } catch (Exception e) {
                    log.error("同步单条调拨单数据异常: djbh={}", transferItem.get("djbh"), e);
                    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", kdYdTransfers.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("【调拨单同步任务】完成，共处理{}条数据，成功{}条，失败{}条",
                    kdYdTransfers.size(), successCount, failCount);

        } catch (Exception e) {
            log.error("调拨单同步任务执行异常", e);
            result.put("code", "500");
            result.put("msg", "系统异常：" + e.getMessage());
            result.put("data", new HashMap<>());
        }
        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 为字符串
    private String safeConvertBigDecimalToString(Object value) {
        if (value == null) {
            return "";
        }
        if (value instanceof BigDecimal) {
            return ((BigDecimal) value).toPlainString();
        }
        return String.valueOf(value);
    }

    // 辅助方法 - 安全转换日期时间为字符串
    private String safeConvertDateTimeToString(Object value) {
        if (value == null) {
            return "";
        }
        if (value instanceof LocalDateTime) {
            return ((LocalDateTime) value).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
        }
        return String.valueOf(value);
    }

    // 辅助方法 - 安全转换为字符串
    private String safeToString(Object obj) {
        return obj != null ? obj.toString() : null;
    }

    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 Object getddAss(String title, String id) {
        return UtilMap.map("appType, formUuid, formType, instanceId, title, subTitle", "APP_VQDMMWS6OR1VHL8VMFD3", "FORM-B62CAE3075CE4098B17BB86C90FFA21C9B7C", "receipt", id, title, "");
    }
    private Object getfhdAss(String title, String id) {
        return UtilMap.map("appType, formUuid, formType, instanceId, title, subTitle", "APP_VQDMMWS6OR1VHL8VMFD3", "FORM-FAE2575E112644ED914CAB4FEC9309F32AVR", "receipt", id, title, "");
    }
    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);
    }
}
