package com.ruoyi.web.controller.business;

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.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.framework.web.service.DictService;
import com.ruoyi.system.service.ISysConfigService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

/**
 * 在线检验不合格Controller
 *
 * @author wms
 * @date 2022-05-29
 */
@Controller
@RequestMapping("/business/comingInspection")
public class ComingInspectionController extends BaseController {
    private String prefix = "business/comingInspection";

    @Autowired
    private ITMiStockService tMiStockService;

    @Autowired
    private ITEbsRecordService tEbsRecordService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private DictService dict;

    @RequiresPermissions("business:comingInspection:view")
    @GetMapping()
    public String stock(ModelMap mmap) throws Exception {
        mmap.put("tMiStock", new TMiStock());
        return prefix + "/comingInspection";
    }

    /**
     * 查询
     */
    @RequiresPermissions("business:comingInspection:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TMiStock tMiStock)
    {
        startPage();
        tMiStock.setSts(dict.getType("stock_sts").get(5).getDictValue());
        List<TMiStock> list = tMiStockService.selectStock(tMiStock);
        return getDataTable(list);
    }

    /**
     * 更改物料状态
     *
     * @param locationIds
     * @return
     */
    @Log(title = "更改物料状态", businessType = BusinessType.UPDATE)
    @RequiresPermissions("business:comingInspection:edit")
    @PostMapping("/stsChange")
    @ResponseBody
    public AjaxResult stsChange(String locationIds) throws Exception {
        // 查找对应库存
        String[] locations = StringUtils.split(locationIds.trim(), ",");
        TMiStock stockForQuery = new TMiStock();
        stockForQuery.setSts("5");
        for (int i = 0; i < locations.length; i++) {
            stockForQuery.setLocationId(locations[i]);
            List<TMiStock> list = tMiStockService.selectStock(stockForQuery);
            if (list.size() < 1) {
                return error("当前库位无待检库存");
            }
            // 更改库存状态，同时转移子库存至合格库
            TMiStock stock = list.get(0);
            // 获取token
            JSONObject token = JSON.parseObject(HttpUtils.httpPostJson(configService.selectConfigByKey("token_ip"), "", ""));
            String paramsWmsSubInvProc = JSON.toJSONString(createJsonWmsSubInvProc(stock,
                    list.get(0).getWhseloc(),
                    "121-108"));
            String resultWmsSubInvProc = "";
            try {
                resultWmsSubInvProc = HttpUtils.httpPostJson(configService.selectConfigByKey("ebs_ip"), paramsWmsSubInvProc, token.get("access_token").toString());
            } catch (Exception e) {
                tEbsRecordService.insertTEbsRecord(new TEbsRecord("wmsSubInvProc", 2, configService.selectConfigByKey("ebs_ip"),
                        paramsWmsSubInvProc, resultWmsSubInvProc, "-1", "子库存转移", stock.getGoodsId(), stock.getGoodsName(), stock.getProduclotid(), stock.getShelvesNum()));
                // 接口失败
                return error("连接EBS失败");
            }
            System.out.println(resultWmsSubInvProc);
            // 子库存转移结果
            if (!JSON.parseObject(resultWmsSubInvProc).getBoolean("success")) {
                tEbsRecordService.insertTEbsRecord(new TEbsRecord("wmsSubInvProc", 2, configService.selectConfigByKey("ebs_ip"),
                        paramsWmsSubInvProc, resultWmsSubInvProc, "-1", "子库存转移", stock.getGoodsId(), stock.getGoodsName(), stock.getProduclotid(), stock.getShelvesNum()));
                return error("子库存转移失败");
            }
            if (JSON.parseObject(JSON.parseObject(resultWmsSubInvProc).getString("obj")).getIntValue("total") < 1) {
                tEbsRecordService.insertTEbsRecord(new TEbsRecord("wmsSubInvProc", 2, configService.selectConfigByKey("ebs_ip"),
                        paramsWmsSubInvProc, resultWmsSubInvProc, "-1", "子库存转移", stock.getGoodsId(), stock.getGoodsName(), stock.getProduclotid(), stock.getShelvesNum()));
                return error("无转移子库存的物料");
            }
            JSONObject resultJsonWmsSubInvProc = (JSONObject) JSON.parseObject(resultWmsSubInvProc).get("obj");
            List<JSONObject> dataWmsSubInvProc = JSON.parseArray(resultJsonWmsSubInvProc.getString("rows"), JSONObject.class);
            if (!dataWmsSubInvProc.get(0).getString("processStatus").equals("PROCESSING")) {
                tEbsRecordService.insertTEbsRecord(new TEbsRecord("wmsSubInvProc", 2, configService.selectConfigByKey("ebs_ip"),
                        paramsWmsSubInvProc, resultWmsSubInvProc, "-1", "子库存转移", stock.getGoodsId(), stock.getGoodsName(), stock.getProduclotid(), stock.getShelvesNum()));
                return error(dataWmsSubInvProc.get(0).getString("errorMsg"));
            }
            tEbsRecordService.insertTEbsRecord(new TEbsRecord("wmsSubInvProc", 2, configService.selectConfigByKey("ebs_ip"),
                    paramsWmsSubInvProc, resultWmsSubInvProc, "0", "子库存转移", stock.getGoodsId(), stock.getGoodsName(), stock.getProduclotid(), stock.getShelvesNum()));
            stock.setSts(dict.getType("stock_sts").get(0).getDictValue());
            stock.setWhseloc("121-108");
            // 更新本地库存
            if (tMiStockService.updateTMiStock(stock) < 1) {
                return error("更新库存失败");
            }
        }
        return success("来料检验成功");
    }

    /**
     * 创建参数Json（子库存转移）
     * @return
     */
    public JSONObject createJsonWmsSubInvProc(TMiStock wmsStock, String fromSubInventoryCode, String toSubInventoryCode) {
        // 创建系统参数
        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", "wmsSubInvProc");
        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();

        // 创建数据
        JSONObject businessData = new JSONObject();
        businessData.put("transTypeId", 2);
        businessData.put("organizationId", configService.selectConfigByKey("organizationId"));
        businessData.put("itemId", wmsStock.getGoodsTypeid());
        businessData.put("quantity", wmsStock.getShelvesNum());
        businessData.put("subInventory", fromSubInventoryCode);
        businessData.put("locatorId", EbsUtils.LOCATOR_AREA_MAP.get(fromSubInventoryCode));
        businessData.put("transDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        businessData.put("transUom", wmsStock.getGoodsMeasureId());
        businessData.put("transSubInventory", toSubInventoryCode);
        businessData.put("transLocatorId", EbsUtils.LOCATOR_AREA_MAP.get(toSubInventoryCode));
        businessData.put("transLotNumber", wmsStock.getProduclotid());
        businessData.put("sourceHeaderId", 1);
        businessData.put("sourceLineId", 1);

        JSONArray jsonArray = new JSONArray();
        jsonArray.add(businessData);

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

        return result;
    }
}
