package nc.bs.ic.m4i.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.stordoc.StordocVO;
import nc.vo.cmp.util.StringUtils;
import nc.vo.ic.m4i.entity.GeneralOutBodyVO;
import nc.vo.ic.m4i.entity.GeneralOutHeadVO;
import nc.vo.ic.m4i.entity.GeneralOutVO;
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 AfterSignRuleSyncOutToMesProcess implements IRule<GeneralOutVO> {

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

    private static final String logginfo = "OALOG";

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

    private static final BaseDAO DAO = new BaseDAO();

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

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

        }
    }

    private void syncOtherOut(GeneralOutVO generalOutVO) throws BusinessException {
        GeneralOutHeadVO head = generalOutVO.getHead();
        obmlog.debug("开始处理其它出库单(4I-01): " + head.getVbillcode());
        // 表体body信息拼接
        JSONArray details = new JSONArray();
        // 填充details
        for (GeneralOutBodyVO body : generalOutVO.getBodys()) {// body中取数
            JSONObject temp = new JSONObject();
            temp.put("sequenceNum", body.getCrowno()); // 通知单序号
            temp.put("type", "QTCK"); // 事务类型
            MaterialVersionVO materialVersionVO = (MaterialVersionVO) iUifService.queryByPrimaryKey(MaterialVersionVO.class, body.getCmaterialoid());
            if (Objects.isNull(materialVersionVO)) {
                throw new BusinessException("搜索物料信息不存在");
            }
            temp.put("materialId", materialVersionVO.getCode()); // 物料ID
            temp.put("issuedQty", body.getNnum() != null ? body.getNnum().doubleValue() : null); // 应发数量
            temp.put("actQty", body.getNshouldnum() != null ? body.getNshouldnum().doubleValue() : null); // 实发数量
            temp.put("assistActQry", body.getNassistnum() != null ? body.getNassistnum().doubleValue() : ""); // 辅助实发数量
            temp.put("productNum", null);
            temp.put("storageId", body.getClocationid()); // 库位
            temp.put("batchNum", body.getVbatchcode()); // 物料批号
            temp.put("customId", null);
            temp.put("supplierId", null);
            temp.put("manufactureDate", null);
            temp.put("remark", body.getVnotebody());
            details.add(temp);
        }
        JSONObject info = new JSONObject();
        info.put("details", details);
        // 从head中取数
        info.put("type", "QTCK"); // 事务类型
        info.put("actureDate", head.getDmakedate().toString()); // 实际日期
        StordocVO warehouse = (StordocVO) iUifService.queryByPrimaryKey(StordocVO.class, head.getCwarehouseid());
        if (Objects.isNull(warehouse)) {
            throw new BusinessException("仓库信息不存在,主键:" + head.getCwarehouseid());
        }
        info.put("storeId", warehouse.getCode()); // 仓库ID
        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("其它出库(4I-01) requestData:" + requestData.toJSONString());
        HTTP_POST_OTHER_SYS.sendToExternalSystem("/GTHINKING/AjaxService/N_KCSJJS/101527004.ashx/gt_rec_api_qtckdj", requestData);
        obmlog.debug("其它出库单(4I-01) " + head.getVbillcode() + " 同步成功");
    }

    private void syncOtherSystem(GeneralOutVO generalOutVO) throws BusinessException {
        obmlog.debug("触发同步其它出库单,出库类型编码:" + generalOutVO.getHead().getVtrantypecode() + "开始拼接数据");

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

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

        String trantypecode = generalOutVO.getHead().getVtrantypecode();
        // 其它出库
        if ("4I-01".equals(trantypecode)) {
            syncOtherOut(generalOutVO);
        }
        // 调拨出库/转库单
        else if ("4I-02".equals(trantypecode)) {
            syncTransferOut(generalOutVO);
        }

    }

    private void syncTransferOut(GeneralOutVO generalOutVO) throws BusinessException {
        GeneralOutHeadVO head = generalOutVO.getHead();
        obmlog.debug("开始处理调拨出库/转库单(4I-02): " + head.getVbillcode());
        // 表体body信息拼接
        JSONArray details = new JSONArray();
        // 填充details
        for (GeneralOutBodyVO body : generalOutVO.getBodys()) {// body中取数
            JSONObject temp = new JSONObject();
//            temp.put("orderNo", head.getVbillcode()); // 通知单ID
            temp.put("sequenceNum", body.getCrowno()); // 通知单序号
            temp.put("type", "DBCK"); // 事务类型
            temp.put("genType", null);
            MaterialVersionVO materialVersionVO = (MaterialVersionVO) iUifService.queryByPrimaryKey(MaterialVersionVO.class, body.getCmaterialoid());
            if (Objects.isNull(materialVersionVO)) {
                throw new BusinessException("搜索物料信息不存在");
            }
            temp.put("materialId", materialVersionVO.getCode()); // 物料ID
            temp.put("issuedQty", body.getNnum() != null ? body.getNnum().doubleValue() : null); // 应发数量
            temp.put("actOutQty", body.getNshouldnum() != null ? body.getNshouldnum().doubleValue() : null); // 实发数量
            temp.put("outQty", body.getNnum() != null ? body.getNnum().doubleValue() : null);
            temp.put("assistActOutQry", body.getNassistnum() != null ? body.getNassistnum().doubleValue() : 0); // 辅助实发数量
            temp.put("productNum", null);
            temp.put("outStorageId", body.getClocationid()); // 库位
            temp.put("outBatchNum", body.getVbatchcode()); // 物料批号
            temp.put("customId", null);
            temp.put("supplierId", null);
            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("orderNo", head.getVbillcode()); // 通知单ID
        info.put("type", "DBCK"); // 事务类型
        info.put("genType", null);
        info.put("outDate", head.getDbilldate().toString());

        StordocVO outWarehouse = (StordocVO) iUifService.queryByPrimaryKey(StordocVO.class, head.getCwarehouseid());
        if (Objects.isNull(outWarehouse)) {
            throw new BusinessException("出库仓库信息不存在,主键:" + head.getCwarehouseid());
        }
        info.put("outStoreId", outWarehouse.getCode()); // 仓库ID

        StordocVO inWarehouse = (StordocVO) iUifService.queryByPrimaryKey(StordocVO.class, head.getCotherwhid());
        if (Objects.isNull(inWarehouse)) {
            throw new BusinessException("入库仓库信息不存在,主键:" + head.getCotherwhid());
        }
        info.put("inStoreId", inWarehouse.getCode()); // 仓库ID
        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("调拨出库/转库单(4I-02) requestData:" + requestData.toJSONString());

        HTTP_POST_OTHER_SYS.sendToExternalSystem("/GTHINKING/AjaxService/N_KCSJJS/101527009.ashx/gt_rec_api_dbckdj", requestData);
        obmlog.debug("调拨出库/转库单(4I-02) " + head.getVbillcode() + " 同步成功");
    }


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

}
