package nc.bs.so.m30.rule.approve;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.bs.logging.Log;
import nc.bs.trade.business.HYPubBO;
import nc.bs.trade.business.HYSuperDMO;
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.bd.defdoc.DefdocVO;
import nc.vo.org.OrgVO;
import nc.vo.pmpub.project.ProjectHeadVO;
import nc.vo.pub.BusinessException;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.so.m30.entity.SaleOrderBVO;
import nc.vo.so.m30.entity.SaleOrderHVO;
import nc.vo.so.m30.entity.SaleOrderVO;
import nccloud.baseapp.core.log.NCCForUAPLogger;

import java.util.Map;

/**
 * 销售订单推送高压mes
 *
 * @author mzr
 */
public class AfterSoSyncRuleGyMes implements IRule<SaleOrderVO> {
    private static final String LOG_INFO_NAME = "gymeslog";
    private static final Log logger = Log.getInstance(LOG_INFO_NAME);
    private static final String reqUrl = "/bip/order/saleOrderAdd";
    private Map<String, String> configParams;

    @Override
    public void process(SaleOrderVO[] saleOrderVOs) {
        try {
            if (saleOrderVOs == null || saleOrderVOs.length == 0) {
                return;
            }
            configParams = MyHelper.getConfigParams("gy-config", null);
            if (configParams.isEmpty()) {
                throw new BusinessException("高压的接口缺少配置");
            }
            buildSyncData(saleOrderVOs);
        } catch (Exception e) {
            ExceptionUtils.wrappException(e);
        }
    }

    /**
     * 构建同步数据
     */
    private void buildSyncData(SaleOrderVO[] useVOs) throws BusinessException {
        BaseDAO baseDAO = new BaseDAO();
        HYPubBO hybo = new HYPubBO();
        for (SaleOrderVO 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;
            }

            SaleOrderHVO hvo = vo.getParentVO();
            SaleOrderBVO[] itemVOS = vo.getChildrenVO();
            // 客户
            String customerSql = " select name from bd_customer where dr = 0 and pk_customer = '" + hvo.getCcustomerid() + "' ";
            String customerName = (String) baseDAO.executeQuery(customerSql, new ColumnProcessor());
            // 创建人
            String userSql = " select user_name from sm_user where dr = 0 and cuserid = '" + hvo.getBillmaker() + "' ";
            String createName = (String) baseDAO.executeQuery(userSql, new ColumnProcessor());
            // 合同编号
            String vdef6 = hvo.getVdef6();
            String contractNum = getDefCode("zdy-001", vdef6);
            if (contractNum.isEmpty()) {
                contractNum = "11";
            }
            for (SaleOrderBVO item : itemVOS) {
                Object projectName = hybo.findColValue(ProjectHeadVO.getDefaultTableName(), ProjectHeadVO.PROJECT_NAME, ProjectHeadVO.PK_PROJECT + " = '" + item.getCprojectid() + "' ");
                String wlsql = " select code,name,graphid from bd_material where dr = 0 and pk_material = '" + item.getCmaterialvid() + "' ";
                Map<String, Object> mrlMap = (Map<String, Object>) baseDAO.executeQuery(wlsql, new MapProcessor());

                JSONObject itemObj = new JSONObject();
                itemObj.put("contractNum", contractNum);// 合同编码
                itemObj.put("bipOrderId", hvo.getVbillcode());// 销售订单号
                itemObj.put("bipId", item.getCsaleorderbid());// 主键ID
                itemObj.put("entryName", projectName);// 项目名称
                itemObj.put("productQuantity", item.getNastnum().doubleValue());// 数量
                itemObj.put("materialCode", mrlMap.get("code"));// 物料编码
                itemObj.put("materialName", mrlMap.get("name"));// 物料名称
                itemObj.put("drawingNumber", mrlMap.get("graphid"));// 图号
                itemObj.put("supplyDate", item.getDreceivedate().toString());// 供货日期-要求收货日期
                itemObj.put("remark", item.getVrownote());// 备注
                itemObj.put("bipCreateBy", createName);// 创建人
                itemObj.put("customers", customerName);// 客户
                pushData(itemObj);
            }
            /**
             * {
             *     "contractNum": "TZF2520201225 合同编码",
             *     "bipOrderId": "TZF2520201225 销售的订单号",
             *     "bipId": "主键ID",
             *     "entryName": "大唐河北故城50MW风电项目",
             *     "productQuantity": "数量个数 例如 1",
             *     "materialCode": "物料编码",
             *     "materialName": "物料名称",
             *     "drawingNumber": "图号编码 计划信息组织是高压的图号",
             *     "supplyDate": "2025-01-03 11:09:22",
             *     "remark": "备注",
             *     "bipCreateBy": "创建人ID",
             *     "customers": "客户 例如贵州电网xxx"
             * }
             */
        }
    }

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

        if (!"200".equals(resultObj.getString("code"))) {
            logger.error("gyMes-SaleOrder-error,result[" + resultObj.toJSONString() + "]");
            throw new BusinessException("gyMes-SaleOrder-error:" + resultObj.getString("message"));
        }
    }

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

    /**
     * 获取自定义项信息
     */
    private String getDefCode(String code, String pk_defdoc) {
        String res = "";
        String strWhere = " pk_defdoclist in (select pk_defdoclist from bd_defdoclist where code='" + code + "' and dr=0 )  and dr = 0 and pk_defdoc = '" + pk_defdoc + "'";
        try {
            DefdocVO[] defdocVOs = (DefdocVO[]) new HYSuperDMO().queryByWhereClause(DefdocVO.class, strWhere);
            if (defdocVOs != null && defdocVOs.length > 0) {
                res = defdocVOs[0].getCode().trim();
            }
        } catch (DAOException e) {
            logger.error("gyMes-SaleOrder-error,getDefCode[" + e.getMessage() + "]");
        }
        return res;

    }


}

