package nc.bs.bd.bom.bom0202.rule;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import nc.bs.logging.Log;
import nc.bs.uapbd.util.MyHelper;
import nc.bs.uapbd.util.ThirdPartyPostRequestUtil;
import nc.impl.pubapp.pattern.rule.IRule;
import nc.util.mmf.framework.base.MMValueCheck;
import nc.vo.bd.bom.bom0202.entity.AggBomVO;
import nc.vo.bd.bom.bom0202.entity.BomItemVO;
import nc.vo.bd.bom.bom0202.entity.BomVO;
import nc.vo.bd.material.MaterialVO;
import nc.vo.org.OrgVO;
import nc.vo.pub.BusinessException;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;

import java.util.Map;

/**
 * BOM修改后同步艾普MES的BOM
 *
 * @author mzr
 * @date 2025/08/29
 */
public class BomSaveAfterEpicMesRule implements IRule<AggBomVO> {
    private static final String LOG_INFO_NAME = "dldzlog";
    private static final Log logDl = Log.getInstance(LOG_INFO_NAME);
    private static final String reqUrl = "/prj-v5-web/ext/api/bom";
    private Map<String, String> configParams;

    @Override
    public void process(AggBomVO[] vos) {
        if (!MMValueCheck.isEmpty(vos)) {
            try {
                configParams = MyHelper.getConfigParams("Dldz-config", null);
                JSONArray data = buildSyncData(vos);
                if (!data.isEmpty()) {
                    pushData(data);
                }
            } catch (BusinessException e) {
                ExceptionUtils.wrappException(e);
            }
        }
    }

    /**
     * 构建同步数据
     */
    private JSONArray buildSyncData(AggBomVO[] useVOs) throws BusinessException {
        JSONArray data = new JSONArray();
        for (AggBomVO vo : useVOs) {
            // 判断物料的业务单元是否是电力电子公司，不是则跳过
            BomVO hvo = (BomVO) vo.getParentVO();
            String pkOrg = (String) hvo.getAttributeValue("pk_org");
            String orgCode = MyHelper.transferField(OrgVO.getDefaultTableName(), OrgVO.CODE, OrgVO.PK_ORG, pkOrg);
            if (MyHelper.checkIfDldzOrg(orgCode, configParams)) {
                continue;
            }
            BomItemVO[] childrenVOs = vo.getChildrenVO();
            if (MMValueCheck.isEmpty(childrenVOs)) {
                continue;
            }
            // 只推送生产BOM 1=生产BOM;2=包装BOM;3=配置BOM;
            Integer fbomtype = hvo.getFbomtype();
            if (fbomtype != 1) {
                continue;
            }
            String hcmaterialid = hvo.getHcmaterialid();// 父项物料编码
            String hversion = hvo.getHversion();// BOM版本号

            String mitm = MyHelper.getStrValByCondition(MaterialVO.getDefaultTableName(), MaterialVO.CODE,
                    MaterialVO.PK_MATERIAL + " = '" + hcmaterialid + "'");
            for (BomItemVO childrenVO : childrenVOs) {
                String cmaterialid = childrenVO.getCmaterialid();
                String sitm = MyHelper.getStrValByCondition(MaterialVO.getDefaultTableName(), MaterialVO.CODE,
                        MaterialVO.PK_MATERIAL + " = '" + cmaterialid + "'");
                // 组装数据
                JSONObject singleObj = new JSONObject();
                singleObj.put("mitm", mitm); // 制造物料编码(ERP父项物料编码)
                singleObj.put("sitm", sitm); // 子物料编码
                singleObj.put("orderNum", hversion); // 合同号(ERP中电力电子项目号=BOM版本号)
                singleObj.put("qana", childrenVO.getNassitemnum().toString()); // 数量(ERP子项数量)
                singleObj.put("ver", hversion); // BOM版本号
                singleObj.put("remark", childrenVO.getVnote()); // 备注
                data.add(singleObj);
            }
            /**
             * [
             *     {
             *         "mitm": "DSF01-2501230028",
             *         "sitm": "2305050447",
             *         "orderNum": "111",
             *         "qana": 1,
             *         "ver": "1",
             *         "remark": ""
             *     }
             * ]
             */

        }
        return data;
    }

    /**
     * 推送同步数据
     */
    private void pushData(JSONArray param) throws BusinessException {
        // 转json字符串的时候保留null值
        String jsonStr = JSON.toJSONString(param,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty
        );
        logDl.error("EpicMes-BOM-param = " + jsonStr);
        // NCCForUAPLogger.debug("EpicMes-BOM-param = " + jsonStr);
        String baseUrl = configParams.get("epicMesUrl");
        String requestUrl = baseUrl + reqUrl;
        logDl.error("EpicMes-BOM-url = " + requestUrl);
        String result = ThirdPartyPostRequestUtil.sendPostRequest(requestUrl, jsonStr);
        JSONObject resultObj = JSONObject.parseObject(result);
        logDl.error("EpicMes-BOM-res = " + result);
        // NCCForUAPLogger.debug("EpicMes-BOM-result = " + result);
        if (!"1".equals(resultObj.getString("flag"))) {
            // throw new BusinessException("EpicMes-BOM-error:" + resultObj.getString("msg"));
            logDl.error("EpicMes-BOM-error,result[" + resultObj.toJSONString() + "]");
        }
    }
}
