package com.ruoyi.quartz.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TEbsRecord;
import com.ruoyi.business.domain.TMiStock;
import com.ruoyi.business.service.ITEbsRecordService;
import com.ruoyi.business.service.ITMiStockService;
import com.ruoyi.business.utils.EbsUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 定时任务半小时查询一次EBS检验结果
 * 查询到检验结果-》接收入库：合格进合格库，不合格进不合格库
 *
 * @author liangzhou
 */
@Component("inspectionResultCheck")
public class InspectionResultCheckTask {

    @Autowired
    private ITMiStockService tMiStockService;

    @Autowired
    private ITEbsRecordService tEbsRecordService;

    @Autowired
    private ISysConfigService configService;

    public void execute() throws Exception {
        // 获取库存
        TMiStock tMiStockForSel = new TMiStock();
        tMiStockForSel.setSts("5");
        List<TMiStock> stocks = tMiStockService.selectStock(tMiStockForSel);
        if (stocks.size() < 1) {
            return;
        }
        // 获取token
        JSONObject token = new JSONObject();
        try {
            token = JSON.parseObject(HttpUtils.httpPostJson(configService.selectConfigByKey("token_ip"), "", ""));
        } catch (Exception e) {
            return;
        }
        // 查询检验结果
        String paramsGeTransactions = JSON.toJSONString(createJsonGeTransactions(stocks));
        String resultGeTransactions = "";
        try {
            resultGeTransactions = HttpUtils.httpPostJson(configService.selectConfigByKey("ebs_ip"), paramsGeTransactions, token.get("access_token").toString());
        } catch (Exception e) {
            // 接口失败
            return;
        }
        JSONObject resultJsonGeTransactions = (JSONObject) JSON.parseObject(resultGeTransactions).get("obj");
        List<JSONObject> dataGeTransactions = JSON.parseArray(resultJsonGeTransactions.getString("rows"), JSONObject.class);
        for (JSONObject dataGeTransaction : dataGeTransactions) {
            // 先查询对应的库存信息
            TMiStock tMiStockForUpd = new TMiStock();
            tMiStockForUpd.setLocidname(dataGeTransaction.getString("poLineLocationId"));
            TMiStock stockAccept = tMiStockService.selectStock(tMiStockForUpd).get(0);
            // 检验交货，合格进合格库，不合格进不合格库
            if (dataGeTransaction.getString("transactionType").equals("ACCEPT")) {// 检验合格
                // 检验交货
                String paramsWmsDevProc = JSON.toJSONString(createJsonWmsDevProc(dataGeTransaction, "121-108"));
                String resultWmsDevProc = "";
                try {
                    resultWmsDevProc = HttpUtils.httpPostJson(configService.selectConfigByKey("ebs_ip"), paramsWmsDevProc, token.get("access_token").toString());
                } catch (Exception e) {
                    tEbsRecordService.insertTEbsRecord(new TEbsRecord("wmsDevProc", 2, configService.selectConfigByKey("ebs_ip"),
                            paramsWmsDevProc, resultWmsDevProc, "-1", "检验交货", stockAccept.getGoodsId(), stockAccept.getGoodsName(), stockAccept.getProduclotid(), stockAccept.getShelvesNum()));
                    // 接口失败
                    return;
                }
                System.out.println(resultWmsDevProc);
                if (!JSON.parseObject(resultWmsDevProc).getBoolean("success")) {
                    tEbsRecordService.insertTEbsRecord(new TEbsRecord("wmsDevProc", 2, configService.selectConfigByKey("ebs_ip"),
                            paramsWmsDevProc, resultWmsDevProc, "-1", "检验交货", stockAccept.getGoodsId(), stockAccept.getGoodsName(), stockAccept.getProduclotid(), stockAccept.getShelvesNum()));
                    return;
                }
                JSONObject resultJsonWmsRcvProc = (JSONObject) JSON.parseObject(resultWmsDevProc).get("obj");
                JSONObject dataWmsRcvProc = JSON.parseArray(resultJsonWmsRcvProc.getString("rows"), JSONObject.class).get(0);
                if (!dataWmsRcvProc.getString("processStatus").equals("SUCCESS")) {
                    tEbsRecordService.insertTEbsRecord(new TEbsRecord("wmsDevProc", 2, configService.selectConfigByKey("ebs_ip"),
                            paramsWmsDevProc, resultWmsDevProc, "-1", "检验交货", stockAccept.getGoodsId(), stockAccept.getGoodsName(), stockAccept.getProduclotid(), stockAccept.getShelvesNum()));
                    return;
                }
                tEbsRecordService.insertTEbsRecord(new TEbsRecord("wmsDevProc", 2, configService.selectConfigByKey("ebs_ip"),
                        paramsWmsDevProc, resultWmsDevProc, "0", "检验交货", stockAccept.getGoodsId(), stockAccept.getGoodsName(), stockAccept.getProduclotid(), stockAccept.getShelvesNum()));

                // 检验交货成功后，更新wms的库存
                stockAccept.setSts("0");
                tMiStockService.updateTMiStock(stockAccept);
            } else {// 检验不合格
                // 检验交货
                String paramsWmsDevProc = JSON.toJSONString(createJsonWmsDevProc(dataGeTransaction, "121-124"));
                String resultWmsDevProc = "";
                try {
                    resultWmsDevProc = HttpUtils.httpPostJson(configService.selectConfigByKey("ebs_ip"), paramsWmsDevProc, token.get("access_token").toString());
                } catch (Exception e) {
                    tEbsRecordService.insertTEbsRecord(new TEbsRecord("wmsDevProc", 2, configService.selectConfigByKey("ebs_ip"),
                            paramsWmsDevProc, resultWmsDevProc, "-1", "检验交货", stockAccept.getGoodsId(), stockAccept.getGoodsName(), stockAccept.getProduclotid(), stockAccept.getShelvesNum()));
                    // 接口失败
                    return;
                }
                System.out.println(resultWmsDevProc);
                if (!JSON.parseObject(resultWmsDevProc).getBoolean("success")) {
                    tEbsRecordService.insertTEbsRecord(new TEbsRecord("wmsDevProc", 2, configService.selectConfigByKey("ebs_ip"),
                            paramsWmsDevProc, resultWmsDevProc, "-1", "检验交货", stockAccept.getGoodsId(), stockAccept.getGoodsName(), stockAccept.getProduclotid(), stockAccept.getShelvesNum()));
                    return;
                }
                JSONObject resultJsonWmsRcvProc = (JSONObject) JSON.parseObject(resultWmsDevProc).get("obj");
                JSONObject dataWmsRcvProc = JSON.parseArray(resultJsonWmsRcvProc.getString("rows"), JSONObject.class).get(0);
                if (!dataWmsRcvProc.getString("processStatus").equals("SUCCESS")) {
                    tEbsRecordService.insertTEbsRecord(new TEbsRecord("wmsDevProc", 2, configService.selectConfigByKey("ebs_ip"),
                            paramsWmsDevProc, resultWmsDevProc, "-1", "检验交货", stockAccept.getGoodsId(), stockAccept.getGoodsName(), stockAccept.getProduclotid(), stockAccept.getShelvesNum()));
                    return;
                }
                tEbsRecordService.insertTEbsRecord(new TEbsRecord("wmsDevProc", 2, configService.selectConfigByKey("ebs_ip"),
                        paramsWmsDevProc, resultWmsDevProc, "0", "检验交货", stockAccept.getGoodsId(), stockAccept.getGoodsName(), stockAccept.getProduclotid(), stockAccept.getShelvesNum()));
                // 检验交货成功后，更新wms的库存
                stockAccept.setWhseloc("121-124");
                stockAccept.setSts("1");
                tMiStockService.updateTMiStock(stockAccept);
            }
        }
    }

