package nc.bs.mmpac.pmo.pac0002.bp.rule.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.NCLocator;
import nc.bs.logging.Log;
import nc.bs.trade.business.HYPubBO;
import nc.bs.uapbd.util.MyHelper;
import nc.bs.uapbd.util.ThirdPartyPostRequestUtil;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.jdbc.framework.processor.MapProcessor;
import nc.pub.billcode.itf.IBillcodeManage;
import nc.vo.bc.pmpub.project.ProjectHeadVO;
import nc.vo.bd.bom.bom0202.entity.BomVO;
import nc.vo.bd.material.MaterialVO;
import nc.vo.mmpac.pmo.pac0002.entity.PMOAggVO;
import nc.vo.mmpac.pmo.pac0002.entity.PMOHeadVO;
import nc.vo.mmpac.pmo.pac0002.entity.PMOItemVO;
import nc.vo.org.DeptVO;
import nc.vo.org.FactoryVO;
import nc.vo.pub.BusinessException;
import nc.vo.pubapp.pattern.pub.SqlBuilder;
import nccloud.commons.lang.StringUtils;

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

/**
 * 流程生产订单审批后推送艾普MES
 *
 * @author mzr
 * @date 2025/7/3
 */
public class SyncEpicMesUtil {

    private static final String LOG_INFO_NAME = "dldzlog";

    private static final Log logDl = Log.getInstance(LOG_INFO_NAME);

    private static final String pmoUrl = "/prj-v5-web/ext/api/workOrder";
    private static final String codeUrl = "/prj-v5-web/ext/api/releaseNo";
    private static String auditCode = "Y";
    private Map<String, String> configParams;
    private Map<String, String> deptParams;

    private static final BaseDAO dao = new BaseDAO();

    public void processData(PMOAggVO[] pmoAggVOS, String flag) throws BusinessException {
        auditCode = flag;
        configParams = MyHelper.getConfigParams("Dldz-config", null);
        if (configParams.isEmpty()) {
            throw new BusinessException("电力电子的艾普MES接口缺少配置");
        }
        deptParams = MyHelper.getConfigParams("Dldz-dept", null);
        if (deptParams.isEmpty()) {
            throw new BusinessException("电力电子的艾普MES接口缺少部门编码映射配置");
        }
        String deptRange = String.join(",", deptParams.keySet());
        configParams.put("deptRange", deptRange);
        List<PMOAggVO> filteredOrders = checkAndFilterBillSrcOrg(pmoAggVOS);
        if (filteredOrders.isEmpty()) {
            logDl.error("没有符合条件的生产订单需要同步到艾普MES系统。");
            return;
        }
        logDl.info("开始同步生产订单到艾普MES系统，符合条件的订单数量: " + filteredOrders.size());
        JSONArray jsonArray = new JSONArray();
        // 推送到艾普MES系统
        for (PMOAggVO aggVO : filteredOrders) {
            PMOHeadVO head = aggVO.getParentVO();
            PMOItemVO[] bodys = aggVO.getChildrenVO();
            if (bodys == null || bodys.length == 0) {
                logDl.error("生产订单 " + head.getVbillcode() + " 没有行信息，跳过同步。");
                continue;
            }
            if ("N".equals(auditCode)) {
                JSONObject data = buildSyncData(aggVO);
                pushData(pmoUrl, data);
            } else {
                JSONObject data = buildSyncData(aggVO);
                pushData(pmoUrl, data);

                JSONObject buildSyncData = buildSyncCodeData(aggVO);
                jsonArray.add(buildSyncData);
            }
        }
        if (!jsonArray.isEmpty()) {
            pushData(codeUrl, jsonArray);
        }


        logDl.info("生产订单同步到艾普MES系统处理完成。");

    }

    /**
     * 调用MES的生产工单接口推送ERP的流程生产订单和备料计划或推送出厂编号
     *
     * @param param 请求体
     * @throws BusinessException 如果发生非特定可忽略的错误
     */
    private void pushData(String reqUrl, Object param) throws BusinessException {
        String responseString = null;
        try {
            // 转json字符串的时候保留null值
            String jsonStr = JSON.toJSONString(param, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty);
            logDl.error("EpicMes-PMO-param = " + jsonStr);
            String baseUrl = configParams.get("epicMesUrl");
            String requestUrl = baseUrl + reqUrl;
            logDl.error(" EpicMes-PMO-url = " + requestUrl);
            responseString = ThirdPartyPostRequestUtil.sendPostRequest(requestUrl, jsonStr);
            logDl.error(" EpicMes-PMO-res = " + responseString);

            JSONObject resultObj = JSONObject.parseObject(responseString);
            if (!"1".equals(resultObj.getString("flag"))) {
                logDl.error("EpicMes-PMO-error,result[" + resultObj.toJSONString() + "]");
                throw new BusinessException("艾普MES返回错误信息:" + resultObj.getString("msg"));
            }
        } catch (Exception e) {
            logDl.error(" 调用MES或处理响应时发生错误。原始响应: " + responseString + " 错误: " + e.getMessage(), e);
            throw new BusinessException("调用艾普MES或处理响应时发生错误：" + e.getMessage(), e);
        }
    }

