package nc.bs.pu.m21.action.rule.approve;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.NCLocator;
import nc.bs.logging.Log;
import nc.bs.uapbd.util.ThirdPartyPostRequestUtil;
import nc.impl.pubapp.pattern.rule.IRule;
import nc.itf.bd.material.baseinfo.IMaterialBaseInfoQueryService;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.pubitf.para.SysInitQuery;
import nc.vo.bd.defdoc.DefdocVO;
import nc.vo.bd.material.MaterialVO;
import nc.vo.bd.psn.PsndocVO;
import nc.vo.bd.stordoc.StordocVO;
import nc.vo.bd.supplier.SupplierVO;
import nc.vo.cmp.util.StringUtils;
import nc.vo.org.OrgVO;
import nc.vo.pu.m21.entity.OrderVO;
import nc.vo.pu.m21.entity.OrderHeaderVO;
import nc.vo.pu.m21.entity.OrderItemVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.pubapp.pattern.pub.SqlBuilder;
import nc.vo.scmpub.util.ArrayUtil;
import nc.vo.util.CloneUtil;

import java.util.*;

import static nccloud.openapi.ic.m4c.mapping.M4cFieldsEnum.cmaterialvid;

/**
 * 采购订单审批后同步到锐制系统
 */
public class AfterApprovingSynchronizeRuleRZ implements IRule<OrderVO> {

    private static Log log = Log.getInstance("rzmomlog");
    private static final BaseDAO dao = new BaseDAO();
    private static final int OPERATION_ADD = 1;
    private static final int STATUS_LOCKED = 1;
    private static final int STATUS_ISSUED = 1;

    @Override
    public void process(OrderVO[] orderVOS) {
        if (ArrayUtil.isEmpty(orderVOS)) {
            return;
        }
        try {
            OrderVO[] cloneOrderVOS = (OrderVO[]) CloneUtil.deepClone(orderVOS);
            //检查并筛选销售出库单据为互感器公司
            List<OrderVO> newOrderVOS = checkAndFilterBillSrcOrg(cloneOrderVOS);
            if (newOrderVOS==null||newOrderVOS.size()<1) {
                return;
            }
            //推送到锐制系统
            pushToRZMOM(newOrderVOS.toArray(new OrderVO[0]));
        } catch (Exception e) {
            log.error("同步采购订单到锐制系统失败: " + e.getMessage());
            ExceptionUtils.wrappException(e);
        }
    }

    private List<OrderVO> checkAndFilterBillSrcOrg(OrderVO[] OrderVOS) throws BusinessException {
        List<OrderVO> aggvoList = new ArrayList<>();
        List<OrderVO> finalList = new ArrayList<>();

        for (OrderVO aggvo : OrderVOS) {
            String pkOrg = aggvo.getHVO().getPk_org();
            Integer forderstatus = aggvo.getHVO().getForderstatus();
            String orgCode = transferCodeByPk(OrgVO.getDefaultTableName(), OrgVO.CODE, OrgVO.PK_ORG, pkOrg);
            String vdef20 = aggvo.getHVO().getVdef20();
            if(vdef20==null||"N".equals(vdef20)){
                if ("C022".equals(orgCode) && 3 == forderstatus && aggvo.getBVO()!=null && aggvo.getBVO().length > 0) {
                    aggvoList.add(aggvo);
                }
            }
        }
        //再次筛选
        //2025年7月2日10点33分--新增不传--表体物料编码前三位为103时不传
        //获取表体物料信息
        if(aggvoList.isEmpty()){
            return aggvoList;
        }
        Set<String> materialpks=new HashSet<>();
        for (OrderVO aggvo : aggvoList) {
            for (OrderItemVO item : aggvo.getBVO()) {
                String cmaterialvid = item.getPk_material();
                materialpks.add(cmaterialvid);
            }
        }
        if(materialpks.isEmpty()){
            return aggvoList;
        }
        //根据物料id查询物料信息
        MaterialVO[] vos = NCLocator.getInstance().lookup(IMaterialBaseInfoQueryService.class).queryDataByPks(materialpks.toArray(new String[0]));
        //组装Map
        Map<String, String> materialMap = new HashMap<>();
        if(vos==null || vos.length<1){
            throw new BusinessException("Failed to query material info , please check !!!");
        }
        for (MaterialVO vo : vos) {
            String cmaterialvid = vo.getPk_material();
            String cmaterialcode =vo.getCode();
            materialMap.put(cmaterialvid, cmaterialcode);
        }
        //筛选行数据
        for (OrderVO aggvo : aggvoList) {
            List<OrderItemVO> newItems = new ArrayList<>();
            for (OrderItemVO item : aggvo.getBVO()) {
                String cmaterialvid = item.getPk_material();
                if (materialMap.containsKey(cmaterialvid)) {
                    String materialCode = materialMap.get(cmaterialvid);
                    if(!materialCode.startsWith("103")){
                        newItems.add(item);
                    }
                }
            }
            if (!newItems.isEmpty()) {
                aggvo.setBVO(newItems.toArray(new OrderItemVO[0]));
                finalList.add(aggvo);
            }
        }
        return finalList;
    }

