package nc.bs.mmpac.pickm.bp.rule;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import nc.bs.dao.BaseDAO;
import nc.bs.logging.Log;
import nc.bs.uapbd.util.ThirdPartyPostRequestUtil;
import nc.impl.pubapp.pattern.rule.IRule;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.pubitf.para.SysInitQuery;
import nc.vo.bd.material.MaterialVO;
import nc.vo.bd.rt.rt0004.entity.RcVO;
import nc.vo.cmp.util.StringUtils;
import nc.vo.mmpac.pickm.entity.AggPickmVO;
import nc.vo.mmpac.pickm.entity.PickmHeadVO;
import nc.vo.mmpac.pickm.entity.PickmItemVO;
import nc.vo.org.OrgVO;
import nc.vo.pub.BusinessException;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.pubapp.pattern.pub.SqlBuilder;
import nc.vo.scmpub.util.ArrayUtil;

import java.util.ArrayList;
import java.util.List;

public class AfterApproveRuleSyncRZWMS implements IRule<AggPickmVO> {

    private static Log log = Log.getInstance("rzmomlog");

    private static BaseDAO dao = new BaseDAO();

    @Override
    public void process(AggPickmVO[] vos) {
        if (ArrayUtil.isEmpty(vos)) {
            return;
        }
        try {
            // 检查并筛选领料组织
            List<AggPickmVO> newAggPickmVOS = checkAndFilterBillSrcOrg(vos);
            if (newAggPickmVOS.isEmpty()) {
                return;
            }
            pushToRZMOM(newAggPickmVOS.toArray(new AggPickmVO[0]));
        } catch (Exception e) {
            ExceptionUtils.wrappException(e);
        }
    }

    private void buildSyncData(PickmHeadVO head, PickmItemVO[] bodys, JSONArray details) throws BusinessException {
        Integer fsourcetype = head.getFsourcetype();
        if(fsourcetype!=0){
            return;
        }
        for (PickmItemVO body : bodys) {
            JSONObject singleObj = new JSONObject();
            String vsourcebillcode = head.getVsourcebillcode();
            String wlbm_wbid =body.getCbmaterialvid();

            String scgx_wbid =head.getVstdprocid();
            //wbid	varchar (200)	第三方系统主键id
            singleObj.put("wbid", head.getCpickmid()+"_"+body.getCpickm_bid()); // 第三方系统主键id
            //wbzbid	varchar (200)	第三方系统分组id
            singleObj.put("wbzbid", head.getCpickmid());
            //operate	int	操作状态	必填	1新增/修改、2删除（删除时只需上传wbid）
            singleObj.put("operate", "1");

            //wbqjpx	varchar(2000)	全局排序	必填	BOM表物料行号
            singleObj.put("wbqjpx", body.getVrowno());

            //scjh_wbid	varchar(100)	第三方系统生产计划ID	必填	生产计划号外部ID，一般ERP系统的生产订单号。
            singleObj.put("scjh_wbid", head.getCsourcebillid());

            //jhxh	numeric(5)	计划序号	-生产订单行号
            singleObj.put("jhxh", head.getVsourcebillrowno());

            singleObj.put("wlbm_wbid", wlbm_wbid); // 第三方系统材料id

            //bomlx	int	BOM类型	必填	默认=0，即传入生产BOM（1为包装BOM）。
            singleObj.put("bomlx", 0);

            singleObj.put("dwyl", body.getNunituseastnum().getDouble()); // 单位用量
            singleObj.put("djyl", body.getNplanoutastnum().getDouble()); // 单据用量
            singleObj.put("clyl", body.getNplanoutastnum().getDouble()); // 材料用量

//            String rccode = transferCodeByPk(RcVO.getDefaultTableName(), RcVO.VRCCODE, RcVO.CRCID, head.getVstdprocid());
            singleObj.put("scgx_wbid", body.getVbdef11());
//            singleObj.put("scgx_wbid", rccode); // 第三方系统使用工序id

            //sdbj	int	锁定标记	必填	默认1：正常业务ERP审核后，传输至锐制MOM
            singleObj.put("sdbj", 1);
            //shbj	int	审核标记	必填	默认1：正常业务ERP审核后，传输至锐制MOM
            singleObj.put("shbj", 1);

            //jylxbm --
            singleObj.put("jylxbm", head.getVbusitype());
            details.add(singleObj);

        }
    }

    private List<AggPickmVO> checkAndFilterBillSrcOrg(AggPickmVO[] aggPickmVOS) throws BusinessException {
        List<AggPickmVO> aggvoList = new ArrayList<>();
        for (AggPickmVO aggvo : aggPickmVOS) {
            String pkOrg = aggvo.getParentVO().getPk_org();
            String orgCode = transferCodeByPk(OrgVO.getDefaultTableName(), OrgVO.CODE, OrgVO.PK_ORG, pkOrg);
            if ("C022".equals(orgCode)&& 1 == aggvo.getParentVO().getFbillstatus()&&aggvo.getChildrenVO()!=null && aggvo.getChildrenVO().length > 0) {
                aggvoList.add(aggvo);
            }
        }
        return aggvoList;
    }

    private void pushToRZMOM(AggPickmVO[] aggPickmVOS) throws BusinessException {
        String rzwmsip = SysInitQuery.getParaString("GLOBLE00000000000000", "RZWMSIP");
        JSONObject jsonObject = new JSONObject();
        JSONObject dataIn = new JSONObject();
        JSONObject dataIn2 = new JSONObject();
        JSONArray details = new JSONArray();
        jsonObject.put("dataflow", "用友BIP→RZMOMv6");
        jsonObject.put("actionCode", "scbomb");

        for (AggPickmVO aggPickmVO : aggPickmVOS) {
            PickmHeadVO head = aggPickmVO.getParentVO();
            PickmItemVO[] bodys = (PickmItemVO[]) aggPickmVO.getChildrenVO();
            buildSyncData(head, bodys, details);
        }
        dataIn2.put("Details", details);
        dataIn.put("Data", dataIn2);
        jsonObject.put("data", dataIn);
        log.error("生产BOW推送锐制请求报文：" + jsonObject.toJSONString());
        String result = ThirdPartyPostRequestUtil.sendPostRequest(rzwmsip, jsonObject.toJSONString());
        JSONObject resultObj = JSONObject.parseObject(result);
        if (resultObj == null || !"true".equals(resultObj.getString("success"))) {
            String errorMsg = resultObj == null ? "接口返回为空" : resultObj.getString("msg");
            throw new BusinessException("RZ同步失败，原因：" + errorMsg);
        }else{
            log.error("RZMOM同步成功，返回参数【"+resultObj.toJSONString()+"】");
        }
    }

    private String transferCodeByPk(String tableName, String selectField, String pkField, String pk) throws BusinessException {
        if (StringUtils.isEmpty(pk)) {
            return null;
        }
        SqlBuilder sqlBuilder = new SqlBuilder();
        sqlBuilder.append(" select " + selectField);
        sqlBuilder.append(" from " + tableName);
        sqlBuilder.append(" where ");
        sqlBuilder.append(pkField, pk);
        Object o = dao.executeQuery(sqlBuilder.toString(), new ColumnProcessor());
        if (o == null) {
            throw new BusinessException("未查询到编码信息，sql【" + sqlBuilder + "】");
        }
        return o.toString();
    }

}
