package nc.bs.mmpac.pmo.pac0002.bp.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.dao.BaseDAO;
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.jdbc.framework.processor.ColumnProcessor;
import nc.jdbc.framework.processor.MapProcessor;
import nc.vo.bc.pmpub.project.ProjectHeadVO;
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.OrgVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.sm.UserVO;

import java.util.Map;

/**
 * 精密-流程生产订单投放后推送QMS
 *
 * @author mzr
 * @date 2025/9/9
 */
public class AfterPmoSyncJmQMSRule implements IRule<PMOAggVO> {

    private static final String LOG_INFO_NAME = "qyMesLog";
    private static final Log logger = Log.getInstance(LOG_INFO_NAME);
    private static final String reqUrl = "/IF_QyErpApi.ashx?action=addscjh";
    private Map<String, String> configParams;
    private String flag = "";

    public AfterPmoSyncJmQMSRule() {
    }

    public AfterPmoSyncJmQMSRule(String flag) {
        this.flag = flag;
    }

    @Override
    public void process(PMOAggVO[] pmoAggVOS) {
        try {
            configParams = MyHelper.getConfigParams("jm-config", null);
            if (configParams.isEmpty()) {
                throw new BusinessException("精密的启源接口缺少配置");
            }
            buildSyncData(pmoAggVOS);
        } catch (BusinessException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 构建同步数据
     */
    private void buildSyncData(PMOAggVO[] useVOs) throws BusinessException {
        BaseDAO baseDAO = new BaseDAO();
        for (PMOAggVO vo : useVOs) {
            // 判断物料的业务单元是否是配置的公司，不是则跳过
            String pkOrg = vo.getParentVO().getPk_org();
            String orgCode = MyHelper.transferField(OrgVO.getDefaultTableName(), OrgVO.CODE, OrgVO.PK_ORG, pkOrg);
            if (checkIfOrg(orgCode, configParams)) {
                continue;
            }
            // 组装数据
            JSONObject singleObj = new JSONObject();
            PMOHeadVO pmoHeadVO = vo.getParentVO();
            PMOItemVO[] itemVOS = vo.getChildrenVO();
            String sql = " select user_name from sm_user where dr = 0 and cuserid = '" + pmoHeadVO.getBillmaker() + "' ";
            String billmakerName = (String) baseDAO.executeQuery(sql, new ColumnProcessor());

            singleObj.put("batchid", System.currentTimeMillis());
            singleObj.put("scdh", pmoHeadVO.getVbillcode());
            singleObj.put("xdrq", pmoHeadVO.getDbilldate().toString());
            singleObj.put("jhy", billmakerName);
            singleObj.put("bz", pmoHeadVO.getVnote());
            // 处理Content数组
            JSONArray contentArray = new JSONArray();
            for (PMOItemVO item : itemVOS) {
                String cmaterialvid = item.getCmaterialvid();
                String whereSql = " select code,name,materialspec,materialtype from bd_material where pk_material = '" + cmaterialvid + "' ";
                Map<String, Object> mrlmap = (Map<String, Object>) baseDAO.executeQuery(whereSql, new MapProcessor());
                String mocloser = item.getMocloser();// BIP关闭人
                String mocloserName = MyHelper.getStrValByCondition("sm_user", UserVO.USER_NAME,
                        UserVO.CUSERID + " = '" + mocloser + "'");
                String cprojectid = item.getCprojectid();// 项目id
                String projectCode = MyHelper.getStrValByCondition(ProjectHeadVO.getDefaultTableName(), ProjectHeadVO.PROJECT_CODE,
                        ProjectHeadVO.PK_PROJECT + " = '" + cprojectid + "'");

                // 行状态 0=自由;4=审批通过;1=投放;2=完工;3=关闭;
                Integer fitemstatus = item.getFitemstatus();

                JSONObject itemObj = new JSONObject();
                itemObj.put("sgdh", projectCode);// 施工单号-BIP项目编码
                itemObj.put("xshth", item.getVfirstcode());// 销售合同号-BIP源头单据号
                itemObj.put("htqdxh", item.getVfirstrowno());// 合同清单序号-BIP源头单据行号
                itemObj.put("wlbh", mrlmap.get("code"));// 产品编号
                itemObj.put("wlmc", mrlmap.get("name"));// 产品名称
                itemObj.put("wlxhgg", mrlmap.get("materialspec") + (String) mrlmap.get("materialtype"));// 产品型号规格
                itemObj.put("jhsl", item.getNastnum().toString());// 计划数量，该产品的生产计划数量
                UFDateTime tplanendtime = item.getTplanendtime();
                String tplanendtimeStr = "";
                if (tplanendtime != null) {
                    tplanendtimeStr = tplanendtime.toString();
                }
                itemObj.put("jhrq", tplanendtimeStr);// 计划数量，该产品的生产计划数量
                int flag_wg = 0;
                int flag_jqbz = 0;
                if (fitemstatus == 2) {
                    flag_wg = 1;
                }
                if (fitemstatus == 3) {
                    flag_wg = 1;
                    flag_jqbz = 1;
                }
                itemObj.put("flag_wg", flag_wg);// 完工标志 1/0 1.完工
                itemObj.put("flag_jqbz", flag_jqbz);// 结清标志 1 代表结清  0 或者空代表非结清
                itemObj.put("jqr", mocloserName);// 结清人-BIP关闭人
                UFDateTime tmoclosedtime = item.getTmoclosedtime();
                String tmoclosedtimeStr = "";
                if (tmoclosedtime != null) {
                    tmoclosedtimeStr = tmoclosedtime.toString();
                }
                itemObj.put("jqrq", tmoclosedtimeStr);// 结清日期-BIP关闭日期
                itemObj.put("bz", item.getVnote());// 清单备注
                contentArray.add(itemObj);
            }

            singleObj.put("Content", contentArray);
            pushData(singleObj);
        }
    }

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

        if (!"true".equals(resultObj.getString("success"))) {
            // throw new BusinessException("QMS-PMO-JM-error:" + resultObj.getString("msg"));
            logger.error("QMS-PMO-JM-error,result[" + resultObj.toJSONString() + "]");
        }
    }

    private boolean checkIfOrg(String code, Map<String, String> configParams) throws BusinessException {
        String targetCode = configParams.get("jmOrg");
        if (targetCode == null || nc.vo.am.common.util.StringUtils.isEmpty(targetCode)) {
            throw new BusinessException("未配置组织参数");
        }
        String[] orgItem = targetCode.split(",");
        for (String orgCode : orgItem) {
            if (!orgCode.isEmpty() && orgCode.equals(code)) {
                return false;
            }
        }
        return true;
    }


}
