//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

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.Logger;
import nc.bs.trade.business.HYPubBO;
import nc.bs.uapbd.util.ThirdPartyPostRequestUtil;
import nc.impl.pubapp.pattern.rule.IRule;
import nc.itf.arap.goldentax.SysParaInitQuery;
import nc.jdbc.framework.processor.ColumnListProcessor;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.jdbc.framework.processor.MapProcessor;
import nc.uif.pub.exception.UifException;
import nc.vo.bd.material.MaterialVO;
import nc.vo.ic.m4d.entity.MaterialOutBodyVO;
import nc.vo.ic.m4d.entity.MaterialOutVO;
import nc.vo.pub.BusinessException;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.scmpub.res.billtype.IABillType;

import java.util.HashMap;
import java.util.Map;

public class
PullProcess implements IRule<MaterialOutVO> {
    public PullProcess() {
    }

    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();
                    Object orgCode = hybo.findColValue("org_purchaseorg", "code", "pk_purchaseorg = '" + vo.getHead().getPk_org() + "' ");
                    //如果不是电力电子集团的取消推送
                    if(!checkIfIncludeOrg((String) orgCode)){
                        continue;
                    }
                    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.size() > 0){
                    pushData("/prj-v5-web/ext/api/getMrlReq", jsonArray1);
                }
                if(jsonArray2.size() > 0){
                    pushData("/prj-v5-web/ext/api/returnMrl", jsonArray2);
                }



            }
        } catch (UifException e) {
            throw new RuntimeException(e);
        } catch (BusinessException e) {
            throw new RuntimeException(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", null);
        obj.put("postingStatus", "Y");
        obj.put("confirmationCode", "Y");
        obj.put("changeFlag", null);


        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());
            detailItem.put("planInQty", item.getNassistnum().abs().doubleValue());//MES退货单数量为正，需要转换
            String unitsql = "select code 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("code"));
            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 = SysParaInitQuery.getParaString("GLOBLE00000000000000", "EPICMESURL");
//        baseUrl="http://192.168.55.39:8080";
        requestUrl = baseUrl + requestUrl;
        String result = ThirdPartyPostRequestUtil.sendPostRequest(requestUrl, param.toJSONString());
        JSONObject resultObj = JSONObject.parseObject(result);
        Logger.error("EpicMes-Material-req = " + result);

        if ("false".equals(resultObj.getString("success"))) {
            throw new BusinessException("EpicMes-Material-failerror:" + resultObj.getString("msg"));
        } else {
            Logger.error("EpicMes-Material-suc,result[" + resultObj.toJSONString() + "]");
        }
    }
    /**
     * 检查当前组织是否为电力电子
     */
    public boolean checkIfIncludeOrg(String code) throws BusinessException {
        // 当当前操作人员是BIP的时候 直接return 不走同步MES的业务逻辑
        String targetCode = SysParaInitQuery.getParaString("GLOBLE00000000000000", "INCLUDEORG");
//        targetCode="C013;C014;C015;C017";
        if (targetCode == null || nc.vo.am.common.util.StringUtils.isEmpty(targetCode)) {
            throw new BusinessException("未配置组织参数,请前往 [业务参数设置-全局] 配置INCLUDEORG参数");
        }
        String[] orgItem = targetCode.split(";");
        for (String orgCode : orgItem) {
            if (!orgCode.isEmpty() && orgCode.equals(code)) {
                Logger.debug("当前处理组织校验为电力电子:" + code);
                return true;
            }
        }
        return false;
    }

}
