package nc.bs.ic.m45.sign.rule;

import com.alibaba.fastjson.JSONObject;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.NCLocator;
import nc.bs.logging.Log;
import nc.impl.pubapp.pattern.rule.IRule;
import nc.itf.arap.goldentax.SysParaInitQuery;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.vo.bd.material.MaterialVO;
import nc.vo.bd.psn.PsndocVO;
import nc.vo.bd.rack.RackVO;
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.pub.BusinessException;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.pubapp.pattern.pub.SqlBuilder;
import nc.vo.vorg.DeptVersionVO;
import nccloud.pubift.commen.itf.utils.IHttpPostOtherSys;

import java.util.ArrayList;
import java.util.List;


/**
 * 采购入库签字后同步到MES
 */
public class AfterSigningSynchronizeRuleMES implements IRule<PurchaseInVO> {

    // MES接口URL
    private static final String ADD_URL = "/GTHINKING/AjaxService/N_KCSJJS/101527010.ashx/gt_rec_api_cgrkdj";
    private static final String DELETE_URL = "/GTHINKING/AjaxService/N_KCSJJS/101527010.ashx/gt_rec_api_qxcgrkdj";

    private static final String logginfo = "OALOG";
    private static final Log obmlog = Log.getInstance(logginfo);
    private static final BaseDAO dao = new BaseDAO();
    // 初始化HTTP请求工具类
    IHttpPostOtherSys httpPostOtherSys = NCLocator.getInstance().lookup(IHttpPostOtherSys.class);

    @Override
    public void process(PurchaseInVO[] purchaseInVOs) {
        try {
            if (purchaseInVOs == null || purchaseInVOs.length == 0) {
                obmlog.debug("AfterSigningSynchronizeRuleMES-采购入库同步MES-无采购入库单");
                return;
            }
            // 检查并筛选组织为电缆的采购入库单
            List<PurchaseInVO> filteredPurchaseInVOS = checkAndFilterBills(purchaseInVOs);
            if (filteredPurchaseInVOS.isEmpty()) {
                obmlog.debug("AfterSigningSynchronizeRuleMES-无组织为电缆的需要同步的采购入库单");
                return;
            }
            for (PurchaseInVO purchaseInVO : filteredPurchaseInVOS) {
                PurchaseInHeadVO hvo = (PurchaseInHeadVO) purchaseInVO.getParentVO();
                PurchaseInBodyVO[] bvos = (PurchaseInBodyVO[]) purchaseInVO.getChildrenVO();
                // 构建请求参数
                JSONObject syncData = buildSyncData(hvo, bvos);
                httpPostOtherSys.sendToExternalSystem(ADD_URL, syncData);
            }
        } catch (Exception e) {
            obmlog.error("采购入库同步MES-处理异常:" + e.getMessage(), e);
            ExceptionUtils.wrappException(e);
        }
    }

