package com.ruoyi.web.controller.business;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.business.domain.*;
import com.ruoyi.business.service.*;
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.DictUtils;
import com.ruoyi.common.utils.ShiroUtils;
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.commons.lang3.ObjectUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 库存Controller
 *
 * @author wms
 * @date 2022-05-29
 */
@Controller
@RequestMapping("/business/stockReport")
public class TStockReportController extends BaseController
{
    private String prefix = "business/stockReport";

    @Autowired
    private ITMiStockService tMiStockService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ITEbsRecordService tEbsRecordService;

    @Autowired
    private ITTransferRecordService tTransferRecordService;

    @Autowired
    private ITTaskMoveService tTaskMoveService;

    @Autowired
    private ITBaseStorageAreaLocationService tBaseStorageAreaLocationService;

    @Autowired
    private  DictService dict;

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

    /**
     * 移库
     * @param mmap
     * @return
     */
    @RequiresPermissions("business:stockReport:view")
    @GetMapping("/moveStock")
    public String ebsConfirm(ModelMap mmap) {
        mmap.put("tMiStock", new TMiStock());
        return prefix + "/stockForMove";
    }

    /**
     * 查询库存列表
     */
    @RequiresPermissions("business:stockReport:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TMiStock tMiStock)
    {
        startPage();
        List<TMiStock> list = tMiStockService.selectStock(tMiStock);
        return getDataTable(list);
    }

    /**
     * 导出库存列表
     */
    @RequiresPermissions("business:stockReport:export")
    @Log(title = "导出库存表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TMiStock tMiStock)
    {
        List<TMiStock> list = tMiStockService.selectStock(tMiStock);
        ExcelUtil<TMiStock> util = new ExcelUtil<TMiStock>(TMiStock.class);
        return util.exportExcel(list, "库存数据");
    }

    /**
     * 导入库存列表
     */
    @RequiresPermissions("business:stockReport:import")
    @Log(title = "导入库存表", businessType = BusinessType.EXPORT)
    @PostMapping("/importExcel")
    @ResponseBody
    public AjaxResult importExcel(TMiStock tMiStock) {
        InputStream is = null;
        try {
            is = new FileInputStream("D:\\库存数据.xlsx");
        } catch (FileNotFoundException e) {
            return error(e.getMessage());
        }
        ExcelUtil<TMiStock> util = new ExcelUtil<TMiStock>(TMiStock.class);
        List<TMiStock> stockList;
        try {
            stockList = util.importExcel(is);
        } catch (Exception e) {
            return error(e.getMessage());
        }
        for (TMiStock stock : stockList) {
           if (tMiStockService.insertTMiStock(stock) < 1) {
               return error("导入数据失败");
           }
        }
        return success("导入成功");
    }

    /**
     * 新增库存
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 弹框表格
     */
    @GetMapping("/modalPage")
    public String table()
    {
        return prefix + "/stockModal";
    }

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

    /**
     * 更新库存状态
     */
    @RequiresPermissions("business:stockReport:edit")
    @GetMapping("/changeStockSts/{stock}")
    public String edit(@PathVariable("stock") String stock, ModelMap mmap)
    {
        Map stockMap = JSON.parseObject(stock);
        TMiStock tMiStockQuery = new TMiStock();
        tMiStockQuery.setGoodsId(String.valueOf(stockMap.get("goodsId")));
        tMiStockQuery.setProduclotid(String.valueOf(stockMap.get("produclotid")));
        tMiStockQuery.setCtl(String.valueOf(stockMap.get("ctl")));
        tMiStockQuery.setSts(String.valueOf(stockMap.get("sts")));
        TMiStock tMiStock = tMiStockService.selectStock(tMiStockQuery).get(0);
        mmap.put("tMiStock", tMiStock);
        return prefix + "/changeStockSts";
    }

    /**
     * 选择移库库位
     */
    @RequiresPermissions("business:stockReport:edit")
    @GetMapping("/selDestinationLocation/{stock}")
    public String selMoveLocation(@PathVariable("stock") String stock, ModelMap mmap)
    {
        // 请求库存信息
        TMiStock requestStock = JSON.parseObject(stock, TMiStock.class);
        // 当前库位信息
        TBaseStorageAreaLocation currentLocation = tBaseStorageAreaLocationService.getOne(
                new LambdaQueryWrapper<TBaseStorageAreaLocation>()
                        .select(TBaseStorageAreaLocation::getLocationId, TBaseStorageAreaLocation::getLocationHeight)
                        .eq(TBaseStorageAreaLocation::getLocationId, requestStock.getLocationId())
        );

        // 移库信息
        TTaskMove moveTask = new TTaskMove();
        moveTask.setVehicleId(requestStock.getCtl());
        moveTask.setOrigin(requestStock.getLocationId());
        mmap.put("moveTask", moveTask);
        List<String> destinations = new ArrayList<>();
        LambdaQueryWrapper<TBaseStorageAreaLocation> queryWrapper = new LambdaQueryWrapper<TBaseStorageAreaLocation>()
                .select(TBaseStorageAreaLocation::getLocationId)
                .eq(TBaseStorageAreaLocation::getStatus, "0")
                .eq(TBaseStorageAreaLocation::getIslock, "0");
//        if (Objects.equals(currentLocation.getLocationHeight(), "2")) {
//            queryWrapper.eq(TBaseStorageAreaLocation::getLocationHeight, "2");
//        }
        List<TBaseStorageAreaLocation> locations = tBaseStorageAreaLocationService.list(queryWrapper);
        for (TBaseStorageAreaLocation location : locations) {
            destinations.add(location.getLocationId());
        }
        mmap.put("locations", destinations);
        return prefix + "/moveDestinationSelect";
    }

    /**
     * 生成移库任务
     */
    @RequiresPermissions("business:stockReport:edit")
    @Log(title = "生成移库任务", businessType = BusinessType.UPDATE)
    @PostMapping("/generateMoveTask")
    @ResponseBody
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    public AjaxResult generateMoveTask(TTaskMove moveTask) {
        if (moveTask == null || StringUtils.isEmpty(moveTask.getVehicleId())
                || StringUtils.isEmpty(moveTask.getOrigin())
                ||StringUtils.isEmpty(moveTask.getDestination())) {
            return error("缺少必填项");
        }
        TBaseStorageAreaLocation originLocation = tBaseStorageAreaLocationService.getOne(
                new LambdaQueryWrapper<TBaseStorageAreaLocation>()
                        .select(TBaseStorageAreaLocation::getLocationId, TBaseStorageAreaLocation::getLocationHeight, TBaseStorageAreaLocation::getAbcId)
                        .eq(TBaseStorageAreaLocation::getLocationId, moveTask.getOrigin()));
        TBaseStorageAreaLocation destinationLocation = tBaseStorageAreaLocationService.getOne(
                new LambdaQueryWrapper<TBaseStorageAreaLocation>()
                        .select(TBaseStorageAreaLocation::getLocationId, TBaseStorageAreaLocation::getLocationHeight, TBaseStorageAreaLocation::getAbcId, TBaseStorageAreaLocation::getIslock, TBaseStorageAreaLocation::getStatus)
                        .eq(TBaseStorageAreaLocation::getLocationId, moveTask.getDestination())
        );
        if (originLocation == null || destinationLocation == null) {
            return error("库位错误，查不到指定库位");
        }
//        if (Objects.equals(originLocation.getLocationHeight(), "2") && Objects.equals(destinationLocation.getLocationHeight(), "1")) {
//            return error("高位不能移入低位");
//        }
        if (!Objects.equals(destinationLocation.getIslock(), "0") || !Objects.equals(destinationLocation.getStatus(), "0")) {
            return error("所选库位不可使用，请重新选择可用库位");
        }
        // 查询库存是否可用
        TMiStock moveStock = tMiStockService.getOne(
                new LambdaQueryWrapper<TMiStock>()
                        .select(TMiStock::getCtl, TMiStock::getFlag)
                        .eq(TMiStock::getCtl, moveTask.getVehicleId()));
        if (moveStock == null || !Objects.equals(moveStock.getFlag(), "0")) {
            return error("当前库存不可移库");
        }
        TTaskMove newMove = new TTaskMove();
        newMove.setTaskId(OrderCodeFactory.getOrderCode("MOVE_", ""));
        newMove.setTaskType(1);
        newMove.setTaskStatus(0);
        newMove.setVehicleId(moveTask.getVehicleId());
        newMove.setOrigin(originLocation.getLocationId());
        newMove.setDestination(destinationLocation.getLocationId());
        if (!Objects.equals(originLocation.getAbcId(), destinationLocation.getAbcId())) {
            newMove.setIsCrossTunnel(1);// 跨巷道
        } else {
            newMove.setIsCrossTunnel(0);// 本巷道
        }
        try {
            // 生成移库任务
            tTaskMoveService.save(newMove);
            // 锁定库位
            tBaseStorageAreaLocationService.update(new LambdaUpdateWrapper<TBaseStorageAreaLocation>()
                    .set(TBaseStorageAreaLocation::getStatus, "1")
                    .eq(TBaseStorageAreaLocation::getLocationId, moveTask.getDestination()));
            // 锁定库存
            tMiStockService.update(new LambdaUpdateWrapper<TMiStock>()
                    .set(TMiStock::getFlag, "1")
                    .eq(TMiStock::getCtl, moveTask.getVehicleId()));
            return success("生成移库任务成功");
        } catch (Exception e) {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return error("生成移库任务失败");
        }
    }

    /**
     * 更新库存状态
     */
    @Log(title = "更新库存状态", businessType = BusinessType.UPDATE)
    @PostMapping("/updateStockSts")
    @ResponseBody
    public AjaxResult update(@RequestBody TMiStock tMiStock) throws Exception {
        logger.info("接收子库转移请求：{}", JSON.toJSONString(tMiStock));
        if (StringUtils.isEmpty(tMiStock.getGoodsId())
                || StringUtils.isEmpty(tMiStock.getProduclotid())
                || StringUtils.isEmpty(tMiStock.getCtl())
                || StringUtils.isEmpty(tMiStock.getSts())) {
            return error("请求缺少必须信息，物料编码、批次号、托盘号、更新后的状态为必须信息。");
        }
        TMiStock stockForSelOrigin = new TMiStock();
        stockForSelOrigin.setGoodsId(tMiStock.getGoodsId());
        stockForSelOrigin.setProduclotid(tMiStock.getProduclotid());
        stockForSelOrigin.setCtl(tMiStock.getCtl());
        // 原来的库存信息
        List<TMiStock> origins  = tMiStockService.selectStock(stockForSelOrigin);
        logger.info("根据请求参数查询到的库存数量: {}", origins.size());
        if (origins.size() > 0) {// 库中存在的库存转移子库
            // 原来的库存信息
            TMiStock stockOrigin = origins.get(0);
            // 更新后的库存
            TMiStock stockAfter = new TMiStock();
            BeanUtils.copyProperties(stockOrigin, stockAfter);
            logger.info("原始库存: {}", JSON.toJSONString(stockOrigin));

            if (StringUtils.isEmpty(stockOrigin.getGoodsId())) {
                return error("对应库存缺少物料编码");
            }

            if (StringUtils.isEmpty(stockOrigin.getProduclotid())) {
                return error("对应库存缺少批次号");
            }

            if (StringUtils.isEmpty(stockOrigin.getGoodsMeasureId())) {
                return error("对应库存缺少单位");
            }

            if (StringUtils.isEmpty(stockOrigin.getGoodsTypeid())) {
                return error("对应库存缺少item_id");
            }

            if (StringUtils.isEmpty(stockOrigin.getWhseloc())) {
                return error("对应库存缺少子库编码");
            }

            // 分库存状态来操作
            if ("0".equals(tMiStock.getSts())) {// 合格
                // 待检-》合格
                stockAfter.setSts(tMiStock.getSts());
                stockAfter.setWhseloc("121-108");
            } else if ("1".equals(tMiStock.getSts())) {// 不合格
                // 获取token
                JSONObject token = JSON.parseObject(HttpUtils.httpPostJson(configService.selectConfigByKey("token_ip"), "", ""));
                String paramsWmsSubInvProc = JSON.toJSONString(createJsonWmsSubInvProc(stockOrigin,
                        stockOrigin.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", "子库存转移", stockOrigin.getGoodsId(), stockOrigin.getGoodsName(), stockOrigin.getProduclotid(), stockOrigin.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", "子库存转移", stockOrigin.getGoodsId(), stockOrigin.getGoodsName(), stockOrigin.getProduclotid(), stockOrigin.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", "子库存转移", stockOrigin.getGoodsId(), stockOrigin.getGoodsName(), stockOrigin.getProduclotid(), stockOrigin.getShelvesNum()));
                    return error("无转移子库存的物料");
                }
                tEbsRecordService.insertTEbsRecord(new TEbsRecord("wmsSubInvProc", 2, configService.selectConfigByKey("ebs_ip"),
                        paramsWmsSubInvProc, resultWmsSubInvProc, "0", "子库存转移", stockOrigin.getGoodsId(), stockOrigin.getGoodsName(), stockOrigin.getProduclotid(), stockOrigin.getShelvesNum()));
                stockAfter.setSts(tMiStock.getSts());
                // 不合格原因
                stockAfter.setMark(tMiStock.getMark());
                stockAfter.setWhseloc("121-124");
            } else if ("2".equals(tMiStock.getSts())) {// 延期
                // 获取token
                JSONObject token = JSON.parseObject(HttpUtils.httpPostJson(configService.selectConfigByKey("token_ip"), "", ""));
                String paramsWmsSubInvProc = JSON.toJSONString(createJsonWmsSubInvProc(stockOrigin,
                        stockOrigin.getWhseloc(),
                        "121-121"));
                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", "子库存转移", stockOrigin.getGoodsId(), stockOrigin.getGoodsName(), stockOrigin.getProduclotid(), stockOrigin.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", "子库存转移", stockOrigin.getGoodsId(), stockOrigin.getGoodsName(), stockOrigin.getProduclotid(), stockOrigin.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", "子库存转移", stockOrigin.getGoodsId(), stockOrigin.getGoodsName(), stockOrigin.getProduclotid(), stockOrigin.getShelvesNum()));
                    return error("无转移子库存的物料");
                }
                tEbsRecordService.insertTEbsRecord(new TEbsRecord("wmsSubInvProc", 2, configService.selectConfigByKey("ebs_ip"),
                        paramsWmsSubInvProc, resultWmsSubInvProc, "0", "子库存转移", stockOrigin.getGoodsId(), stockOrigin.getGoodsName(), stockOrigin.getProduclotid(), stockOrigin.getShelvesNum()));
                stockAfter.setSts(tMiStock.getSts());
                // 将有效日期设置为延期日期
                stockAfter.setExpirationDate(tMiStock.getExpirationDate());
                stockAfter.setWhseloc("121-121");
            } else if ("3".equals(tMiStock.getSts())) {// 报废
                // 获取token
                JSONObject token = JSON.parseObject(HttpUtils.httpPostJson(configService.selectConfigByKey("token_ip"), "", ""));
                String paramsWmsSubInvProc = JSON.toJSONString(createJsonWmsSubInvProc(stockOrigin,
                        stockOrigin.getWhseloc(),
                        "121-127"));
                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", "子库存转移", stockOrigin.getGoodsId(), stockOrigin.getGoodsName(), stockOrigin.getProduclotid(), stockOrigin.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", "子库存转移", stockOrigin.getGoodsId(), stockOrigin.getGoodsName(), stockOrigin.getProduclotid(), stockOrigin.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", "子库存转移", stockOrigin.getGoodsId(), stockOrigin.getGoodsName(), stockOrigin.getProduclotid(), stockOrigin.getShelvesNum()));
                    return error("无转移子库存的物料");
                }
                tEbsRecordService.insertTEbsRecord(new TEbsRecord("wmsSubInvProc", 2, configService.selectConfigByKey("ebs_ip"),
                        paramsWmsSubInvProc, resultWmsSubInvProc, "0", "子库存转移", stockOrigin.getGoodsId(), stockOrigin.getGoodsName(), stockOrigin.getProduclotid(), stockOrigin.getShelvesNum()));
                stockAfter.setSts(tMiStock.getSts());
                // 报废流程编号
                stockAfter.setMark(tMiStock.getMark());
                stockAfter.setWhseloc("121-127");
            } else if ("4".equals(tMiStock.getSts())) {// 锁定
                // 合格-》锁定
                stockAfter.setSts(tMiStock.getSts());
            } else if ("-1".equals(tMiStock.getSts())){// 出库
                logger.info("出库请求");
                logger.info("出库请求原始库存：{}", stockOrigin.getWhseloc());
                // 获取token
                JSONObject token = JSON.parseObject(HttpUtils.httpPostJson(configService.selectConfigByKey("token_ip"), "", ""));
                String paramsWmsSubInvProc = JSON.toJSONString(createJsonWmsSubInvProc(stockOrigin,
                        "121-108",
                        "121-141"));
                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", "子库存转移", stockOrigin.getGoodsId(), stockOrigin.getGoodsName(), stockOrigin.getProduclotid(), stockOrigin.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", "子库存转移", stockOrigin.getGoodsId(), stockOrigin.getGoodsName(), stockOrigin.getProduclotid(), stockOrigin.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", "子库存转移", stockOrigin.getGoodsId(), stockOrigin.getGoodsName(), stockOrigin.getProduclotid(), stockOrigin.getShelvesNum()));
                    return error("无转移子库存的物料");
                }
                tEbsRecordService.insertTEbsRecord(new TEbsRecord("wmsSubInvProc", 2, configService.selectConfigByKey("ebs_ip"),
                        paramsWmsSubInvProc, resultWmsSubInvProc, "0", "子库存转移", stockOrigin.getGoodsId(), stockOrigin.getGoodsName(), stockOrigin.getProduclotid(), stockOrigin.getShelvesNum()));
                stockAfter.setSts(tMiStock.getSts());
                // 设定子库
                stockAfter.setWhseloc("121-141");
            }

            // 库存状态更新成功之后，插入检验记录表
            if (tMiStockService.updateTMiStock(stockAfter) > 0) {
                TTransferRecord transferRecord = new TTransferRecord();
                if ("0".equals(stockAfter.getSts())) {
                    transferRecord.setTransferid(OrderCodeFactory.getOrderCode("HG", ""));
                } else if ("1".equals(stockAfter.getSts())) {
                    transferRecord.setTransferid(OrderCodeFactory.getOrderCode("BHG", ""));
                } else if ("2".equals(stockAfter.getSts())) {
                    transferRecord.setTransferid(OrderCodeFactory.getOrderCode("YQ", ""));
                    transferRecord.setDelaydate(stockAfter.getExpirationDate());
                } else if ("3".equals(stockAfter.getSts())) {
                    transferRecord.setTransferid(OrderCodeFactory.getOrderCode("BF", ""));
                } else if ("4".equals(stockAfter.getSts())) {
                    transferRecord.setTransferid(OrderCodeFactory.getOrderCode("SD", ""));
                } else if ("-1".equals(stockAfter.getSts())) {
                    transferRecord.setTransferid(OrderCodeFactory.getOrderCode("CK", ""));
                }
                transferRecord.setGoodsid(stockAfter.getGoodsId());
                transferRecord.setGoodsname(stockAfter.getGoodsName());
                transferRecord.setProductlotid(stockAfter.getProduclotid());
                transferRecord.setShelfnum(stockAfter.getShelvesNum().toString());
                transferRecord.setLocation(stockAfter.getLocationId());
                transferRecord.setCtl(stockAfter.getCtl());
                transferRecord.setProductiondate(stockOrigin.getProductionDate());
                transferRecord.setExpirationdate(stockOrigin.getExpirationDate());
                transferRecord.setCreateTime(new Date());
                transferRecord.setFromstatus(stockOrigin.getSts());
                transferRecord.setTostatus(stockAfter.getSts());
                if (tTransferRecordService.insertTTransferRecord(transferRecord) > 0) {
                    return success();
                }
            }
        } else {// 退库时转移子库
            logger.info("退库请求");
            // 退库后新生成的库存
            TMiStock stockAfter = new TMiStock();
            BeanUtils.copyProperties(tMiStock, stockAfter);
            logger.info("退库请求的库存：{}", stockAfter.getWhseloc());
            logger.info("接收子库转移请求：{}", JSON.toJSONString(stockAfter));

            if (StringUtils.isEmpty(stockAfter.getGoodsId())) {
                return error("缺少物料编码");
            }

            if (StringUtils.isEmpty(stockAfter.getProduclotid())) {
                return error("缺少批次号");
            }

            if (StringUtils.isEmpty(stockAfter.getGoodsMeasureId())) {
                return error("缺少单位");
            }

            if (StringUtils.isEmpty(stockAfter.getGoodsTypeid())) {
                return error("缺少item_id");
            }

            if (StringUtils.isEmpty(stockAfter.getWhseloc())) {
                return error("缺少子库编码");
            }

            // 获取token
            JSONObject token = JSON.parseObject(HttpUtils.httpPostJson(configService.selectConfigByKey("token_ip"), "", ""));
            String paramsWmsSubInvProc = JSON.toJSONString(createJsonWmsSubInvProc(stockAfter,
                    "121-141",
                    "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", "子库存转移", stockAfter.getGoodsId(), stockAfter.getGoodsName(), stockAfter.getProduclotid(), stockAfter.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", "子库存转移", stockAfter.getGoodsId(), stockAfter.getGoodsName(), stockAfter.getProduclotid(), stockAfter.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", "子库存转移", stockAfter.getGoodsId(), stockAfter.getGoodsName(), stockAfter.getProduclotid(), stockAfter.getShelvesNum()));
                return error("无转移子库存的物料");
            }
            tEbsRecordService.insertTEbsRecord(new TEbsRecord("wmsSubInvProc", 2, configService.selectConfigByKey("ebs_ip"),
                    paramsWmsSubInvProc, resultWmsSubInvProc, "0", "子库存转移", stockAfter.getGoodsId(), stockAfter.getGoodsName(), stockAfter.getProduclotid(), stockAfter.getShelvesNum()));

            TTransferRecord transferRecord = new TTransferRecord();
            transferRecord.setTransferid(OrderCodeFactory.getOrderCode("TK", ""));
            transferRecord.setGoodsid(stockAfter.getGoodsId());
            transferRecord.setGoodsname(stockAfter.getGoodsName());
            transferRecord.setProductlotid(stockAfter.getProduclotid());
            transferRecord.setShelfnum(stockAfter.getShelvesNum().toString());
            transferRecord.setLocation(stockAfter.getLocationId());
            transferRecord.setCtl(stockAfter.getCtl());
            transferRecord.setProductiondate(stockAfter.getProductionDate());
            transferRecord.setExpirationdate(stockAfter.getExpirationDate());
            transferRecord.setCreateTime(new Date());
            transferRecord.setFromstatus(stockAfter.getSts());
            transferRecord.setTostatus(stockAfter.getSts());
            if (tTransferRecordService.insertTTransferRecord(transferRecord) > 0) {
                return success();
            }
        }

        return error();
    }

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