package nc.bs.ic.m4d.sign.rule;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import nc.bs.dao.BaseDAO;
import nc.bs.logging.Log;
import nc.bs.trade.business.HYPubBO;
import nc.bs.uapbd.util.MyHelper;
import nc.bs.uapbd.util.ThirdPartyPostRequestUtil;
import nc.impl.pubapp.pattern.rule.IRule;
import nc.jdbc.framework.processor.MapProcessor;
import nc.vo.ic.m4d.entity.MaterialOutBodyVO;
import nc.vo.ic.m4d.entity.MaterialOutVO;
import nc.vo.pub.BusinessException;

import java.util.Map;

/**
 * 入库领料-材料出库审核后推送艾普MES
 *
 * @author lihao
 */
public class PullProcessEpicMesRule implements IRule<MaterialOutVO> {
    public PullProcessEpicMesRule() {
    }

    public PullProcessEpicMesRule(String auditCode) {
        this.auditCode = auditCode;
    }

    public String auditCode = "Y";

    private static final String LOG_INFO_NAME = "dldzlog";
    private static final Log logDl = Log.getInstance(LOG_INFO_NAME);

    private Map<String, String> configParams;

    public void process(MaterialOutVO[] vos) {
        try {
            if (vos != null && vos.length != 0) {
                JSONArray jsonArray1 = new JSONArray();// 领料单据
                JSONArray jsonArray2 = new JSONArray();// 退库单据

                for (MaterialOutVO vo : vos) {
                    HYPubBO hybo = new HYPubBO();
                    String orgCode = (String) hybo.findColValue("org_purchaseorg", "code", "pk_purchaseorg = '" + vo.getHead().getPk_org() + "' ");
                    configParams = MyHelper.getConfigParams("Dldz-config", null);
                    if (configParams.isEmpty()) {
                        throw new BusinessException("电力电子的艾普MES接口缺少配置");
                    }
                    // 如果不是电力电子集团的取消推送
                    if (MyHelper.checkIfDldzOrg(orgCode, configParams)) {
                        continue;
                    }
                    // 领料单默认值17 退库单默认值37
                    if (vo.getBodys().length > 0 && vo.getBodys()[0].getNshouldassistnum().doubleValue() > 0) {
                        jsonArray1.add(this.buildSyncData(vo, 17));
                    }
                    if (vo.getBodys().length > 0 && vo.getBodys()[0].getNshouldassistnum().doubleValue() < 0) {
                        jsonArray2.add(this.buildSyncData(vo, 37));
                    }

                }

                if (!jsonArray1.isEmpty()) {
                    pushData("/prj-v5-web/ext/api/getMrlReq", jsonArray1);
                }
                if (!jsonArray2.isEmpty()) {
                    pushData("/prj-v5-web/ext/api/returnMrl", jsonArray2);
                }


            }
        } catch (BusinessException e) {
            logDl.error("EpicMes-MaterialOut-req = " + e.getMessage(), e);
        }
    }

    private JSONObject buildSyncData(MaterialOutVO vo, int businessType) throws BusinessException {
        JSONObject obj = new JSONObject();
        obj.put("billCode", vo.getHead().getVbillcode()); // 已存在的billCode字段
        obj.put("workOrderCode", null);// 工单号（可为空）
        obj.put("businessType", businessType); // 业务类型
        obj.put("supplierCode", null);// 供应商编码（可为空）
        obj.put("supplierName", null);// 供应商名称（可为空）
        obj.put("conditionalCode", null);// 状况码（可为空，用于控制业务逻辑）
        obj.put("auditCode", auditCode);// 审核码 N:未审核 Y:已审核 X:已作废
        obj.put("postingStatus", "Y");// 过账状态（Y:已过账，N:未过账）
        obj.put("confirmationCode", "Y"); // 确认码（Y:已确认，N:未确认）
        obj.put("changeFlag", null); // 变更标识（可为空，Y:已变更，N:未变更）


        BaseDAO dao = new BaseDAO();
        String orgsql = "select code,name from org_purchaseorg where pk_purchaseorg = '" + vo.getHead().getPk_org() + "' ";
        Map<String, Object> tr = (Map<String, Object>) dao.executeQuery(orgsql, new MapProcessor());
        obj.put("companyCode", tr.get("code"));// 公司编码
        obj.put("companyName", tr.get("name"));// 公司名称
        JSONArray jsonArray = new JSONArray();
        for (MaterialOutBodyVO item : vo.getBodys()) {
            JSONObject detailItem = new JSONObject();
            detailItem.put("billCode", vo.getHead().getVbillcode());  // 与主单据号一致
            detailItem.put("workOrderCode", null);// 工单号（关联工单）
            detailItem.put("rowNum", Integer.parseInt(item.getCrowno()));// 明细行号（整数）
            String mrlsql = "select code,name from bd_material_v where pk_source = '" + item.getCmaterialoid() + "' ";
            Map<String, Object> mrl = (Map<String, Object>) dao.executeQuery(mrlsql, new MapProcessor());
            detailItem.put("mrlCode", mrl.get("code"));// 物料编码
            detailItem.put("mrlName", mrl.get("name"));// 物料名称
            detailItem.put("planInDate", item.getDbizdate().toStdString()); // 计划入库日期（可为空）
            //  计划入库数量（浮点数）MES退货单数量为正，需要转换
            detailItem.put("planInQty", item.getNassistnum().abs().doubleValue());
            String unitsql = "select name from bd_measdoc where pk_measdoc = '" + item.getCastunitid() + "' ";
            Map<String, Object> unit = (Map<String, Object>) dao.executeQuery(unitsql, new MapProcessor());
            detailItem.put("unit", unit.get("name"));// 单位
            detailItem.put("contractNo", null);// 合同号（可为空）

            String areasql = "select code from bd_stordoc where pk_stordoc = '" + item.getCbodywarehouseid() + "' ";
            Map<String, Object> area = (Map<String, Object>) dao.executeQuery(areasql, new MapProcessor());
            detailItem.put("area", area.get("code"));// 仓库
            detailItem.put("subArea", item.getVcontractcode());// 库位
            jsonArray.add(detailItem);
        }
        obj.put("details", jsonArray);

        return obj;
    }

    private void pushData(String requestUrl, JSONArray param) throws BusinessException {
        String baseUrl = configParams.get("epicMesUrl");
        requestUrl = baseUrl + requestUrl;
        String reqJson = param.toJSONString();
        logDl.error("EpicMes-MaterialOut-req = " + reqJson);
        String result = ThirdPartyPostRequestUtil.sendPostRequest(requestUrl, reqJson);
        JSONObject resultObj = JSONObject.parseObject(result);
        logDl.error("EpicMes-MaterialOut-res = " + result);

        if (!"1".equals(resultObj.getString("flag"))) {
            throw new BusinessException("EpicMes-MaterialOut-error:" + resultObj.getString("msg"));
        } else {
            logDl.error("EpicMes-MaterialOut-suc,result[" + resultObj.toJSONString() + "]");
        }
    }

}
