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.KdYdOutbound;
import com.malk.huagao.entity.KdYdOutboundDetail;
import com.malk.huagao.mapper.KdYdDeliveryDetailMapper;
import com.malk.huagao.mapper.KdYdDeliveryMapper;
import com.malk.huagao.mapper.KdYdOutboundDetailMapper;
import com.malk.huagao.mapper.KdYdOutboundMapper;
import com.malk.huagao.service.IKdYdOutboundService;
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.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LQY
 * @since 2025-10-15
 */
@Service
@Slf4j
public class KdYdOutboundServiceImpl extends ServiceImpl<KdYdOutboundMapper, KdYdOutbound> implements IKdYdOutboundService {
    @Autowired
    private YDClient ydClient;
    @Autowired
    private KdYdOutboundMapper kdYdOutboundMapper;
    @Autowired
    private KdYdOutboundDetailMapper kdYdOutboundDetailMapper;
    @Override
    public Map<String, Object> insertkdYdOutbound(Map json) {
        HashMap<String, Object> result = new HashMap<>();

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

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

                for (Map item : kdYdOutbounddels) {
                    try {
                        String djbh = String.valueOf(item.get("djbh"));

                        List<Map> list1 = (List<Map>) ydClient.queryData(YDParam.builder()
                                .formUuid("FORM-AADBCDA8126F41A0ADDEE3353828583192M8")
                                .searchCondition(JSONObject.toJSONString(UtilMap.map("textField_mg34txgm", 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-AADBCDA8126F41A0ADDEE3353828583192M8")
                                .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 (action.equals("del")) {
                log.info("【出库单删除任务】无需要删除的数据");
                result.put("code", "200");
                result.put("msg", "无需要删除的数据");
                result.put("data", new HashMap<>());
                return result;
            }

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

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

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

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

                try {
                    String djbh = String.valueOf(tableItem.get("djbh"));
                    List<Map<String, Object>> tableList1 = UtilMap.getList(tableItem, "tableList");
                    String  deliveryId = UtilMap.getString(tableItem, "deliveryId");

                    // 检查明细数据是否存在
                    if (tableList1 == null || tableList1.isEmpty()) {
                        log.warn("出库单明细数据为空: djbh={}", djbh);
                        singleResult.put("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 item1 : tableList1) {
                        HashMap<String, String> tablemap = new HashMap<>();
//                        tablemap.put("textField_mg34txgm", String.valueOf(tableItem.get("djbh")));
                        tablemap.put("textField_mejnamff", String.valueOf(item1.get("wlbm")));
                        tablemap.put("textField_mejnamfg", String.valueOf(item1.get("wlmc")));
                        tablemap.put("textField_mg34txh1", String.valueOf(item1.get("tpsb")));
                        tablemap.put("textField_mejnamfh", String.valueOf(item1.get("ggxh")));
                        tablemap.put("textField_mejnamfk", String.valueOf(item1.get("kcdw")));

                        // 处理数值字段
                        tablemap.put("numberField_mejnamfl", safeConvertBigDecimalToString(item1.get("yfsl")));
                        tablemap.put("numberField_mg34txh2", safeConvertBigDecimalToString(item1.get("sfsl")));
                        tablemap.put("numberField_mg34txh3", safeConvertBigDecimalToString(item1.get("dj")));
                        tablemap.put("numberField_mg34txh4", safeConvertBigDecimalToString(item1.get("hsdj")));

                        tablemap.put("textField_mg34txh5", String.valueOf(item1.get("ph")));
                        tablemap.put("numberField_mg34txh6", safeConvertBigDecimalToString(item1.get("sl")));
                        tablemap.put("numberField_mg34txh7", safeConvertBigDecimalToString(item1.get("se")));
                        tablemap.put("numberField_mg34txh8", safeConvertBigDecimalToString(item1.get("je")));
                        tablemap.put("numberField_mg34txh9", safeConvertBigDecimalToString(item1.get("jshj")));

                        tablemap.put("textField_mf6a0h6l", String.valueOf(item1.get("ck")));
                        tablemap.put("textField_mf6a0h6k", String.valueOf(item1.get("cw")));
                        tablemap.put("textField_mf6a0h6p", String.valueOf(item1.get("kczt")));
                        tablemap.put("numberField_mg34txha", safeConvertBigDecimalToString(item1.get("jtc")));

                        tablemap.put("textField_mejnamf6", String.valueOf(item1.get("sjr")));
                        tablemap.put("textField_mejnamf7", String.valueOf(item1.get("sjdh")));
                        tablemap.put("textareaField_mf6a0h5e", String.valueOf(item1.get("sjdz")));
                        tablemap.put("textField_mejnamfx", String.valueOf(item1.get("ssxl")));
                        tablemap.put("textField_mf6a0h6u", String.valueOf(item1.get("gg")));
                        tablemap.put("textField_mhlqeoas", String.valueOf(item1.get("zbq")));

                        // 处理日期字段
                        tablemap.put("dateField_mg34txhb", safeConvertDateTimeToString(item1.get("fwdqr")));
                        tablemap.put("textField_mhlqeoat", String.valueOf(item1.get("zbqsf")));
                        tablemap.put("textField_mf6a0h6x", String.valueOf(item1.get("kddh")));
                        tablemap.put("textField_mf6a0h6y", String.valueOf(item1.get("jx")));
                        tablemap.put("radioField_mf6a0h6h", String.valueOf(item1.get("sfzp")));

                        tableList.add(tablemap);

                        // 处理序列号明细
                        String xlhjh = String.valueOf(item1.get("xlhjh"));
                        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(item1.get("wlbm")));
                                        xlhMap.put("textField_mjqst61m", String.valueOf(item1.get("ggxh")));
                                        return xlhMap;
                                    })
                                    .collect(Collectors.toList());

                            tableListxlh.addAll(currentXlhList);
                        }
                    }

                    // 查询发货单数据
                    String fhdformInstanceId = null;
                    String fhdbh = null;
                    if (deliveryId != null) {
                        try {
                            log.debug("开始查询发货单数据: deliveryId={}", deliveryId);

                            List<Map> ddlist = (List<Map>) ydClient.queryData(
                                    YDParam.builder()
                                            .formUuid("FORM-FAE2575E112644ED914CAB4FEC9309F32AVR")
                                                   .searchCondition(JSON.toJSONString(UtilMap.map("serialNumberField_mheazm7w", deliveryId)))
                                            .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 && deliveryId.equals(khformData.get("serialNumberField_mheazm7w"))) {
                                        fhdformInstanceId = (String) khitem.get("formInstanceId");
                                        fhdbh = (String) khformData.get("serialNumberField_mheazm7w");
                                        break;
                                    }
                                }
                            } else {
                                log.warn("未查询到发货单数据: deliveryId={}", deliveryId);
                            }

                        } catch (Exception e) {
                            log.error("查询发货单数据异常: deliveryId={}", deliveryId, e);
                        }
                    }

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

                    // 添加关联表单数据
                    if (fhdbh != null && !"null".equals(fhdbh) && fhdformInstanceId != null) {
                        updateMap.put("associationFormField_mejmml36",
                                Arrays.asList(getfhdAss(fhdbh,fhdformInstanceId)));
                    }

                    // 添加主表字段
                    updateMap.put("dateField_krbgloam", safeConvertDateTimeToString(tableItem.get("dateTime")));
                    updateMap.put("textField_krnn5bmr", String.valueOf(tableItem.get("xsDept")));
                    updateMap.put("textField_ml4qflc0", String.valueOf(tableItem.get("kdgs")));
                    updateMap.put("textField_mhjxw689", String.valueOf(tableItem.get("fhDept")));
                    updateMap.put("textField_mhjxw686", String.valueOf(tableItem.get("cgy")));
                    updateMap.put("textField_mf6a0h6f", String.valueOf(tableItem.get("ddbh")));
                    updateMap.put("selectField_mejowmna", String.valueOf(tableItem.get("djlx")));
                    updateMap.put("textField_mg34txgm", String.valueOf(tableItem.get("djbh")));
                    updateMap.put("textField_mhlqeoar", String.valueOf(tableItem.get("jsbb")));
                    updateMap.put("textField_mejnamf2", String.valueOf(tableItem.get("kh")));
                    updateMap.put("selectField_mejowmnc", String.valueOf(tableItem.get("xslx")));
                    updateMap.put("textField_mhjxw688", String.valueOf(tableItem.get("xsy")));
                    updateMap.put("selectField_mg34txgt", String.valueOf(tableItem.get("xssx")));
                    updateMap.put("selectField_megi74y8", String.valueOf(tableItem.get("khsx")));
                    updateMap.put("textField_mg34txgy", String.valueOf(tableItem.get("khtjr")));
                    updateMap.put("textField_mg34txgz", String.valueOf(tableItem.get("ysdh")));
                    updateMap.put("textField_migw33w6", String.valueOf(deliveryId));

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

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

                    log.info("出库单同步成功: djbh={}, deliveryId={}", djbh, deliveryId);

                } catch (Exception e) {
                    String djbh = String.valueOf(tableItem.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", kdYdOutbounds.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("【出库单同步任务】完成，共处理{}条数据，成功{}条，失败{}条",
                    kdYdOutbounds.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;
    }

    // 辅助方法：安全转换BigDecimal为字符串（保留2位小数）
    private String safeConvertBigDecimalToString(Object value) {
        try {
            if (value == null) {
                return java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP).toString();
            }

            if (value instanceof BigDecimal) {
                return ((BigDecimal) value).setScale(2, java.math.RoundingMode.HALF_UP).toString();
            } else if (value instanceof Number) {
                return new BigDecimal(value.toString()).setScale(2, java.math.RoundingMode.HALF_UP).toString();
            } else if (value instanceof String) {
                return new BigDecimal((String) value).setScale(2, java.math.RoundingMode.HALF_UP).toString();
            }

            return java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP).toString();
        } catch (Exception e) {
            log.warn("转换BigDecimal异常: value={}", value);
            return java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP).toString();
        }
    }

    // 辅助方法：安全转换日期时间为字符串
//    private String safeConvertDateTimeToString(Object dateTime) {
//        try {
//            if (dateTime == null) {
//                return "";
//            }
//
//            if (dateTime instanceof java.time.LocalDateTime) {
//                java.time.LocalDateTime dt = (java.time.LocalDateTime) dateTime;
//                return String.valueOf(dt.atZone(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli());
//            }
//
//            return String.valueOf(dateTime);
//        } catch (Exception e) {
//            log.warn("转换日期时间异常: dateTime={}", dateTime);
//            return "";
//        }
//    }
    /**
     * 最简化日期转换
     */
    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 ""; }
    }
    private Object getfhdAss(String title, String id) {
        return UtilMap.map("appType, formUuid, formType, instanceId, title, subTitle", "APP_VQDMMWS6OR1VHL8VMFD3", "FORM-FAE2575E112644ED914CAB4FEC9309F32AVR", "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);
    }
}
