package com.ruoyi.web.controller.business;

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

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.TInspectReport;
import com.ruoyi.business.service.ITEbsRecordService;
import com.ruoyi.business.service.ITInspectReportService;
import com.ruoyi.business.utils.EbsUtils;
import com.ruoyi.business.utils.OrderCodeFactory;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ShiroUtils;
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.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.business.domain.TMiStock;
import com.ruoyi.business.service.ITMiStockService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;

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

    @Autowired
    private ITMiStockService tMiStockService;

    @Autowired
    private ITInspectReportService tInspectReportService;

    @Autowired
    private ITEbsRecordService tEbsRecordService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private  DictService dict;

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

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

    /**
     * 在线检验界面
     */
    @RequiresPermissions("business:onlineInspection:edit")
    @GetMapping("/edit/{data}")
    public String edit(@PathVariable("data") String data, ModelMap mmap)
    {
        Map dataMap = JSON.parseObject(data);
        TMiStock tMiStockQuery = new TMiStock();
        tMiStockQuery.setGoodsId(String.valueOf(dataMap.get("goodsId")));
        tMiStockQuery.setProduclotid(String.valueOf(dataMap.get("produclotid")));
        tMiStockQuery.setCtl(String.valueOf(dataMap.get("ctl")));
//        tMiStockQuery.setGoodsId(goodsId);
        TMiStock tMiStock = tMiStockService.selectStock(tMiStockQuery).get(0);
        mmap.put("tMiStock", tMiStock);
        return prefix + "/edit";
    }

    /**
     * 更新库存状态
     */
    @Log(title = "更新库存状态", businessType = BusinessType.UPDATE)
    @RequiresPermissions("business:onlineInspection:edit")
    @PostMapping("/update")
    @ResponseBody
    public AjaxResult update(TMiStock tMiStock) throws Exception {
        TMiStock tMiStockSel = new TMiStock();
        tMiStockSel.setGoodsId(tMiStock.getGoodsId());
        tMiStockSel.setProduclotid(tMiStock.getProduclotid());
        tMiStockSel.setCtl(tMiStock.getCtl());
        TMiStock tMiStockUpdate = tMiStockService.selectStock(tMiStockSel).get(0);
        tMiStockUpdate.setMark(tMiStock.getMark());
        // 获取token
        JSONObject token = JSON.parseObject(HttpUtils.httpPostJson(configService.selectConfigByKey("token_ip"), "", ""));
        if (Objects.equals(tMiStockUpdate.getSts(), dict.getType("stock_sts").get(0).getDictValue())) {
            String paramsWmsSubInvProc = JSON.toJSONString(createJsonWmsSubInvProc(tMiStockUpdate,
                    tMiStockUpdate.getWhseloc(),
                    "121-124"));
            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", "子库存转移", tMiStockUpdate.getGoodsId(), tMiStockUpdate.getGoodsName(), tMiStockUpdate.getProduclotid(), tMiStockUpdate.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", "子库存转移", tMiStockUpdate.getGoodsId(), tMiStockUpdate.getGoodsName(), tMiStockUpdate.getProduclotid(), tMiStockUpdate.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", "子库存转移", tMiStockUpdate.getGoodsId(), tMiStockUpdate.getGoodsName(), tMiStockUpdate.getProduclotid(), tMiStockUpdate.getShelvesNum()));
                return error("无转移子库存的物料");
            }
            tEbsRecordService.insertTEbsRecord(new TEbsRecord("wmsSubInvProc", 2, configService.selectConfigByKey("ebs_ip"),
                    paramsWmsSubInvProc, resultWmsSubInvProc, "0", "子库存转移", tMiStockUpdate.getGoodsId(), tMiStockUpdate.getGoodsName(), tMiStockUpdate.getProduclotid(), tMiStockUpdate.getShelvesNum()));
            tMiStockUpdate.setSts(dict.getType("stock_sts").get(1).getDictValue());
            tMiStockUpdate.setWhseloc("121-124");
        } else {
            String paramsWmsSubInvProc = JSON.toJSONString(createJsonWmsSubInvProc(tMiStockUpdate,
                    tMiStockUpdate.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", "子库存转移", tMiStockUpdate.getGoodsId(), tMiStockUpdate.getGoodsName(), tMiStockUpdate.getProduclotid(), tMiStockUpdate.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", "子库存转移", tMiStockUpdate.getGoodsId(), tMiStockUpdate.getGoodsName(), tMiStockUpdate.getProduclotid(), tMiStockUpdate.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", "子库存转移", tMiStockUpdate.getGoodsId(), tMiStockUpdate.getGoodsName(), tMiStockUpdate.getProduclotid(), tMiStockUpdate.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", "子库存转移", tMiStockUpdate.getGoodsId(), tMiStockUpdate.getGoodsName(), tMiStockUpdate.getProduclotid(), tMiStockUpdate.getShelvesNum()));
                return error(dataWmsSubInvProc.get(0).getString("errorMsg"));
            }
            tEbsRecordService.insertTEbsRecord(new TEbsRecord("wmsSubInvProc", 2, configService.selectConfigByKey("ebs_ip"),
                    paramsWmsSubInvProc, resultWmsSubInvProc, "0", "子库存转移", tMiStockUpdate.getGoodsId(), tMiStockUpdate.getGoodsName(), tMiStockUpdate.getProduclotid(), tMiStockUpdate.getShelvesNum()));
            tMiStockUpdate.setSts(dict.getType("stock_sts").get(0).getDictValue());
            tMiStockUpdate.setWhseloc("121-108");
        }

        // 库存状态更新成功之后，插入检验记录表
        if (tMiStockService.updateTMiStock(tMiStockUpdate) > 0) {
            // 获取用户名
            SysUser sysUser = ShiroUtils.getCurrentUser();
            TInspectReport tInspectReport = new TInspectReport();
            tInspectReport.setInspectid(OrderCodeFactory.getOrderCode("JY", ""));
            tInspectReport.setGoodsid(tMiStockUpdate.getGoodsId());
            tInspectReport.setCtl(tMiStockUpdate.getCtl());
            tInspectReport.setGoodsname(tMiStockUpdate.getGoodsName());
            tInspectReport.setProductlotid(tMiStockUpdate.getProduclotid());
            tInspectReport.setProvider(tMiStockUpdate.getProviderId());
            tInspectReport.setProductiondate(tMiStockUpdate.getProductionDate());
            tInspectReport.setExpirationdate(tMiStockUpdate.getExpirationDate());
            tInspectReport.setShelfnum(tMiStockUpdate.getShelvesNum().toString());
            tInspectReport.setCreateTime(new Date());
            tInspectReport.setUsername(sysUser.getUserName());
            tInspectReport.setStatus(tMiStockUpdate.getSts());
            tInspectReport.setLocation(tMiStockUpdate.getLocationId());
            if (tInspectReportService.insertTInspectReport(tInspectReport) > 0) {
                return success();
            }
        }
        return error();
    }

    /**
     * 状态说明弹框
     */
    @GetMapping("/stsDescribe")
    public String stsDescribe()
    {
        return prefix + "/stsdescribe";
    }

    /**
     * 创建参数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;
    }
}
