package com.malk.huagao.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.malk.huagao.entity.*;
import com.malk.huagao.mapper.KdYdReceivableDetailMapper;
import com.malk.huagao.mapper.KdYdReceivableMapper;
import com.malk.huagao.mapper.KdYdZpDetailMapper;
import com.malk.huagao.mapper.KdYdZpMapper;
import com.malk.huagao.service.IKdYdZpService;
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 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.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author LQY
 * @since 2025-10-16
 */
@Service
public class KdYdZpServiceImpl extends ServiceImpl<KdYdZpMapper, KdYdZp> implements IKdYdZpService {
    @Autowired
    private YDClient ydClient;
    @Autowired
    private KdYdZpMapper kdYdZpMapper;
    @Autowired
    private KdYdZpDetailMapper kdYdZpDetailMapper;

    @Override
    public void insertkdYdZp(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");
            KdYdZp kdYdZp = new KdYdZp();
            kdYdZp.setOperationType("3");
            kdYdZp.setSyncStatus("0");
            kdYdZpMapper.update(kdYdZp, new LambdaQueryWrapper<KdYdZp>().eq(KdYdZp::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, "radioField_mg3cexkm");
//        long receivableId = UtilMap.getLong(formData, "textField_mgt4w4ip");
        String kh = UtilMap.getString(formData, "textField_mhn5h4mo");
        String kpfs = UtilMap.getString(formData, "selectField_mg3cexke");
        String fph = UtilMap.getString(formData, "textField_mejmml3a");
        LocalDateTime ywrq = parseTimestamp(UtilMap.getString(formData, "dateField_mejmml39"));
        String bb = UtilMap.getString(formData, "selectField_mg3fuqvn");
        String bz = UtilMap.getString(formData, "textareaField_mejmml3e");
        String djbh = UtilMap.getString(formData, "serialNumberField_mhn4661d");
        String spdzyx = UtilMap.getString(formData, "textField_mejmml3d");
        String dddjbh = UtilMap.getString(formData, "textField_mg3cexkf");
        String ysddjbh = UtilMap.getString(formData, "textField_mejmml3k");
        String jshjstr = UtilMap.getString(formData, "numberField_mejmml38");
        BigDecimal jshj = toBigDecimal(jshjstr);
        List<Map> tableField = (List<Map>) formData.get("tableField_mf6el3zx");
        KdYdZp kdYdZp = new KdYdZp();
        kdYdZp.setDjlx(djlx);
        kdYdZp.setKpfs(kpfs);
        kdYdZp.setDjbh(djbh);
        kdYdZp.setFph(fph);
        kdYdZp.setYwrq(ywrq);
//          kdYdZp.setReceivableId(receivableId);
        kdYdZp.setBb(bb);
        kdYdZp.setJshj(jshj);
        kdYdZp.setBz(bz);
        kdYdZp.setKh(kh);
        kdYdZp.setSyncStatus("0");
        kdYdZp.setOperationType("1");
        kdYdZp.setSpdzyx(spdzyx);
        kdYdZp.setCreateTime(LocalDateTime.now());
//        kdYdZp.setForminstid(formInstId);
        if ("2".equals(type)) {
            kdYdZp.setOperationType(type);
            kdYdZpMapper.update(kdYdZp, new LambdaQueryWrapper<KdYdZp>().eq(KdYdZp::getDjbh, djbh));
        } else {
            kdYdZpMapper.insert(kdYdZp);
        }


        Long id = kdYdZp.getId();
        int count = 1;
        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 zjshj = toBigDecimal(safeGetString(item, "numberField_mejmtic7"));
            String ph = safeGetString(item, "textField_mf6el409");
            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 rjdj = toBigDecimal(safeGetString(item, "numberField_mg3cexkl"));
            String gg = safeGetString(item, "textField_mf6el40b");
            String xxddbm = safeGetString(item, "textField_mf6el408");
//            String ysdjbh = safeGetString(item, "textField_mhn5h4mi");
            KdYdZpDetail kdYdZpDetail = new KdYdZpDetail();
            kdYdZpDetail.setZpId(id);
            kdYdZpDetail.setWlbm(wlbm);
            kdYdZpDetail.setWlmc(wlmc);
            kdYdZpDetail.setGgxh(ggxh);
            kdYdZpDetail.setJjdw(jjdw);
            kdYdZpDetail.setSsxl(ssxl);
            kdYdZpDetail.setDj(dj);
            kdYdZpDetail.setHsdj(hsdj);
            kdYdZpDetail.setSl(sl);
            kdYdZpDetail.setSe(se);
            kdYdZpDetail.setJe(zjshj);
            kdYdZpDetail.setPh(ph);
            kdYdZpDetail.setJjsl(jjsl);
            kdYdZpDetail.setZkl(zkl);
            kdYdZpDetail.setBhsje(bhsje);
            kdYdZpDetail.setZke(zke);
            kdYdZpDetail.setRjdj(rjdj);
            kdYdZpDetail.setGg(gg);
            kdYdZpDetail.setXxddbh(xxddbm);
            kdYdZpDetail.setDetailId(count);
            kdYdZpDetail.setSyncStatus("0");
            kdYdZpDetail.setOperationType("1");
            if ("2".equals(type) || "3".equals(type)) {
                kdYdZpDetail.setOperationType(type);
                kdYdZpDetailMapper.update(kdYdZpDetail, new LambdaQueryWrapper<KdYdZpDetail>().eq(KdYdZpDetail::getDetailId, count));
            } else {
                kdYdZpDetailMapper.insert(kdYdZpDetail);
            }
            count++;
        }

    }

    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);
    }
}