    /**
     * 创建参数Json(查询检验结果，一次性查询多个)
     *
     * @return
     */
    public JSONObject createJsonGeTransactions(List<TMiStock> stocks) {
        // 创建系统参数
        JSONObject systemParams = new JSONObject();
        systemParams.put("requestId", new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()));
        systemParams.put("application", "NT_WMS");
        systemParams.put("sourceSystem", "NT_WMS");
        systemParams.put("targetSystem", "EBS");
        systemParams.put("serviceName", "geTransactions");
        systemParams.put("nonce", 1);
        systemParams.put("timestamp", 1);
        systemParams.put("serviceOperation", "S");
        systemParams.put("serviceVersion", "1.0");
        systemParams.put("token", "fd");

        // 创建查询参数
        JSONObject baseQueryParams = new JSONObject();

        JSONArray jsonArray = new JSONArray();
        // 创建数据
        for (TMiStock stock : stocks) {
            JSONObject businessData = new JSONObject();
            businessData.put("organizationId", configService.selectConfigByKey("organizationId"));
            businessData.put("poLineLocationId", stock.getLocidname());
            jsonArray.add(businessData);
        }

        JSONObject result = new JSONObject();
        result.put("systemParams", systemParams);
        result.put("baseQueryParams", baseQueryParams);
        result.put("businessData", jsonArray);

        return result;
    }

    /**
     * 创建参数Json(检验交货)
     *
     * @return
     */
    public JSONObject createJsonWmsDevProc(JSONObject dataGeTransaction, String subInventory) {
        // 创建系统参数
        JSONObject systemParams = new JSONObject();
        systemParams.put("requestId", new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()));
        systemParams.put("application", "NT_WMS");
        systemParams.put("sourceSystem", "NT_WMS");
        systemParams.put("targetSystem", "EBS");
        systemParams.put("serviceName", "wmsDevProc");
        systemParams.put("nonce", 1);
        systemParams.put("timestamp", 1);
        systemParams.put("serviceOperation", "E");
        systemParams.put("serviceVersion", "1.0");
        systemParams.put("token", "fd");

        // 创建查询参数
        JSONObject baseQueryParams = new JSONObject();

        JSONArray jsonArray = new JSONArray();
        // 创建数据
        JSONObject businessData = new JSONObject();
        businessData.put("transDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        businessData.put("transId", dataGeTransaction.getIntValue("transactionId"));
        businessData.put("organizationId", configService.selectConfigByKey("organizationId"));
        businessData.put("subInventory", subInventory);
        businessData.put("quantity", dataGeTransaction.getIntValue("quantity"));
        businessData.put("locatorId", EbsUtils.LOCATOR_AREA_MAP.get(subInventory));
        businessData.put("lotNumber", dataGeTransaction.getString("vendorLotNum"));
        businessData.put("shipmentNum", dataGeTransaction.getString("receiptNum"));

        jsonArray.add(businessData);

        JSONObject result = new JSONObject();
        result.put("systemParams", systemParams);
        result.put("baseQueryParams", baseQueryParams);
        result.put("businessData", jsonArray);

        return result;
    }
}