    /**
     * 检查并筛选需要同步的单据
     */
    private List<PMOAggVO> checkAndFilterBillSrcOrg(PMOAggVO[] pmoAggVOS) throws BusinessException {
        List<PMOAggVO> aggvoList = new ArrayList<>();
        for (PMOAggVO aggVo : pmoAggVOS) {
            String pkOrg = aggVo.getParentVO().getPk_org();
            String orgCode = MyHelper.transferField(FactoryVO.getDefaultTableName(), FactoryVO.CODE, FactoryVO.PK_FACTORY, pkOrg);
            // 检查当前组织是否为电力电子
            if (MyHelper.checkIfDldzOrg(orgCode, configParams)) {
                continue;
            }
            // 按照部门筛选生产订单，只传消弧车间、电容车间、成套车间（部门是配置项）
            PMOItemVO childrenVO = aggVo.getChildrenVO()[0];
            String cdeptid = childrenVO.getCdeptid();
            String deptCode = MyHelper.transferField(DeptVO.getDefaultTableName(), DeptVO.CODE, DeptVO.PK_DEPT, cdeptid);
            // 如果部门不在范围内则跳过本次循环
            String deptRange = configParams.get("deptRange");
            if (deptCode == null || !deptRange.contains(deptCode)) {
                continue;
            }
            aggvoList.add(aggVo);
        }

        return aggvoList;
    }