    /**
     * 推送数据到睿智MOM系统
     */
    private void pushToRZMOM(OrderVO[] orderVOS) throws BusinessException {
        String rzwmsip = SysInitQuery.getParaString("GLOBLE00000000000000", "RZWMSIP");

        JSONObject jsonObject = new JSONObject();
        // 设置请求头
        jsonObject.put("dataflow", "用友BIP→RZMOMv6");
        jsonObject.put("actionCode", "htmxb");

        JSONObject dataIn = new JSONObject();
        JSONObject dataIn2 = new JSONObject();
        JSONArray details = new JSONArray();

        // 单笔/批量按明细传
        for (OrderVO orderVO : orderVOS) {
            OrderHeaderVO head = orderVO.getHVO();
            OrderItemVO[] items = orderVO.getBVO();

            // 构建同步数据
            buildSyncData(head, items, details);
        }

        dataIn2.put("Details", details);
        dataIn.put("Data", dataIn2);
        jsonObject.put("data", dataIn);

        log.error("采购订单推送锐制请求报文：" + jsonObject.toJSONString());

        // 使用ThirdPartyPostRequestUtil发送请求
        String result = ThirdPartyPostRequestUtil.sendPostRequest(rzwmsip, jsonObject.toJSONString());
        JSONObject resultObj = JSONObject.parseObject(result);
        log.error("采购订单推送锐制返回报文：" + result);

        if ("false".equals(resultObj.getString("success"))) {
            throw new BusinessException("RZMOM同步失败，原因：" + resultObj.getString("msg"));
        } else {
            log.error("RZMOM同步成功，返回参数【" + resultObj.toJSONString() + "】");
        }
    }

    /**
     * 构建同步数据
     */
    private void buildSyncData(OrderHeaderVO head, OrderItemVO[] items, JSONArray details) throws BusinessException {
        if (items == null) {
            return;
        }

        for (OrderItemVO item : items) {
            if (item == null) {
                continue;
            }

            JSONObject detailItem = new JSONObject();
            UFDate dbilldate = item.getDbilldate();
            // 设置订单基本信息
//            第三方系统表体主键id
            detailItem.put("htmx_wbid", head.getPk_order() + "_" + item.getPk_order_b());
            //第三方系统合同ID
            detailItem.put("cght_wbid", head.getPk_order());
            //操作状态 1新增/修改、2删除（删除时只需上传wbid）
            detailItem.put("operate", OPERATION_ADD);
            //zbxx_cglb_wbid	varchar(100)	第三方系统采购类别id	必填	维护对应关系
            detailItem.put("zbxx_cglb_wbid", head.getVtrantypecode());

            //zbxx_cgrq	datetime	采购日期	必填	表头采购日期
            detailItem.put("zbxx_cgrq", head.getDbilldate().toString());


            // 设置合同信息
//            合同编号	必填	例如：采购订单编号：1001
            detailItem.put("htxsbh", head.getVbillcode());
//            合同序号	必填	例如：采购订单序号：1、2、3
            detailItem.put("htxh", item.getCrowno());

            // 设置物料信息
            detailItem.put("wlbm_wbid", item.getPk_material());

            // 设置数量信息
            UFDouble nastnum = item.getNastnum() == null ? UFDouble.ZERO_DBL : item.getNastnum();
            detailItem.put("cgsl", nastnum.getDouble());
            //采购日期	必填	明细行的采购日期
            if (dbilldate != null) {
                detailItem.put("cgrq", dbilldate.toString());
            }
            // zbxx_gycs_wbid	varchar(100)	第三方系统厂商id	必填	厂商名称的ID
            detailItem.put("zbxx_gycs_wbid", head.getPk_supplier());
            //zbxx_cgy_wbid	varchar(100)	第三方系统采购员id	 	维护对应关系
            detailItem.put("zbxx_cgy_wbid", head.getCemployeeid());
            // 设置计划日期
//            交货日期	必填	明细行的交货日期
            if (item.getDplanarrvdate() != null) {
                detailItem.put("jhrq", item.getDplanarrvdate().toString());
            }

            // 设置仓库和备注信息
            detailItem.put("sdck", item.getPk_reqstordoc());
            detailItem.put("bzsm", item.getVbmemo());

            // 设置状态信息
            detailItem.put("sdbj", STATUS_LOCKED);
            detailItem.put("qfbj", STATUS_ISSUED);

            // 项目编号
            detailItem.put("wlzdycs06", transferCodeByPk("bd_defdoc", DefdocVO.CODE, DefdocVO.PK_DEFDOC, item.getVbdef6()));
            detailItem.put("wlzdycs11", transferCodeByPk("bd_defdoc", DefdocVO.NAME, DefdocVO.PK_DEFDOC, item.getVbdef6()));
            details.add(detailItem);
        }
    }

    /**
     * 根据主键查询编码
     */
    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();
    }
}