    /**
     * 构建符合MES系统接口规范的请求数据
     */
    private JSONObject buildSyncData(PurchaseInHeadVO hvo, PurchaseInBodyVO[] bvos) throws BusinessException {
        obmlog.debug("采购入库同步MES-开始构建数据: " + hvo.getVbillcode());
        JSONObject requestData = new JSONObject();
        // 设置操作类型
        requestData.put("operation_type", "I");  // 签字为新增操作
        // 构建data数组
        List<JSONObject> dataList = new ArrayList<>();
        JSONObject dataObj = new JSONObject();
        // 设置入库单基本信息
        UFDate billDate = hvo.getDbilldate();
        dataObj.put("orderDate", billDate != null ? billDate.toString().substring(0, 10) : "");  // 入库日期 - 格式yyyy-MM-dd
        dataObj.put("originalOrderNo", hvo.getVbillcode());  // 采购收货单号
        // 仓库编码 - 使用正确的仓库字段(cwarehouseid)
        dataObj.put("warehouseId", transferCodeByPk(StordocVO.getDefaultTableName(),
                StordocVO.CODE, StordocVO.PK_STORDOC, hvo.getCwarehouseid()));  // 仓库编码
        // 部门ID - 采购部门最新版本(cdptid)而非cdptvid，cdptvid是部门版本信息
        dataObj.put("departmentId", transferCodeByPk(DeptVersionVO.getDefaultTableName(),
                DeptVersionVO.CODE, DeptVersionVO.PK_VID, hvo.getCdptvid()));  // 部门编码
        // 保管员
        dataObj.put("creator", transferCodeByPk(PsndocVO.getDefaultTableName(),
                PsndocVO.NAME, PsndocVO.PK_PSNDOC, hvo.getCwhsmanagerid()));  // 保管员
        dataObj.put("remark", hvo.getVnote());  // 备注
        // 构建明细
        List<JSONObject> detailsList = new ArrayList<>();
        if (bvos != null) {
            for (PurchaseInBodyVO bvo : bvos) {
                JSONObject detailMap = new JSONObject();
                detailMap.put("originalOrderNo", hvo.getVbillcode());  // 采购收货单号
                detailMap.put("sequenceNum", bvo.getCrowno());  // 采购收货单序号
                // 物料编码 - 必填
                detailMap.put("materialId", transferCodeByPk(MaterialVO.getDefaultTableName(),
                        MaterialVO.CODE, MaterialVO.PK_MATERIAL, bvo.getCmaterialoid()));  // 物料编码
                // 库位编码 - 根据字段表使用clocationid而非cspaceid
                detailMap.put("storageId", transferCodeByPk(RackVO.getDefaultTableName(),
                        RackVO.CODE, RackVO.PK_RACK, bvo.getClocationid()));  // 库位编码
                detailMap.put("batchNum", bvo.getVbatchcode());  // 物料批号
                // 数量信息 - 根据字段表修正
                UFDouble assistNum = bvo.getNassistnum();  // 实收数量
                detailMap.put("quantity", assistNum != null ? assistNum.doubleValue() : null);  // 入库数量
                UFDouble mainNum = bvo.getNnum();  // 实收主数量
                detailMap.put("mQuantity", mainNum != null ? mainNum.doubleValue() : null);  // 主入库数量
                // 供应商编码 - 根据字段表使用cvendorid而非csupplierid
                detailMap.put("supplierId", transferCodeByPk(SupplierVO.getDefaultTableName(),
                        SupplierVO.CODE, SupplierVO.PK_SUPPLIER, bvo.getCvendorid()));  // 供应商编码
                // 生产日期 - 字段表确认为dproducedate
                UFDate produceDate = bvo.getDproducedate();
                if (produceDate != null) {
                    detailMap.put("manufactureDate", produceDate.toString().substring(0, 10));
                }
                detailsList.add(detailMap);
            }
        }
        dataObj.put("details", detailsList);
        dataList.add(dataObj);
        requestData.put("data", dataList);
        return requestData;
    }


    /**
     * 检查并筛选需要同步的单据
     */
    private List<PurchaseInVO> checkAndFilterBills(PurchaseInVO[] purchaseInVOS) {
        List<PurchaseInVO> result = new ArrayList<>();
        for (PurchaseInVO vo : purchaseInVOS) {
            try {
                String code = transferCodeByPk(StockOrgVO.getDefaultTableName(), StockOrgVO.CODE, StockOrgVO.PK_STOCKORG, vo.getParentVO().getPk_org());
                if (httpPostOtherSys.checkIfIncludeOrg(code)) {
                    result.add(vo);
                }
            } catch (BusinessException e) {
                ExceptionUtils.wrappBusinessException("查询组织时发生错误");
            }
        }
        return result;
    }


    /**
     * 根据主键查询对应的编码
     */
    private String transferCodeByPk(String tableName, String selectField, String pkField, Object pk) throws BusinessException {
        if (pk == null || "".equals(pk.toString().trim())) {
            return null;
        }
        SqlBuilder sqlBuilder = new SqlBuilder();
        sqlBuilder.append(" select " + selectField);
        sqlBuilder.append(" from " + tableName);
        sqlBuilder.append(" where ");
        sqlBuilder.append(pkField, pk.toString());
        Object o = dao.executeQuery(sqlBuilder.toString(), new ColumnProcessor());
        if (o == null) {
            obmlog.warn("未查询到编码信息，sql【" + sqlBuilder + "】");
            return null;
        }
        return o.toString();
    }
}
