package nccloud.wmssync.ml.m45;

import nc.bs.businessevent.IBusinessEvent;
import nc.bs.businessevent.IBusinessListener;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.NCLocator;
import nc.bs.ic.general.businessevent.ICGeneralCommonEvent;
import nc.bs.logging.Log;
import nc.vo.bd.material.MaterialVO;
import nc.vo.bd.stordoc.StordocVO;
import nc.vo.bd.supplier.SupplierVO;
import nc.vo.ic.m45.entity.PurchaseInBodyVO;
import nc.vo.ic.m45.entity.PurchaseInHeadVO;
import nc.vo.ic.m45.entity.PurchaseInVO;
import nc.vo.org.StockOrgVO;
import nc.vo.pmpub.project.ProjectHeadVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDateTime;
import nccloud.api.uapbd.wms.utils.IWmsSyncUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 采购入库下发WMS
 */
public class WmsSyncPurchaseInListener implements IBusinessListener {

    private static final String WAREHOUSE_PREFIX = "CK";
    private static final String WAREHOUSE_SUFFIX = "001";

    public static final IWmsSyncUtils WMS_SYNC_UTILS = NCLocator.getInstance().lookup(IWmsSyncUtils.class);

    public static final BaseDAO dao = new BaseDAO();

    private static final Log log = Log.getInstance("wmslog");

    @Override
    public void doAction(IBusinessEvent iBusinessEvent) throws BusinessException {
        // 先检查是否是BDCommonEvent类型
        if (iBusinessEvent instanceof ICGeneralCommonEvent event) {
            PurchaseInVO[] purchaseInVOs = (PurchaseInVO[]) event.getOldObjs();
            if (purchaseInVOs != null) {
                log.info("采购入库单下发WMS开始");
                for (PurchaseInVO purchaseInVO : purchaseInVOs) {
                    try {
                        sendToWMS(purchaseInVO);
                    } catch (BusinessException e) {
                        throw new BusinessException("采购入库单下发WMS失败:" + e.getMessage(), e);
                    }
                }
            }

        }
    }

    private void sendToWMS(PurchaseInVO purchaseInVO) throws BusinessException {
        String pkOrg = purchaseInVO.getHead().getPk_org();
        String orgCode = WMS_SYNC_UTILS.transferCodeByPk(StockOrgVO.getDefaultTableName(), StockOrgVO.CODE, StockOrgVO.PK_STOCKORG, pkOrg);
        if (WMS_SYNC_UTILS.checkIfIncludeOrg(orgCode)) {
            log.info("采购入库单下发WMS开始，组织code" + orgCode);

            // 构造WMS请求数据
            Map<String, Object> requestData = buildWMSRequestData(purchaseInVO, orgCode);

            // 调用WMS接口
            WMS_SYNC_UTILS.sendToExternalSystem("putASN", requestData);

            log.info("采购入库单下发WMS完成，单据号：" + purchaseInVO.getHead().getVbillcode());
        } else {
            log.info("采购入库单下发: 当前组织" + orgCode + "不是指定组织，不同步WMS");
        }
    }

    /**
     * 构造WMS putASN接口请求数据
     *
     * @param purchaseInVO 采购入库单VO - ERP: PurchaseInVO
     * @param orgCode      组织编码
     * @return WMS请求数据
     * @throws BusinessException
     */
    private Map<String, Object> buildWMSRequestData(PurchaseInVO purchaseInVO, String orgCode) throws BusinessException {
        Map<String, Object> requestData = new HashMap<>();

        Map<String, Object> data = new HashMap<>();
        PurchaseInHeadVO head = purchaseInVO.getHead();
        PurchaseInBodyVO[] bodies = purchaseInVO.getBodys();

        // 构造headlist
        Map<String, Object> headlist = buildHeadList(head, bodies, orgCode);

        // 构造details
        List<Map<String, Object>> detailsList = new ArrayList<>();
        if (bodies != null) {
            for (PurchaseInBodyVO body : bodies) {
                Map<String, Object> detail = buildDetailItem(body, head);
                detailsList.add(detail);
            }
        }
        headlist.put("details", detailsList);
        data.put("header", List.of(headlist));
        requestData.put("data", data);

        return requestData;
    }

