package nccloud.api.uapbd.material.listener;

import com.alibaba.fastjson.JSONObject;
import nc.bs.bd.baseservice.ArrayClassConvertUtil;
import nc.bs.businessevent.IBusinessEvent;
import nc.bs.businessevent.IBusinessListener;
import nc.bs.businessevent.bd.BDCommonEvent;
import nc.bs.logging.Logger;
import nc.bs.uapbd.util.MyHelper;
import nc.bs.uapbd.util.ThirdPartyPostRequestUtil;
import nc.itf.arap.goldentax.SysParaInitQuery;
import nc.vo.bd.material.MaterialVO;
import nc.vo.bd.material.marbasclass.MarBasClassVO;
import nc.vo.bd.material.measdoc.MeasdocVO;
import nc.vo.org.FactoryVO;
import nc.vo.pub.BusinessException;

import java.util.HashMap;
import java.util.Map;

/**
 * 物料新增修改后同步艾普MES的物料
 *
 * @author mzr
 * @date 2025/06/27
 */
public class MaterialToEpicMesListener implements IBusinessListener {

    private static final String reqUrl = "/prj-v5-web/ext/api/mrl";

    @Override
    public void doAction(IBusinessEvent event) throws BusinessException {
        BDCommonEvent e = (BDCommonEvent) event;
        String eventType = event.getEventType();
        Object[] objs = e.getObjs();
        MaterialVO[] useVOs = ArrayClassConvertUtil.convert(objs, MaterialVO.class);
        // EventType是事件编码
        if ("1002".equals(eventType)) {
            // 新增后
            buildSyncData(useVOs, eventType);
        } else if ("1004".equals(eventType)) {
            // 修改后
            buildSyncData(useVOs, eventType);
        }
    }

    /**
     * 构建同步数据
     */
    private void buildSyncData(MaterialVO[] useVOs, String eventType) throws BusinessException {
        for (MaterialVO vo : useVOs) {
            // 判断物料的业务单元是否是电力电子公司，不是则跳过
            String pkOrg = vo.getPk_org();
            String orgCode = MyHelper.transferField(FactoryVO.getDefaultTableName(), FactoryVO.CODE, FactoryVO.PK_FACTORY, pkOrg);
            if (!MyHelper.checkIfDldzOrg(orgCode)) {
                continue;
            }
            // 1=未启用;2=已启用;3=已停用;
            Integer enablestate = vo.getEnablestate();
            String statusCode = (3 == enablestate) ? "N" : "Y";
            JSONObject singleObj = new JSONObject();
            singleObj.put("id", null);// 唯一标识（主键）
            singleObj.put("siteCode", null);// 工厂编码
            singleObj.put("mrlCode", vo.getCode());// 物料编码
            singleObj.put("mrlName", vo.getName());// 物料名称
            String pkMeasdoc = vo.getPk_measdoc();
            String unitName = MyHelper.transferField(MeasdocVO.getDefaultTableName(), MeasdocVO.NAME, MeasdocVO.PK_MEASDOC, pkMeasdoc);
            singleObj.put("unit", unitName);// 单位
            singleObj.put("model", vo.getMaterialtype());// 型号
            singleObj.put("specification", vo.getMaterialspec());// 规格
            singleObj.put("type", getType(eventType));// 类型（I:新增 U:修改 D:删除）
            singleObj.put("deputyUnit", null);// 副单位
            singleObj.put("auditCode", "1");// 审核码
            singleObj.put("statusCode", statusCode);// 状态码（Y表示启用，N表示停用）
            singleObj.put("mrlTypeErp", "1");// 物料类型ERP（1:专用件，3:通用件）
            String pk_marbasclass = vo.getPk_marbasclass();
            String mrlTypeCOde = MyHelper.transferField(MarBasClassVO.getDefaultTableName(), MarBasClassVO.CODE, MarBasClassVO.PK_MARBASCLASS, pk_marbasclass);
            singleObj.put("mrlType", mrlTypeCOde);// 物料分类编码
            singleObj.put("convertRate", "1");// 单位换算率
            singleObj.put("isCheck", "1");// 是否选中（1:是，0:否）
            pushData(singleObj);
        }
    }

    /**
     * 推送同步数据
     */
    private void pushData(JSONObject param) throws BusinessException {
        String baseUrl = SysParaInitQuery.getParaString("GLOBLE00000000000000", "EPICMESURL");
        String requestUrl = baseUrl + reqUrl;
        String result = ThirdPartyPostRequestUtil.sendPostRequest(requestUrl, param.toJSONString());
        JSONObject resultObj = JSONObject.parseObject(result);
        Logger.error("EpicMes-Material-req = " + result);

        if ("false".equals(resultObj.getString("success"))) {
            throw new BusinessException("EpicMes-Material-fail，error:" + resultObj.getString("msg"));
        } else {
            Logger.error("EpicMes-Material-suc,result[" + resultObj.toJSONString() + "]");
        }
    }

    private String getType(String eventType) {
        // 类型（I:新增 U:修改 D:删除）
        Map<String, String> map = new HashMap<>();
        map.put("1002", "I");
        map.put("1004", "U");
        return map.getOrDefault(eventType, "I");
    }

}
