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.TCkOrderdetail;
import com.ruoyi.business.domain.TEbsRecord;
import com.ruoyi.business.domain.TMiStock;
import com.ruoyi.business.service.ITEbsRecordService;
import com.ruoyi.business.utils.OrderCodeFactory;
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.http.HttpUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
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/ebsReport")
public class EbsReportController extends BaseController {
    private String prefix = "/business/ebsReport";

    @Autowired
    private ITEbsRecordService tEbsRecordService;

    @Autowired
    private ISysConfigService configService;

    @RequiresPermissions("business:ebsReport:view")
    @GetMapping()
    public String ebsReport(ModelMap mmap) throws Exception {
        // 查询账户别名出库的结果
        TEbsRecord wmsOthersProcResForQuery = new TEbsRecord("wmsOthersProc", 2, configService.selectConfigByKey("ebs_ip"), "", "", "0", "账户别名发放", "", "", "" , null);
        List<TEbsRecord> wmsOthersProcResList = tEbsRecordService.selectTEbsRecordList(wmsOthersProcResForQuery);
        // 查询子库存转移的结果
        TEbsRecord WmsSubInvProcResForQuery = new TEbsRecord("wmsSubInvProc", 2, configService.selectConfigByKey("ebs_ip"), "", "", "0", "子库存转移", "", "", "" , null);
        List<TEbsRecord> WmsSubInvProcResList = tEbsRecordService.selectTEbsRecordList(WmsSubInvProcResForQuery);
        if (wmsOthersProcResList.size() < 1 && WmsSubInvProcResList.size() < 1) {
            return prefix + "/ebsReport";
        }
        // 获取token
        JSONObject token = JSON.parseObject(HttpUtils.httpPostJson(configService.selectConfigByKey("token_ip"), "", ""));
        // 账户别名发放结果查询
        for (TEbsRecord wmsOthersProcRes : wmsOthersProcResList) {
            JSONObject resultJsonWmsOthersProc = (JSONObject) JSON.parseObject(wmsOthersProcRes.getResult()).get("obj");
            List<JSONObject> dataWmsOthersProc = JSON.parseArray(resultJsonWmsOthersProc.getString("rows"), JSONObject.class);
            String requestId = dataWmsOthersProc.get(0).getString("requestId");
            String lastUpdateDate = dataWmsOthersProc.get(0).getString("lastUpdateDate");
            String paramGetOthersInf = JSON.toJSONString(createJsonGetOthersInf(requestId, lastUpdateDate));
            String resultGetOthersInf = "";
            try {
                resultGetOthersInf = HttpUtils.httpPostJson(configService.selectConfigByKey("ebs_ip"), paramGetOthersInf, token.get("access_token").toString());
            } catch (Exception e) {
                // 接口调用失败
                return prefix + "/ebsReport";
            }
            System.out.println(resultGetOthersInf);
            JSONObject resultJsonGetOthersInf = (JSONObject) JSON.parseObject(resultGetOthersInf).get("obj");
            List<JSONObject> dataGetOthersInf = JSON.parseArray(resultJsonGetOthersInf.getString("rows"), JSONObject.class);
            if (dataGetOthersInf.size() > 0 && dataGetOthersInf.get(0).getString("processStatus").equals("SUCCESS")) {
                // 更新账户别名发放结果
                wmsOthersProcRes.setStatus("1");
                wmsOthersProcRes.setResult(resultGetOthersInf);
                tEbsRecordService.updateTEbsRecord(wmsOthersProcRes);
            } else if (dataGetOthersInf.size() > 0 && dataGetOthersInf.get(0).getString("processStatus").equals("ERROR")) {
                // 更新账户别名发放结果
                wmsOthersProcRes.setStatus("-1");
                wmsOthersProcRes.setResult(resultGetOthersInf);
                tEbsRecordService.updateTEbsRecord(wmsOthersProcRes);
            }
        }
        // 子库存转移结果查询
        for (TEbsRecord WmsSubInvProcRes : WmsSubInvProcResList) {
            JSONObject resultJsonWmsSubInvProc = (JSONObject) JSON.parseObject(WmsSubInvProcRes.getResult()).get("obj");
            List<JSONObject> dataWmsSubInvProc = JSON.parseArray(resultJsonWmsSubInvProc.getString("rows"), JSONObject.class);
            String requestId = dataWmsSubInvProc.get(0).getString("requestId");
            String lastUpdateDate = dataWmsSubInvProc.get(0).getString("lastUpdateDate");
            String paramGetSubinvInf = JSON.toJSONString(createJsonGetSubinvIntf(requestId, lastUpdateDate));
            String resultGetSubinvInf = "";
            try {
                resultGetSubinvInf = HttpUtils.httpPostJson(configService.selectConfigByKey("ebs_ip"), paramGetSubinvInf, token.get("access_token").toString());
            } catch (Exception e) {
                // 接口调用失败
                return prefix + "/ebsReport";
            }
            System.out.println(resultGetSubinvInf);
            JSONObject resultJsonGetSubinvInf = (JSONObject) JSON.parseObject(resultGetSubinvInf).get("obj");
            List<JSONObject> dataGetSubinvInf = JSON.parseArray(resultJsonGetSubinvInf.getString("rows"), JSONObject.class);
            if (dataGetSubinvInf.size() > 0 && dataGetSubinvInf.get(0).getString("processStatus").equals("SUCCESS")) {
                // 更新子库存转移
                WmsSubInvProcRes.setStatus("1");
                WmsSubInvProcRes.setResult(resultGetSubinvInf);
                tEbsRecordService.updateTEbsRecord(WmsSubInvProcRes);
            } else if (dataGetSubinvInf.size() > 0 && dataGetSubinvInf.get(0).getString("processStatus").equals("ERROR")) {
                // 更新子库存转移
                WmsSubInvProcRes.setStatus("-1");
                WmsSubInvProcRes.setResult(resultGetSubinvInf);
                tEbsRecordService.updateTEbsRecord(WmsSubInvProcRes);
            }
        }
        return prefix + "/ebsReport";
    }