    /**
     * 构造WMS表头数据
     *
     * @param head    采购入库单表头VO - ERP: PurchaseInHeadVO
     * @param bodies  采购入库单表体VO数组 - ERP: PurchaseInBodyVO[]
     * @param orgCode 组织编码
     * @return WMS表头数据
     * @throws BusinessException
     */
    private Map<String, Object> buildHeadList(PurchaseInHeadVO head, PurchaseInBodyVO[] bodies, String orgCode) throws BusinessException {
        Map<String, Object> headlist = new HashMap<>();

        // warehouseId - 所属仓库 - ERP: cwarehouseid -> WMS: warehouseId
        headlist.put("warehouseId", WAREHOUSE_PREFIX + orgCode + WAREHOUSE_SUFFIX);

        // customerId - 货主ID - ERP: 默认固定值 -> WMS: customerId
        headlist.put("customerId", "TKJT");

        // asnType - 订单类型 - ERP: 根据业务类型判断 -> WMS: asnType
        headlist.put("asnType", "CGRK"); // 采购入库订单

        // docNo - ERP单据号 - ERP: vbillcode -> WMS: docNo
        headlist.put("docNo", head.getVbillcode());

        // asnReferenceA - SRM单号 - ERP: 暂无对应字段 -> WMS: asnReferenceA
        // headlist.put("asnReferenceA", "");

        // asnReferenceB - ASN参考信息B - ERP: 暂无对应字段 -> WMS: asnReferenceB
        // headlist.put("asnReferenceB", "");

        // asnReferenceC - ASN参考信息C - ERP: 暂无对应字段 -> WMS: asnReferenceC
        // headlist.put("asnReferenceC", "");

        // asnReferenceD - ASN参考信息D - ERP: 暂无对应字段 -> WMS: asnReferenceD
        // headlist.put("asnReferenceD", "");

        // asnCreationTime - ASN创建时间 - ERP: creationtime -> WMS: asnCreationTime
        UFDateTime creationTime = head.getCreationtime();
        if (creationTime != null) {
            headlist.put("asnCreationTime", creationTime.toString());
        }

        // expectedArriveTime1 - 预期到货时间段从 - ERP: 暂无对应字段 -> WMS: expectedArriveTime1
        // headlist.put("expectedArriveTime1", "");

        // expectedArriveTime2 - 预期到货时间段到 - ERP: 暂无对应字段 -> WMS: expectedArriveTime2
        // headlist.put("expectedArriveTime2", "");

        // supplierId - 供应商ID - ERP: cvendorid -> WMS: supplierId
        String supplierCode = WMS_SYNC_UTILS.transferCodeByPk(SupplierVO.getDefaultTableName(),
                SupplierVO.CODE, SupplierVO.PK_SUPPLIER, head.getCvendorid());
        headlist.put("supplierId", supplierCode);

        // supplierName - 供应商名称 - ERP: 通过供应商ID查询名称 -> WMS: supplierName
        String supplierName = WMS_SYNC_UTILS.transferCodeByPk(SupplierVO.getDefaultTableName(),
                SupplierVO.NAME, SupplierVO.PK_SUPPLIER, head.getCvendorid());
        headlist.put("supplierName", supplierName);

        // supplierAddress1 - 供应商地址 - ERP: 通过供应商ID查询地址 -> WMS: supplierAddress1
        String supplierAddress = WMS_SYNC_UTILS.transferCodeByPk(SupplierVO.getDefaultTableName(), SupplierVO.CORPADDRESS, SupplierVO.PK_SUPPLIER, head.getCvendorid());
        headlist.put("supplierAddress1", supplierAddress != null ? supplierAddress : "");

        // supplierAddress2~4 - 供应商地址2~4 - ERP: 暂无对应字段 -> WMS: supplierAddress2~4
        // headlist.put("supplierAddress2", "");
        // headlist.put("supplierAddress3", "");
        // headlist.put("supplierAddress4", "");

        // 供应商国家省份等信息 - ERP: 暂无对应字段 -> WMS: supplierCountry等
        // headlist.put("supplierCountry", "");
        // headlist.put("supplierProvince", "");
        // headlist.put("supplierCity", "");
        // headlist.put("supplierDistrict", "");
        // headlist.put("supplierStreet", "");

        // supplierContact - 供应商联系人 - ERP: 暂无对应字段 -> WMS: supplierContact
//        String supplierContact = WMS_SYNC_UTILS.transferFieldByPkAllowNull(SupplierVO.getDefaultTableName(),
//                SupplierVO.LINKMAN, SupplierVO.PK_SUPPLIER, head.getCvendorid());
//        headlist.put("supplierContact", supplierContact != null ? supplierContact : "");

        // supplierFax - 供应商传真 - ERP: 暂无对应字段 -> WMS: supplierFax
        // headlist.put("supplierFax", "");

        // supplierMail - 供应商电子邮件 - ERP: 暂无对应字段 -> WMS: supplierMail
        // headlist.put("supplierMail", "");

        // supplierTel1 - 供应商移动电话 - ERP: 通过供应商ID查询电话 -> WMS: supplierTel1
        String supplierTel = WMS_SYNC_UTILS.transferFieldByPkAllowNull(SupplierVO.getDefaultTableName(),
                SupplierVO.TEL1, SupplierVO.PK_SUPPLIER, head.getCvendorid());
        headlist.put("supplierTel1", supplierTel != null ? supplierTel : "");

        // supplierTel2 - 供应商固定电话 - ERP: 暂无对应字段 -> WMS: supplierTel2
        // headlist.put("supplierTel2", "");

        // supplierZip - 供应商邮政编码 - ERP: 暂无对应字段 -> WMS: supplierZip
        // headlist.put("supplierZip", "");

        // carrierId - 承运人ID - ERP: 暂无对应字段 -> WMS: carrierId
        // headlist.put("carrierId", "");

        // carrierName - 承运人名称 - ERP: 暂无对应字段 -> WMS: carrierName
        // headlist.put("carrierName", "");

        // issuePartyId - 下单方ID - ERP: 暂无对应字段 -> WMS: issuePartyId
        // headlist.put("issuePartyId", "");

        // issuePartyName - 下单方名称 - ERP: 暂无对应字段 -> WMS: issuePartyName
        // headlist.put("issuePartyName", "");

        // countryOfDestination - 目的国 - ERP: crececountryid -> WMS: countryOfDestination
        // headlist.put("countryOfDestination", "");

        // countryOfOrigin - 原产国 - ERP: csendcountryid -> WMS: countryOfOrigin
        // headlist.put("countryOfOrigin", "");

        // followUp - 业务担当 - ERP: cbizid -> WMS: followUp
        // headlist.put("followUp", "");

        // hedi01 - EDI相关信息01 - ERP: 自定义字段 -> WMS: hedi01
        // headlist.put("hedi01", "");

        // hedi02 - 是否为负数 - 根据expectedQty决定 -> WMS: hedi02
        // 先计算所有表体的expectedQty总和来判断正负
        boolean hasNegativeQty = false;
        if (bodies != null) {
            for (PurchaseInBodyVO body : bodies) {
                if (body.getNshouldnum() != null && body.getNshouldnum().doubleValue() < 0) {
                    hasNegativeQty = true;
                    break;
                }
            }
        }
        String isNegative = hasNegativeQty ? "Y" : "N";
        headlist.put("hedi02", isNegative);

        // 表头自定义项使用
        // 获取来源/源头单据信息从表体第一个记录中获取
        String sourceBillHid = "";
        String firstBillHid = "";
        String sourceTranstype = "";
        String firstTranstype = "";

        if (bodies != null && bodies.length > 0) {
            PurchaseInBodyVO firstBody = bodies[0];
            sourceBillHid = firstBody.getCsourcebillhid() != null ? firstBody.getCsourcebillhid() : "";
            firstBillHid = firstBody.getCfirstbillhid() != null ? firstBody.getCfirstbillhid() : "";
            sourceTranstype = firstBody.getCsourcetranstype() != null ? firstBody.getCsourcetranstype() : "";
            firstTranstype = firstBody.getCfirsttranstype() != null ? firstBody.getCfirsttranstype() : "";
        }

        // hedi03 - 来源单据表头主键 - ERP: csourcebillhid -> WMS: hedi03
        headlist.put("hedi03", sourceBillHid);

        // hedi04 - 源头单据表头主键 - ERP: cfirstbillhid -> WMS: hedi04
        headlist.put("hedi04", firstBillHid);

        // hedi05 - 来源单据交易类型 - ERP: csourcetranstype -> WMS: hedi05
        headlist.put("hedi05", sourceTranstype);

        // hedi06 - 源头单据交易类型 - ERP: cfirsttranstype -> WMS: hedi06
        headlist.put("hedi06", firstTranstype);

        // hedi07 - 当前单据表头主键 - ERP: cgeneralhid -> WMS: hedi07
        headlist.put("hedi07", head.getCgeneralhid());

        // hedi08~10 - EDI相关信息08~10 - ERP: 自定义字段 -> WMS: hedi08~10
        // headlist.put("hedi08", "");
        headlist.put("hedi09", 0);
        headlist.put("hedi10", 0);

        // 装卸货地信息 - ERP: 暂无对应字段 -> WMS: placeOf系列
        // headlist.put("placeOfDischarge", "");
        // headlist.put("placeOfLoading", "");
        // headlist.put("placeOfDelivery", "");

        // priority - 优先级 - ERP: 暂无对应字段 -> WMS: priority
        // headlist.put("priority", "");

        // userDefine1~6 - 用户自定义1~6 - ERP: 自定义字段 -> WMS: userDefine1~6
        // headlist.put("userDefine1", "");
        // headlist.put("userDefine2", "");
        // headlist.put("userDefine3", "");
        // headlist.put("userDefine4", "");
        // headlist.put("userDefine5", "");
        // headlist.put("userDefine6", "");

        // notes - 备注 - ERP: vnote -> WMS: notes
        headlist.put("notes", head.getVnote() != null ? head.getVnote() : "");

        // createSource - 创建来源 - ERP: 固定值 -> WMS: createSource
        headlist.put("createSource", "ERP");

        // crossdockFlag - 越库标记 - ERP: 暂无对应字段 -> WMS: crossdockFlag
        // headlist.put("crossdockFlag", "");

        return headlist;
    }