    /**
     * 组装数据-流程生产订单+备料计划
     */
    private JSONObject buildSyncData(PMOAggVO aggVO) throws BusinessException {
        PMOHeadVO headVo = aggVO.getParentVO();
        // 目前电力电子只做一个表体的订单，故只处理的流程生产订单第一个子表行
        PMOItemVO pmoItem = aggVO.getChildrenVO()[0];
        // 翻译字段值
        // 组织
        String pkOrg = headVo.getPk_org();
        String selectFields = FactoryVO.CODE + "," + FactoryVO.NAME;
        Map<String, Object> orgMap = MyHelper.transferFields(FactoryVO.getDefaultTableName(), selectFields, FactoryVO.PK_FACTORY, pkOrg);
        // 物料
        String cmaterialid = pmoItem.getCmaterialid();
        selectFields = MaterialVO.CODE + "," + MaterialVO.NAME;
        Map<String, Object> goodsMap = MyHelper.transferFields(MaterialVO.getDefaultTableName(), selectFields, MaterialVO.PK_MATERIAL, cmaterialid);
        // 项目
        String cprojectid = pmoItem.getCprojectid();
        selectFields = ProjectHeadVO.PROJECT_CODE + "," + ProjectHeadVO.PROJECT_NAME;
        Map<String, Object> projectMap = MyHelper.transferFields(MaterialVO.getDefaultTableName(), selectFields, ProjectHeadVO.PK_PROJECT, cprojectid);
        // 生产部门 cdeptid
        String cdeptid = pmoItem.getCdeptid();
        String deptCode = MyHelper.transferField(DeptVO.getDefaultTableName(), DeptVO.CODE, DeptVO.PK_DEPT, cdeptid);
        // 生产BOM版本
        String cbomversionid = pmoItem.getCbomversionid();
        String bomCode = MyHelper.transferField(BomVO.TABLE_NAME, BomVO.HVERSION, BomVO.CBOMID, cbomversionid);
        // 组装数据
        JSONObject data = new JSONObject();
        JSONObject orderParam = new JSONObject();
        orderParam.put("id", null); // 唯一标识（主键）
        orderParam.put("siteCode", deptParams.getOrDefault(deptCode, ""));// 工厂编码
        if (projectMap != null) {
            orderParam.put("contractNo", projectMap.get(ProjectHeadVO.PROJECT_CODE));// 合同号
            orderParam.put("contractName", projectMap.get(ProjectHeadVO.PROJECT_NAME)); // 合同名称
        }
        orderParam.put("workOrderCode", headVo.getVbillcode());// 工单号
        orderParam.put("qty", String.valueOf(pmoItem.getNastnum())); // 计划数量，字符串类型
        if (goodsMap != null) {
            orderParam.put("produCode", goodsMap.get(MaterialVO.CODE)); // 产品编码
            orderParam.put("produName", goodsMap.get(MaterialVO.NAME)); // 产品名称
        }
        // cbomversionid 生产BOM版本
        orderParam.put("bomCode", bomCode); // BOM 编码
        // NCCForUAPLogger.debug("计划开始时间：" + pmoItem.getTplanstarttime().getMillis());
        // NCCForUAPLogger.debug("计划完成时间：" + pmoItem.getTplanendtime().getMillis());
        orderParam.put("planBeginDate", pmoItem.getTplanstarttime().getMillis()); // 计划开始时间（毫秒级时间戳）
        orderParam.put("planEndDate", pmoItem.getTplanendtime().getMillis()); // 计划完成时间（毫秒级时间戳）
        // orderParam.put("endDate", null); // 试验结束时间（毫秒级时间戳）
        orderParam.put("type", "I"); // 类型：I:新增 U:修改 D:删除
        orderParam.put("auditCode", auditCode); // 审核状态（Y:已审核 N:未审核）
        // orderParam.put("transferPlanTime", null); // 生产转检计划时间（格式为YYYY-MM-DD）
        // orderParam.put("receiptScheduledTime", null); // 完工入库时间（格式为YYYY-MM-DD）
        if (orgMap != null) {
            orderParam.put("companyCode", orgMap.get(FactoryVO.CODE)); // 公司编码
            orderParam.put("companyName", orgMap.get(FactoryVO.NAME)); // 公司名称
        }
        JSONArray orderArr = new JSONArray();
        orderArr.add(orderParam);
        // 流程生产订单
        data.put("workOrders", orderArr);
        data.put("mrls", getPickmInfo(pmoItem.getPrimaryKey())); // 备料计划
        //       {
        //           "workOrders": [// 流程生产订单
        //           {
        //               "id": null,                          // 唯一标识（主键）
        //                   "siteCode": "04",                    // 工厂编码
        //                   "contractNo": "HDDK0111325",        // 合同号
        //                   "workOrderCode": "DSF01-2501230028",// 工单号
        //                   "qty": "1.000",                      // 计划数量（字符串类型）
        //                   "produCode": "103248250005",        // 产品编码
        //                   "produName": "150KV滤抗-特高压宝塔山（试装）-低端", // 产品名称
        //                   "bomCode": "103248250005",          // BOM 编码
        //                   "planBeginDate": 1751328000000,     // 计划开始时间（毫秒级时间戳）
        //                   "planEndDate": 1751328000000,       // 计划结束时间（毫秒级时间戳）
        //                   "endDate": 1751328000000,            // 试验结束时间（毫秒级时间戳）
        //                   "type": null,                        // 类型（I:新增 U:修改 D:删除）
        //                   "auditCode": "Y",                    // 审核码（Y:已审核 N:未审核）
        //                   "contractName": "特高压宝塔山±800 千伏换流站工程", // 合同名称
        //                   "transferPlanTime": "2025-07-01",   // 生产转检计划时间（格式：YYYY-MM-DD）
        //                   "receiptScheduledTime": "2025-07-01", // 完工入库时间（格式：YYYY-MM-DD）
        //                   "companyCode": "DLDZ",              // 公司编码
        //                   "companyName": "泰开电力电子"       // 公司名称
        //           }
        // ],
        //           "mrls": [ 备料计划
        //           {
        //               "workOrderCode": "DSF01-2501230028",// 工单号
        //                   "mrlCode": "2305050447",           // 物料编码
        //                   "mrlName": "铝加工件",             // 物料名称
        //                   "qty": 1.000,                        // 数量（浮点数）
        //                   "unit": "套"                         // 单位
        //           }
        // ]
        //       }

        return data;
    }

    /**
     * 备料计划数据封装
     *
     * @param sourceId 流程生产订单唯一标识
     * @return
     * @throws BusinessException
     */
    private JSONArray getPickmInfo(String sourceId) throws BusinessException {
        // vsourcemorowid 来源生产订单明细id
        JSONArray pickmArr = new JSONArray();
        if (StringUtils.isEmpty(sourceId) || "~".equals(sourceId)) {
            return pickmArr;
        }
        SqlBuilder sqlBuilder = new SqlBuilder();
        sqlBuilder.append(" select c.code mrlcode, c.name mrlname, d.name unit, b.nplanoutastnum qty");
        sqlBuilder.append(" from mm_pickm_b b");
        sqlBuilder.append(" left join mm_pickm a on b.cpickmid = a.cpickmid");
        sqlBuilder.append(" left join bd_material c on b.cbmaterialid = c.pk_material");
        sqlBuilder.append(" left join bd_measdoc d on b.cbastunitid = d.pk_measdoc");
        sqlBuilder.append(" where b.dr = 0");
        sqlBuilder.append(" and ");
        // sqlBuilder.append("a.csourcebillid", sourceId);
        sqlBuilder.append("a.vsourcemorowid", sourceId);// 来源生产订单明细id
        logDl.error("查询备料计划数据：" + sqlBuilder);
        List<Map<String, Object>> result = (List<Map<String, Object>>) dao.executeQuery(sqlBuilder.toString(), new MapListProcessor());
        for (Map<String, Object> objectMap : result) {
            JSONObject bodyJson = new JSONObject();
            bodyJson.put("mrlCode", objectMap.get("mrlcode"));// 物料编码
            bodyJson.put("mrlName", objectMap.get("mrlname"));// 物料名称
            bodyJson.put("qty", objectMap.get("qty"));// 数量
            bodyJson.put("unit", objectMap.get("unit"));// 单位
            pickmArr.add(bodyJson);
        }
        if (pickmArr.isEmpty()) {
            logDl.error("查询备料计划为空，sourceId = " + sourceId + ",sql = " + sqlBuilder);
        }
        return pickmArr;

    }

