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


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.impl.pubapp.pattern.rule.IRule;
import nc.itf.uif.pub.IUifService;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.vo.bd.material.MaterialVersionVO;
import nc.vo.bd.rack.RackVO;
import nc.vo.bd.stordoc.StordocVO;
import nc.vo.cmp.util.StringUtils;
import nc.vo.ic.m4a.entity.GeneralInBodyVO;
import nc.vo.ic.m4a.entity.GeneralInHeadVO;
import nc.vo.ic.m4a.entity.GeneralInVO;
import nc.vo.org.StockOrgVO;
import nc.vo.pub.BusinessException;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.pubapp.pattern.pub.SqlBuilder;
import nccloud.pubift.commen.itf.utils.IHttpPostOtherSys;

import java.util.Objects;

public class AfterSignRuleSyncInToMesProcess implements IRule<GeneralInVO> {

    public static final IHttpPostOtherSys HTTP_POST_OTHER_SYS = NCLocator.getInstance().lookup(IHttpPostOtherSys.class);

    private static final String LOG_INFO_NAME = "OALOG";

    private static final Log obmlog = Log.getInstance(LOG_INFO_NAME);

    private static final IUifService IUIFSERVICE = NCLocator.getInstance().lookup(IUifService.class);

    private static final BaseDAO DAO = new BaseDAO();


    public void process(GeneralInVO[] vos) {
        if (vos != null && vos.length != 0) {
            try {
                for (GeneralInVO vo : vos) {
                    syncOtherSystem(vo);
                }
            } catch (BusinessException ex) {
                ExceptionUtils.wrappException(ex);
            }
        }
    }

    private void syncOtherIn(GeneralInVO generalInVO) throws BusinessException {
        GeneralInHeadVO head = generalInVO.getHead();
        obmlog.debug("开始处理其它入库单(4A-01): " + head.getVbillcode());
        // 表体body信息拼接
        JSONArray details = new JSONArray();
        // 填充details
        for (GeneralInBodyVO body : generalInVO.getBodys()) {
            JSONObject temp = new JSONObject();
            temp.put("sequenceNum", body.getCrowno()); // 通知单序号
            temp.put("type", "QTRK"); // 事务类型

            MaterialVersionVO materialVersionVO = (MaterialVersionVO) IUIFSERVICE.queryByPrimaryKey(MaterialVersionVO.class, body.getCmaterialvid());
            if (Objects.isNull(materialVersionVO)) {
                throw new BusinessException("物料信息不存在, 主键:" + body.getCmaterialvid());
            }
            temp.put("materialId", materialVersionVO.getCode()); // 物料ID
            temp.put("recQty", body.getNnum() != null ? body.getNnum().doubleValue() : 0); // 应收数量
            temp.put("actQty", body.getNshouldnum() != null ? body.getNshouldnum().doubleValue() : 0); // 实收数量
            temp.put("assistActQry", body.getNassistnum() != null ? body.getNassistnum().doubleValue() : 0); // 辅助实收数量
            temp.put("productNum", null); // 产品编号
            String RackVOCode = transferCodeByPk(RackVO.getDefaultTableName(), RackVO.CODE, RackVO.PK_RACK, body.getClocationid());
            if (RackVOCode != null && !RackVOCode.isBlank()) {
                temp.put("storageId", body.getClocationid()); // 库位
            }

            temp.put("batchNum", body.getVbatchcode()); // 物料批号
            temp.put("customId", null); // 客户ID
            temp.put("supplierId", null); // 供应商ID
            temp.put("manufactureDate", null); // 生产日期
            temp.put("color", null); // 颜色
            temp.put("packLen", null); // 包装长度
            temp.put("packSize", null); // 包装尺寸
            temp.put("remark", body.getVnotebody()); // 备注 (行)
            details.add(temp);
        }

        JSONObject info = new JSONObject();
        info.put("details", details); // 明细
        // 从head中取数
        info.put("type", "QTRK"); // 事务类型
        info.put("actureDate", head.getDmakedate() != null ? head.getDmakedate().toString() : null); // 实际日期
        StordocVO warehouse = (StordocVO) IUIFSERVICE.queryByPrimaryKey(StordocVO.class, head.getCwarehouseid());
        if (warehouse.getCode() != null && warehouse.getCode().length() > 4) {
            throw new BusinessException("MES系统仓库编码[" + warehouse.getCode() + "]不能超过4位，请选择合适的仓库!");
        } else {
            info.put("storeId", warehouse.getCode());
        }
        info.put("department", null); // 部门
        info.put("customId", null); // 客户
        info.put("supplierId", null); // 供应商

        info.put("workerNo", null); // 工人编号
        info.put("worker", null); // 工人
        info.put("storeKeeper", head.getCwhsmanagerid()); // 库管员
        info.put("returned", "N"); // 是否退库
        info.put("mark", "N"); // 生成标志
        info.put("remark", head.getVnote()); // 备注 (头)

        // 拼接数据,先创建一个jsonObject
        JSONObject requestData = new JSONObject();
        requestData.put("operation_type", "I"); // 操作
        requestData.put("info", info);
        obmlog.debug("其它入库(4A-01) requestData:" + requestData.toJSONString());

        HTTP_POST_OTHER_SYS.sendToExternalSystem("/GTHINKING/AjaxService/N_KCSJJS/101527002.ashx/gt_rec_api_qtrkdj", requestData);
        obmlog.debug("其它入库单(4A-01) " + head.getVbillcode() + " 同步成功");
    }

    private void syncOtherSystem(GeneralInVO generalInVO) throws BusinessException {
        GeneralInHeadVO head = generalInVO.getHead();
        obmlog.debug("触发同步其它入库单(M4A), 单据号:" + head.getVbillcode() + ", 出库类型编码:" + head.getVtrantypecode() + "开始拼接数据");

        String orgCode = transferCodeByPk(StockOrgVO.getDefaultTableName(), StockOrgVO.CODE, StockOrgVO.PK_STOCKORG, head.getPk_org());

        if (!HTTP_POST_OTHER_SYS.checkIfIncludeOrg(orgCode)) {
            obmlog.debug("当前组织不在同步范围内,当前组织:" + generalInVO.getHead().getPk_org() + ", 组织编码:" + orgCode);
            return; // 仅操作需要同步的组织
        }

//        // 调拨入库
//        if ("4A-02".equals(head.getVtrantypecode())) {
//            syncTransferIn(generalInVO);
//        }
        // 其它入库
        else if ("4A-01".equals(head.getVtrantypecode())) {
            syncOtherIn(generalInVO);
        }
    }

    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();
    }
}
