package nc.bs.sc.m61.referred.rule.pm;


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.defdoc.DefdocVO;
import nc.vo.cmp.util.StringUtils;
import nc.vo.org.OrgVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.pubapp.pattern.pub.SqlBuilder;
import nc.vo.sc.m61.entity.SCOrderHeaderVO;
import nc.vo.sc.m61.entity.SCOrderItemVO;
import nc.vo.sc.m61.entity.SCOrderVO;
import nc.vo.scmpub.util.ArrayUtil;

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

public class AfterApproceRuleSyncRZWMSProcess implements IRule<SCOrderVO> {

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

    private static BaseDAO dao = new BaseDAO();

    @Override
    public void process(SCOrderVO[] vos) {
        if (ArrayUtil.isEmpty(vos)) {
            return;
        }
        try {
            //检查并筛选销售出库单据为互感器公司
            List<SCOrderVO> newSCOrderVOS = checkAndFilterBillSrcOrg(vos);
            if (newSCOrderVOS == null || newSCOrderVOS.size() < 1) {
                return;
            }
            pushToRZMOM(newSCOrderVOS.toArray(new SCOrderVO[0]));
        } catch (Exception e) {
            ExceptionUtils.wrappException(e);
        }
    }

    private void buildSyncData(SCOrderHeaderVO head, SCOrderItemVO[] bodys, JSONArray details) throws BusinessException {
        String vbillcode = head.getVbillcode();
        String pkOrder = head.getPk_order();
        for (SCOrderItemVO body : bodys) {
            JSONObject singleObj = new JSONObject();

            //htmx_wbid	varchar(100)	第三方系统主键id	必填
            singleObj.put("htmx_wbid", pkOrder+"_"+body.getPk_order_b());

            //cght_wbid	varchar(100)	第三方系统合同ID	必填
            singleObj.put("cght_wbid", pkOrder);

            //操作状态 1新增/修改、2删除（删除时只需上传wbid）
            singleObj.put("operate", 1);

            // zbxx_cglb_wbid	varchar(100)	第三方系统采购类别id	必填
            singleObj.put("zbxx_cglb_wbid", head.getVtrantypecode());

            //zbxx_cgrq	datetime	采购日期	必填	表头采购日期
            if (head.getDbilldate() != null) {
                singleObj.put("zbxx_cgrq", head.getDbilldate().toString()); // 采购日期
            }

            //htxsbh	varchar(100)	合同编号
            singleObj.put("htxsbh", head.getVbillcode());

            // 合同序号
            singleObj.put("htxh", body.getCrowno());

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

            // 采购数量
            UFDouble nqtunitnum = body.getNqtunitnum() == null ? UFDouble.ZERO_DBL : body.getNqtunitnum();
            singleObj.put("cgsl", nqtunitnum.getDouble());

            // 采购日期
            if (head.getDbilldate() != null) {
                singleObj.put("cgrq", head.getDbilldate().toString());
            }

            // 第三方系统厂商id
            singleObj.put("zbxx_gycs_wbid", head.getPk_supplier());

            //zbxx_cgy_wbid	varchar(100)	第三方系统采购员id
            singleObj.put("zbxx_cgy_wbid", head.getCemployeeid());

            // 交货日期
            if (body.getDplanarrvdate() != null) {
                singleObj.put("jhrq", body.getDplanarrvdate().toString());
            }

            singleObj.put("sdck", body.getPk_recvstordoc()); // 送达仓库

            singleObj.put("bzsm", body.getVbmemo());              // 备注说明

            //sdbj	int	锁定标记	必填	上位单据审核传输，默认=1
            singleObj.put("sdbj", 1);
            //qfbj	int	签发标记	必填	上位单据审核传输，默认=1
            singleObj.put("qfbj", 1);
            // 项目编号
            singleObj.put("wlzdycs06", transferCodeByPk("bd_defdoc", DefdocVO.CODE, DefdocVO.PK_DEFDOC, body.getVbdef6()));
            singleObj.put("wlzdycs11", transferCodeByPk("bd_defdoc", DefdocVO.NAME, DefdocVO.PK_DEFDOC, body.getVbdef6()));

            details.add(singleObj);
        }
    }

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

    private void pushToRZMOM(SCOrderVO[] SCOrderVOS) throws BusinessException {
        String rzwmsip = SysInitQuery.getParaString("GLOBLE00000000000000", "RZWMSIP");
        JSONObject jsonObject = new JSONObject();
        JSONObject data = new JSONObject();
        JSONObject dataIn = new JSONObject();
        JSONObject dataIn2 = new JSONObject();
        JSONArray details = new JSONArray();
        jsonObject.put("dataflow", "用友BIP→RZMOMv6");
        jsonObject.put("actionCode", "htmxb");
        //单笔/批量按明细传
        for (SCOrderVO SCOrderVO : SCOrderVOS) {
            SCOrderHeaderVO head = SCOrderVO.getParentVO();
            SCOrderItemVO[] bodys = SCOrderVO.getChildrenVO();
            // 构建需要同步的数据
            buildSyncData(head, bodys, details);
        }
        dataIn2.put("Details", details);
        dataIn.put("Data", dataIn2);
        data.put("data", dataIn);
        jsonObject.put("data", data);
        log.error("委外订单推送锐制请求报文：" + jsonObject.toJSONString());
        String result = ThirdPartyPostRequestUtil.sendPostRequest(rzwmsip, jsonObject.toJSONString());
        JSONObject resultObj = JSONObject.parseObject(result);
        if ("false".equals(resultObj.getString("success"))) {
            throw new BusinessException("RZMOM同步失败，原因：" + resultObj.getString("msg"));
        }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();
    }


}