    private JSONObject buildSyncCodeData(PMOAggVO vo) throws BusinessException {
//        [
//        {
//            "siteCode": "", // 工厂编码
//                "workOrderCode": "", // 工单号
//                "companyCode": "DLDZ", //公司编码
//                "companyName": "泰开电力电子",//公司名称
//                "releaseNo": [] // 出厂编号
//        }
//]
        PMOHeadVO hvo = vo.getParentVO();
        PMOItemVO pmoItem = vo.getChildrenVO()[0];
        // 生产部门 cdeptid
        String cdeptid = pmoItem.getCdeptid();
        String deptCode = MyHelper.transferField(DeptVO.getDefaultTableName(), DeptVO.CODE, DeptVO.PK_DEPT, cdeptid);
        JSONObject obj = new JSONObject();
        obj.put("siteCode", deptParams.getOrDefault(deptCode, ""));
        obj.put("workOrderCode", hvo.getVbillcode());

        BaseDAO dao = new BaseDAO();
        String orgsql = "select code,name from org_factory where pk_factory = '" + hvo.getPk_org() + "' ";
        Map<String, Object> tr = (Map<String, Object>) dao.executeQuery(orgsql, new MapProcessor());
        obj.put("companyCode", tr.get("code"));
        obj.put("companyName", tr.get("name"));
        JSONArray jsonArray = new JSONArray();
        for (PMOItemVO item : vo.getChildrenVO()) {
            HYPubBO hybo = new HYPubBO();
            Object materialtype = hybo.findColValue("bd_material_v", "materialtype", "pk_source = '" + item.getCmaterialid() + "' ");
            IBillcodeManage billcodeManage = NCLocator.getInstance().lookup(IBillcodeManage.class);;
            String code = billcodeManage.getPreBillCode_RequiresNew("xxxxx-code-rule", hvo.getPk_group(), hvo.getPk_org());
            String detailItem = materialtype + hvo.getDbilldate().toStdString().substring(0, 3) + hvo.getDbilldate().toStdString().substring(5, 6) + code;
            jsonArray.add(detailItem);
        }
        obj.put("releaseNo", jsonArray);

        return obj;
    }

    /**
     * 组装数据-取消审核流程生产订单
     */
    private JSONObject buildUnAuditSyncData(PMOAggVO aggVO) throws BusinessException {
        PMOHeadVO headVo = aggVO.getParentVO();
        PMOItemVO pmoItem = aggVO.getChildrenVO()[0];
        // 翻译字段值
        // 组织
        String pkOrg = headVo.getPk_org();
        String selectFields = FactoryVO.CODE + "," + FactoryVO.NAME;
        Map<String, Object> orgMap = MyHelper.transferFields(FactoryVO.getDefaultTableName(), selectFields, FactoryVO.PK_FACTORY, pkOrg);
        // 生产部门 cdeptid
        String cdeptid = pmoItem.getCdeptid();
        String deptCode = MyHelper.transferField(DeptVO.getDefaultTableName(), DeptVO.CODE, DeptVO.PK_DEPT, cdeptid);
        // 组装数据
        JSONObject data = new JSONObject();
        JSONObject orderParam = new JSONObject();
        orderParam.put("siteCode", deptParams.getOrDefault(deptCode, ""));
        orderParam.put("workOrderCode", headVo.getVbillcode());// 工单号
        orderParam.put("auditCode", "N"); // 审核状态（Y:已审核 N:未审核）
        if (orgMap != null) {
            orderParam.put("companyCode", orgMap.get(FactoryVO.CODE)); // 公司编码
            orderParam.put("companyName", orgMap.get(FactoryVO.NAME)); // 公司名称
        }
        JSONArray orderArr = new JSONArray();
        orderArr.add(orderParam);
        // 流程生产订单
        data.put("workOrders", orderArr);
        return data;
    }

}