    /**
     * 构造WMS表体明细数据
     *
     * @param body 采购入库单表体VO - ERP: PurchaseInBodyVO
     * @param head 采购入库单表头VO - ERP: PurchaseInHeadVO
     * @return WMS表体明细数据
     * @throws BusinessException
     */
    private Map<String, Object> buildDetailItem(PurchaseInBodyVO body, PurchaseInHeadVO head) throws BusinessException {
        Map<String, Object> detail = new HashMap<>();

        // lineNo - ERP行号 - ERP: crowno -> WMS: lineNo
        detail.put("lineNo", body.getCrowno());

        // sku - 产品编码 - ERP: cmaterialvid -> WMS: sku
        String materialCode = WMS_SYNC_UTILS.transferCodeByPk(MaterialVO.getDefaultTableName(),
                MaterialVO.CODE, MaterialVO.PK_MATERIAL, body.getCmaterialvid());
        detail.put("sku", materialCode);

        // expectedQty - 应收数量 - ERP: nshouldnum -> WMS: expectedQty (确保为正数)
        double expectedQty = body.getNshouldnum() != null ? body.getNshouldnum().doubleValue() : 0;
        detail.put("expectedQty", Math.abs(expectedQty)); // 取绝对值确保为正数

        // totalPrice - 总价 - ERP: 暂无直接对应字段 -> WMS: totalPrice
        detail.put("totalPrice", 0);

        // packUom - 单位 - ERP: castunitid -> WMS: packUom (仅可选择EA/IP/CS/PL)
        // String unitCode = WMS_SYNC_UTILS.transferCodeByPk("bd_measdoc",
        //         "code", "pk_measdoc", body.getCastunitid());
        // detail.put("packUom", convertToWMSUnit(unitCode));
        detail.put("packUom", "EA"); // 默认EA

        // lotAtt01 - 生产日期 - ERP: dproducedate -> WMS: lotAtt01
        detail.put("lotAtt01", body.getDproducedate() != null ? body.getDproducedate().toString() : "");

        // lotAtt02 - 失效日期 - ERP: dvalidate -> WMS: lotAtt02
        detail.put("lotAtt02", body.getDvalidate() != null ? body.getDvalidate().toString() : "");

        // lotAtt03 - 入库日期 - ERP: dbizdate -> WMS: lotAtt03
        detail.put("lotAtt03", body.getDbizdate() != null ? body.getDbizdate().toString() : "");

        // lotAtt04 - ERP批次号 - ERP: vbatchcode -> WMS: lotAtt04
        detail.put("lotAtt04", body.getVbatchcode() != null ? body.getVbatchcode() : "");

        // lotAtt05 - ERP仓库 - ERP: cbodywarehouseid -> WMS: lotAtt05
        String bodyWarehouseCode = WMS_SYNC_UTILS.transferCodeByPk(StordocVO.getDefaultTableName(),
                StordocVO.CODE, StordocVO.PK_STORDOC, body.getCbodywarehouseid());
        detail.put("lotAtt05", bodyWarehouseCode);

        // lotAtt06 - 供应商 - ERP: cvendorid -> WMS: lotAtt06
        String bodySupplierCode = WMS_SYNC_UTILS.transferCodeByPk(SupplierVO.getDefaultTableName(),
                SupplierVO.CODE, SupplierVO.PK_SUPPLIER, body.getCvendorid());
        detail.put("lotAtt06", bodySupplierCode);

        // lotAtt07 - 生产厂商 - ERP:  -> WMS: lotAtt07
        detail.put("lotAtt07", ""); // 采购入库无生产厂商

        // lotAtt08 - 质量状态 - ERP: 默认合格 -> WMS: lotAtt08
        detail.put("lotAtt08", "HG");

        // lotAtt09 - 项目号 - ERP: cprojectid -> WMS: lotAtt09
        String projectCode = WMS_SYNC_UTILS.transferCodeByPk(ProjectHeadVO.getDefaultTableName(),
                ProjectHeadVO.PROJECT_CODE, ProjectHeadVO.PK_PROJECT, body.getCprojectid());
        detail.put("lotAtt09", projectCode != null ? projectCode : "");

        // lotAtt10~24 - 批次属性10~24 - ERP: 暂无对应字段 -> WMS: lotAtt10~24
        // for (int i = 10; i <= 24; i++) {
        //     detail.put("lotAtt" + String.format("%02d", i), "");
        // }

        // dedi04 - 来源单据表体行主键 - ERP: csourcebillbid -> WMS: dedi04
        detail.put("dedi04", body.getCsourcebillbid() != null ? body.getCsourcebillbid() : "");

        // dedi05 - 源头单据表体主键 - ERP: cfirstbillbid -> WMS: dedi05
        detail.put("dedi05", body.getCfirstbillbid() != null ? body.getCfirstbillbid() : "");

        // dedi06 - 当前单据表体行主键 - ERP: cgeneralbid -> WMS: dedi06
        detail.put("dedi06", body.getCgeneralbid() != null ? body.getCgeneralbid() : "");

        // dedi07 - 源头单据号 - ERP: vfirstbillcode -> WMS: dedi07
        // detail.put("dedi07", body.getVfirstbillcode() != null ? body.getVfirstbillcode() : "");

        // dedi08 - 来源单据行号 - ERP: vsourcerowno -> WMS: dedi08
        // detail.put("dedi08", body.getVsourcerowno() != null ? body.getVsourcerowno() : "");

        // dedi09 - 避免使用 ，只能存数字
        // detail.put("dedi09", "");

        // dedi10 - 避免使用  ， 只能存数字
        // detail.put("dedi10", "");

        // dedi11 - 当前单据表体主键 - ERP: cgeneralbid -> WMS: dedi11
        // detail.put("dedi11", ""); // 字段移至userDefine6

        // dedi12 - 当前单据号 - ERP: vbillcode -> WMS: dedi12
        // detail.put("dedi12", head.getVbillcode() != null ? head.getVbillcode() : "");

        // dedi13 - 当前单据行号 - ERP: crowno -> WMS: dedi13
        // detail.put("dedi13", body.getCrowno() != null ? body.getCrowno() : "");

        // dedi14~16 - 保留为扩展字段
        // detail.put("dedi14", "");
        // detail.put("dedi15", "");
        // detail.put("dedi16", "");

        // userDefine1~6 - 用户自定义字段 - 停用
        // userDefine1 -
        // detail.put("userDefine1", "");
        // userDefine2 -
        // detail.put("userDefine2", "");
        // userDefine3 -
        // detail.put("userDefine3", "");
        // userDefine4 - 来源单据表体行主键
        // detail.put("userDefine4", body.getCsourcebillbid() != null ? body.getCsourcebillbid() : "");
        // userDefine5 - 源头单据表体行主键
        // detail.put("userDefine5", body.getCfirstbillbid() != null ? body.getCfirstbillbid() : "");
        // userDefine6 - 当前单据表体行主键
        // detail.put("userDefine6", body.getCgeneralbid() != null ? body.getCgeneralbid() : "");

        // notes - 备注 - ERP: vnotebody -> WMS: notes
        detail.put("notes", body.getVnotebody() != null ? body.getVnotebody() : "");

        return detail;
    }
}