    @RequiresPermissions("business:ekpReport:view")
    @GetMapping("/ekp")
    public String ekpReport(ModelMap mmap) throws Exception {
        return prefix + "/ekpReport";
    }

    /**
     * 查询EBS接口记录
     */
    @RequiresPermissions("business:ebsReport:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TEbsRecord ebsRecord)
    {
        startPage();
        // 子查询写入的ebs。
        ebsRecord.setApiId(2);
        List<TEbsRecord> list = tEbsRecordService.selectTEbsRecordList(ebsRecord);
        return getDataTable(list);
    }

    /**
     * 查询ekp申报记录
     */
    @RequiresPermissions("business:ekpReport:list")
    @PostMapping("/ekp/list")
    @ResponseBody
    public TableDataInfo ekpList(TEbsRecord ebsRecord)
    {
        startPage();
        // 子查询写入的ebs。
        ebsRecord.setApiId(3);
        List<TEbsRecord> list = tEbsRecordService.selectTEbsRecordList(ebsRecord);
        return getDataTable(list);
    }

    /**
     * 导出ebs接口记录
     */
    @RequiresPermissions("business:ebsReport:export")
    @Log(title = "导出ebs接口记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TEbsRecord ebsRecord)
    {
        // 子查询写入的ebs。
        ebsRecord.setApiId(2);
        List<TEbsRecord> list = tEbsRecordService.selectTEbsRecordList(ebsRecord);
        ExcelUtil<TEbsRecord> util = new ExcelUtil<TEbsRecord>(TEbsRecord.class);
        return util.exportExcel(list, "ebs接口记录表");
    }

    /**
     * 导出ekp申报记录
     */
    @RequiresPermissions("business:ekpReport:export")
    @Log(title = "导出ekp申报记录", businessType = BusinessType.EXPORT)
    @PostMapping("/ekp/export")
    @ResponseBody
    public AjaxResult ekpExport(TEbsRecord ebsRecord)
    {
        ebsRecord.setApiId(3);
        List<TEbsRecord> list = tEbsRecordService.selectTEbsRecordList(ebsRecord);
        ExcelUtil<TEbsRecord> util = new ExcelUtil<TEbsRecord>(TEbsRecord.class);
        return util.exportExcel(list, "ekp申报记录");
    }

    /**
     * 创建参数Json(子库存转移结果查询)
     * @return
     */
    public JSONObject createJsonGetSubinvIntf(String requestId, String lastUpdateDate) {
        // 创建系统参数
        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", "getSubinvIntf");
        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();
        baseQueryParams.put("lastUpdateDateF", lastUpdateDate);

        // 创建数据
        JSONObject businessData = new JSONObject();
        businessData.put("requestId", requestId);

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

    /**
     * 创建参数Json(账户别名发放结果查询)
     * @return
     */
    public JSONObject createJsonGetOthersInf(String requestId, String lastUpdateDate) {
        // 创建系统参数
        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", "getOthersIntf");
        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();
        baseQueryParams.put("lastUpdateDateF", lastUpdateDate);

        // 创建数据
        JSONObject businessData = new JSONObject();
        businessData.put("requestId", requestId);

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

    /**
     * 创建参数Json(EKP申报过期结果查询)
     * @return
     */
    public JSONObject createJsonGetEkpExpireItem(String fdId) {
        // 创建系统参数
        JSONObject systemParams = new JSONObject();
        systemParams.put("requestId", new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()));
        systemParams.put("application", "WMS");
        systemParams.put("sourceSystem", "WMS");
        systemParams.put("targetSystem", "EKP");
        systemParams.put("serviceName", "getEkpExpireItem");
        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();

        // 创建数据
        JSONObject businessData = new JSONObject();
        businessData.put("fdId", fdId);
        businessData.put("itemNo", "");
        businessData.put("lotNumber", "");

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