package nccloud.api.uapbd.material.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
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.dao.BaseDAO;
import nc.bs.logging.Log;
import nc.bs.uapbd.util.MyHelper;
import nc.bs.uapbd.util.ThirdPartyPostRequestUtil;
import nc.jdbc.framework.processor.MapProcessor;
import nc.vo.bd.material.MaterialVO;
import nc.vo.bd.material.marbasclass.MarBasClassVO;
import nc.vo.bd.material.stock.MaterialStockVO;
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 LOG_INFO_NAME = "dldzlog";
    private static final Log logDl = Log.getInstance(LOG_INFO_NAME);
    private static final String reqUrl = "/prj-v5-web/ext/api/mrl";
    private Map<String, String> configParams;

    @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是事件编码 1002-新增后 1004-修改后 1071-状态由停用变为启用后 1069-状态由启用变为停用后
        if ("1002".equals(eventType) || "1004".equals(eventType)) {
            configParams = MyHelper.getConfigParams("Dldz-config", null);
            if (configParams.isEmpty()) {
                throw new BusinessException("电力电子的艾普MES接口缺少配置");
            }
            buildSyncData(useVOs, eventType);
        } else if ("1071".equals(eventType) || "1069".equals(eventType)) {
            configParams = MyHelper.getConfigParams("Dldz-config", null);
            if (configParams.isEmpty()) {
                throw new BusinessException("电力电子的艾普MES接口缺少配置");
            }

        }
    }

    /**
     * 构建同步数据
     */
    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, configParams)) {
                continue;
            }
            // 字段值翻译
            String pk_marbasclass = vo.getPk_marbasclass();
            String mrlTypeCOde = MyHelper.transferField(MarBasClassVO.getDefaultTableName(), MarBasClassVO.CODE, MarBasClassVO.PK_MARBASCLASS, pk_marbasclass);
            // 计量单位
            String pkMaterial = vo.getPk_material();
            Map unitMap = getGoodsInfo(pkMaterial);

            // 1=未启用;2=已启用;3=已停用;
            Integer enablestate = vo.getEnablestate();
            String statusCode = (3 == enablestate) ? "N" : "Y";
            // 组装数据
            JSONObject singleObj = new JSONObject();
            singleObj.put("id", null);// 唯一标识（主键）
            singleObj.put("siteCode", orgCode);// 工厂编码
            singleObj.put("mrlCode", vo.getCode());// 物料编码
            singleObj.put("mrlName", vo.getName());// 物料名称
            singleObj.put("unit", unitMap.get("unitname"));// 单位
            singleObj.put("model", vo.getMaterialtype());// 型号
            singleObj.put("specification", vo.getMaterialspec());// 规格
            singleObj.put("type", getType(eventType));// 类型（I:新增 U:修改 D:删除）
            singleObj.put("deputyUnit", unitMap.get("deputy_unitname"));// 副单位
            singleObj.put("auditCode", "1");// 审核码
            singleObj.put("statusCode", statusCode);// 状态码（Y表示启用，N表示停用）
            singleObj.put("mrlTypeErp", getGoodsProject(pkMaterial));// 物料类型ERP（1:专用件，3:通用件）
            singleObj.put("mrlType", mrlTypeCOde);// 物料分类编码
            singleObj.put("convertRate", unitMap.getOrDefault("convertRate", "1"));// 单位换算率
            // singleObj.put("isCheck", "1");// 是否选中（1:是，0:否）
            pushData(singleObj);
        }
    }

    /**
     * 推送同步数据
     */
    private void pushData(JSONObject param) throws BusinessException {
        // String jsonString = param.toJSONString();
        // 转json字符串的时候保留null值
        String jsonStr = JSON.toJSONString(param,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty
        );
        logDl.error("EpicMes-Material-param = " + jsonStr);
        String baseUrl = configParams.get("epicMesUrl");
        String requestUrl = baseUrl + reqUrl;
        logDl.error("EpicMes-Material-url = " + requestUrl);
        String result = ThirdPartyPostRequestUtil.sendPostRequest(requestUrl, jsonStr);
        JSONObject resultObj = JSONObject.parseObject(result);
        logDl.error("EpicMes-Material-res = " + result);

        if (!"1".equals(resultObj.getString("flag"))) {
            // throw new BusinessException("EpicMes-Material-error:" + resultObj.getString("msg"));
            logDl.error("EpicMes-Material-error,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");
        map.put("1069", "U");
        map.put("1071", "U");
        return map.getOrDefault(eventType, "I");
    }

    private Map getGoodsInfo(String pkMaterial) throws BusinessException {
        String sql = " select a.pk_measdoc, c.name unitname, b.pk_measdoc deputyUnit, d.name deputy_unitname, nvl(b.measrate, '1/1') measrate " +
                "from bd_material a " +
                "left join bd_materialconvert b on a.pk_material = b.pk_material " +
                "left join bd_measdoc c on a.pk_measdoc = c.pk_measdoc " +
                "left join bd_measdoc d on b.pk_measdoc = d.pk_measdoc " +
                "where a.pk_material = '" + pkMaterial + "' ";
        // logDl.error("EpicMes-Material-getUnitInfo-sql = " + sql);
        Map map = (Map) new BaseDAO().executeQuery(sql, new MapProcessor());
        map.put("convertRate", MyHelper.transferSpecialField(map.get("measrate") + ""));
        return map;
    }

    private String getGoodsProject(String pkMaterial) throws BusinessException {
        // 物料-库存信息页签勾选项目为专用件、未勾选项目为通用件
        String mrlTypeErp = "3"; // 物料类型ERP（1:专用件，3:通用件）
        String fixasst2 = MyHelper.transferField(MaterialStockVO.getDefaultTableName(), MaterialStockVO.FIXASST2, MaterialStockVO.PK_MATERIAL, pkMaterial);
        if ("Y".equals(fixasst2)) {
            mrlTypeErp = "1";
        }
        return mrlTypeErp;
    }

}
