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.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.pmpub.project.ProjectHeadVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDateTime;

import java.util.Map;

/**
 * 箱变-流程生产订单审批后推送QMS
 *
 * @author lihao
 * @date 2025/8/25
 */
public class AfterApproveSyncQMSRule 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;

    @Override
    public void process(PMOAggVO[] pmoAggVOS) {
        try {
            configParams = MyHelper.getConfigParams("xb-config", null);
            if (configParams.isEmpty()) {
                throw new BusinessException("箱变的QMS接口缺少配置");
            }
            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 cprojectid = item.getCprojectid();// 项目id
                String projectCode = MyHelper.getStrValByCondition(ProjectHeadVO.getDefaultTableName(), ProjectHeadVO.PROJECT_CODE,
                        ProjectHeadVO.PK_PROJECT + " = '" + cprojectid + "'");

                JSONObject itemObj = new JSONObject();
                itemObj.put("sgdh", pmoHeadVO.getVbillcode());
                itemObj.put("xshth", projectCode);
                itemObj.put("htqdxh", item.getVfirstrowno());
                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);
                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-XB-param = " + jsonStr);
        // NCCForUAPLogger.debug("QMS-PMO-XB-param = " + jsonStr);
        String baseUrl = configParams.get("qmsBaseUrl");
        String requestUrl = baseUrl + reqUrl;
        logger.error("QMS-PMO-XB-url = " + requestUrl);
        String result = ThirdPartyPostRequestUtil.sendPostRequest(requestUrl, jsonStr);
        JSONObject resultObj = JSONObject.parseObject(result);
        logger.error("QMS-PMO-XB-res = " + result);

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

    private boolean checkIfOrg(String code, Map<String, String> configParams) throws BusinessException {
        String targetCode = configParams.get("xbOrg");
        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;
    }


}
