package com.ruoyi.web.controller.business;

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.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.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysConfigService;
import org.apache.poi.hpsf.GUID;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
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.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 入库任务单Controller
 * 
 * @author tony.wu
 * @date 2022-05-29
 */
@Controller
@RequestMapping("/business/ongoodsshelf")
public class TOngoodsshelfController extends BaseController
{
    private String prefix = "business/ongoodsshelf";

    @Autowired
    private ITOngoodsshelfService tOngoodsshelfService;

    @Autowired
    private ITOngoodsshelfBakService  tOngoodsshelfBakService;

    @Autowired
    private ITCkOrderdetailService tckOrderdetailService;

    @Autowired
    private ITConveyorStatusService tConveyorStatusService;

    @Autowired
    private ITEbsRecordService tEbsRecordService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ITEbsOrderService itEbsOrderService;

    @Autowired
    private ITMiStockService tMiStockService;

    @Autowired
    private ITBaseGoodsService goodsService;

    @Autowired
    private ITBaseProviderService tBaseProviderService;

    @RequiresPermissions("business:ongoodsshelf:view")
    @GetMapping()
    public String ongoodsshelf(ModelMap mmap)
    {
        // 获取用户
        SysUser sysUser = ShiroUtils.getCurrentUser();
        mmap.put("sysUser", sysUser);
        // 获取供应商
        List<TBaseProvider> providers = tBaseProviderService.list();
        mmap.put("providers", providers);
        return prefix + "/ongoodsshelf";
    }

    /**
     * 查询入库任务单列表
     */
    @RequiresPermissions("business:ongoodsshelf:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TOngoodsshelf tOngoodsshelf)
    {
        startPage();
        List<TOngoodsshelf> list = new ArrayList<>();
        return getDataTable(list);
    }

    /**
     * 导出入库任务单列表
     */
    @RequiresPermissions("business:ongoodsshelf:export")
    @Log(title = "导出入库任务单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TOngoodsshelf tOngoodsshelf)
    {
        List<TOngoodsshelf> list = tOngoodsshelfService.selectTOngoodsshelfList(tOngoodsshelf);
        ExcelUtil<TOngoodsshelf> util = new ExcelUtil<TOngoodsshelf>(TOngoodsshelf.class);
        return util.exportExcel(list, "入库任务单数据");
    }

    /**
     * 新增入库任务单
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }


    @GetMapping(value = "/getBarcode")
    @ResponseBody
    public AjaxResult getbarcode(){
        List<TConveyorStatus> tConveyorStatuses = getTConveyorStatus();
        if(tConveyorStatuses != null && tConveyorStatuses.size() > 0) {
            return success(tConveyorStatuses.get(0));
        }
        logger.error("没有查询到该设备对应的站台信息………………………………");
        return toAjax(false);
    }

    /**
     * 开始入库
     */
    @Log(title = "开始入库", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/startIn",consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public AjaxResult startIn(@RequestBody TBaseProvider startInRequest) {
        logger.info("接收到开始入库请求:{}", JSON.toJSONString(startInRequest));
        try {
            if (StringUtils.isEmpty(startInRequest.getProviderId())) {
                return error("请求参数缺少供应商id。");
            }
            TBaseProvider currentInProvider = tBaseProviderService.getOne(new LambdaQueryWrapper<TBaseProvider>()
                    .eq(TBaseProvider::getRemark, "1")
                    .last("limit 1"));
            if (currentInProvider == null) {
                // 查询当前供应商
                TBaseProvider currentRequestProvider = tBaseProviderService.getOne(new LambdaQueryWrapper<TBaseProvider>()
                        .eq(TBaseProvider::getProviderId, startInRequest.getProviderId())
                        .last("limit 1"));
                if (currentRequestProvider == null) {
                    return error("请求的供应商错误，数据库中不存在。");
                }
                // 更新当前供应商为入库中状态
                currentRequestProvider.setRemark("1");
                if (tBaseProviderService.updateById(currentRequestProvider)) {
                    return success("当前供应商开始入库成功。");
                } else {
                    return error("当前供应商开始入库失败。");
                }
            } else {
                if (Objects.equals(currentInProvider.getProviderId(), startInRequest.getProviderId())) {
                    return success("当前供应商已经开始入库。");
                } else {
                    return error("其他供应商正在入库，请结束后再试。");
                }
            }
        } catch (Exception e) {
            return error("发生异常。");
        }
    }

    /**
     * 停止入库
     */
    @Log(title = "停止入库", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/stopIn",consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public AjaxResult stopIn(@RequestBody TBaseProvider startInRequest) {
        logger.info("接收到停止入库请求:{}", JSON.toJSONString(startInRequest));
        try {
            boolean result = tBaseProviderService.update(new LambdaUpdateWrapper<TBaseProvider>()
                    .set(TBaseProvider::getRemark, "0")
                    .eq(TBaseProvider::getRemark, "1"));
            if (result) {
                return success("停止入库成功。");
            } else {
                return error("停止入库失败。");
            }
        } catch (Exception e) {
            return error("发生异常。");
        }
    }

    /**
     * 结束入库
     */
    @Log(title = "入库", businessType = BusinessType.INSERT)
    @PostMapping(value = "/finishIn",consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public AjaxResult finishIn(@RequestBody List<TOngoodsshelf> tOngoodsshelves) throws Exception {
        logger.info("接收到入库请求:{}",tOngoodsshelves.toString());
        if(tOngoodsshelves.size() == 0){
            logger.error("提交入库的数据为空");
            return error();
        }
        // 入库id
        String lotId = OrderCodeFactory.getOrderCode("RK", "");
        // 创建日期
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SysUser sysUser = new SysUser();
        if (StringUtils.isEmpty(tOngoodsshelves.get(0).getUserName())) {
            // 获取用户名
            sysUser = ShiroUtils.getCurrentUser();
        } else {
            sysUser.setUserName(tOngoodsshelves.get(0).getUserName());
        }
        for (TOngoodsshelf s:
                tOngoodsshelves) {
            s.setAgvsts("0");
            s.setTasktype("0");
            s.setLotId(lotId);
            s.setOrderId(initOrderId());
            s.setCreateDate(sdf.format(date));
            s.setInstatus("0");
            s.setUserName(sysUser.getUserName());
            // 设置子库ID
            s.setWhseloc("121-108");
        }

        // 开始对接ebs
        String ebsCongfirmResult = ebsConfirm(tOngoodsshelves);
        if (StringUtils.isNotEmpty(ebsCongfirmResult)) {
            return error(ebsCongfirmResult);
        }
        if (tOngoodsshelfService.insertTOngoodsshelfValues(tOngoodsshelves) < 1) {
            return error("生成入库任务失败");
        }
        return success("生成入库任务成功");
    }

    /**
     * 写入Ebs
     */
    @Log(title = "写入Ebs", businessType = BusinessType.INSERT)
    @PostMapping(value = "/wmsRcvProc",consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public AjaxResult wmsRcvProc(@RequestBody List<TOngoodsshelf> tOngoodsshelves) throws Exception {
        logger.info("接收写入参数：{}", tOngoodsshelves.toString());
        // 查询任务
        TOngoodsshelf queryOnTask = new TOngoodsshelf();
        queryOnTask.setInstand(tOngoodsshelves.get(0).getInstand());
        queryOnTask.setInstatus(tOngoodsshelves.get(0).getInstatus());
        List<TOngoodsshelf> tOngoodsshelvesNew = tOngoodsshelfService.selectTOngoodsshelfList(queryOnTask);
        // 获取token
        JSONObject token = JSON.parseObject(HttpUtils.httpPostJson(configService.selectConfigByKey("token_ip"), "", ""));
        for (TOngoodsshelf tOngoodsshelve : tOngoodsshelvesNew) {
            // 获取本地缓存过的订单信息
            TEbsOrder queryOrder = new TEbsOrder();
            queryOrder.setPhaSegment1(tOngoodsshelve.getWmsorderid());// 订单号
            queryOrder.setItemId(Integer.parseInt(tOngoodsshelve.getGoodsTypeid()));
            TEbsOrder ebsOrder = itEbsOrderService.selectTEbsOrderList(queryOrder).get(0);
            // 开始写入EBS
            String paramsWmsRcvProc = JSON.toJSONString(createJsonWmsRcvProc(ebsOrder, tOngoodsshelve));
            logger.info("写入EBS参数：{}", paramsWmsRcvProc);
            String resultWmsRcvProc = "";
            try {
                resultWmsRcvProc = HttpUtils.httpPostJson(configService.selectConfigByKey("ebs_ip"), paramsWmsRcvProc, token.get("access_token").toString());
                logger.info("写入EBS响应结果：{}", resultWmsRcvProc);
            } catch (Exception e) {
                tEbsRecordService.insertTEbsRecord(new TEbsRecord("wmsRcvProc", 2, configService.selectConfigByKey("ebs_ip"),
                        paramsWmsRcvProc, resultWmsRcvProc, "-1", "写入EBS", tOngoodsshelve.getGoodsid(), ebsOrder.getItemDescription(), tOngoodsshelve.getProduclotid(), tOngoodsshelve.getShelfNum()));
                // 接口失败
                return error("连接EBS失败");
            }
            System.out.println(resultWmsRcvProc);
            if (!JSON.parseObject(resultWmsRcvProc).getBoolean("success")) {
                tEbsRecordService.insertTEbsRecord(new TEbsRecord("wmsRcvProc", 2, configService.selectConfigByKey("ebs_ip"),
                        paramsWmsRcvProc, resultWmsRcvProc, "-1", "物料入库写入EBS", tOngoodsshelve.getGoodsid(), ebsOrder.getItemDescription(), tOngoodsshelve.getProduclotid(), tOngoodsshelve.getShelfNum()));
                return error("写入EBS失败:" + JSON.parseObject(resultWmsRcvProc).getString("msg"));
            }
            JSONObject resultJsonWmsRcvProc = (JSONObject) JSON.parseObject(resultWmsRcvProc).get("obj");
            JSONObject dataWmsRcvProc = JSON.parseArray(resultJsonWmsRcvProc.getString("rows"), JSONObject.class).get(0);
            if (!dataWmsRcvProc.getString("processStatus").equals("SUCCESS")) {
                tEbsRecordService.insertTEbsRecord(new TEbsRecord("wmsRcvProc", 2, configService.selectConfigByKey("ebs_ip"),
                        paramsWmsRcvProc, resultWmsRcvProc, "-1", "物料入库写入EBS", tOngoodsshelve.getGoodsid(), ebsOrder.getItemDescription(), tOngoodsshelve.getProduclotid(), tOngoodsshelve.getShelfNum()));
                return error("写入EBS失败");
            }
            tEbsRecordService.insertTEbsRecord(new TEbsRecord("wmsRcvProc", 2, configService.selectConfigByKey("ebs_ip"),
                    paramsWmsRcvProc, resultWmsRcvProc, "0", "物料入库写入EBS", tOngoodsshelve.getGoodsid(), ebsOrder.getItemDescription(), tOngoodsshelve.getProduclotid(), tOngoodsshelve.getShelfNum()));
            // 用于查询检验结果
            tOngoodsshelve.setDecid(dataWmsRcvProc.getString("lineLocationId"));
            // 待检----待检状态无法出库
            tOngoodsshelve.setAccStatus("5");
            // 更新信息
            tOngoodsshelfService.updateTOngoodsshelf(tOngoodsshelve);
        }

        return success("写入EBS成功");
    }

    /**
     * 对接ebs
     *
     * @param tOngoodsshelves
     * @return
     * @throws Exception
     */
    public String ebsConfirm(List<TOngoodsshelf> tOngoodsshelves) {
        try {
            // 获取token
            JSONObject token = JSON.parseObject(HttpUtils.httpPostJson(configService.selectConfigByKey("token_ip"), "", ""));
            // 查询物料ID
            for (TOngoodsshelf tOngoodsshelve : tOngoodsshelves) {
                // 物料id
                int itemId;
                // 先查询物料表，根据当前的物料编码
                TBaseGoods goodsTemp = goodsService.selectTBaseGoodsByGoodsId(tOngoodsshelve.getGoodsid());
                if (goodsTemp != null) {
                    itemId = Integer.parseInt(goodsTemp.getGoodsTypeId());
                } else {
                    JSONObject dataGetInvItemId = getInvItemId(tOngoodsshelve.getGoodsid(), token.get("access_token").toString());
                    logger.info("查询到的物料ID结果：{}", JSON.toJSONString(dataGetInvItemId));
                    itemId = dataGetInvItemId.getIntValue("inventoryItemId");
                    // 将查到的信息存放到Goods表
                    TBaseGoods newGoods = new TBaseGoods();
                    // 物料ID
                    newGoods.setGoodsTypeId(String.valueOf(dataGetInvItemId.getIntValue("inventoryItemId")));
                    // 物料编码
                    newGoods.setGoodsId(dataGetInvItemId.getString("itemCode"));
                    // 物料描述
                    newGoods.setGoodsName(dataGetInvItemId.getString("itemDesc"));
                    // 单位
                    newGoods.setUnit(dataGetInvItemId.getString("primaryUnitOfMeasure"));
                    goodsService.insertTBaseGoods(newGoods);
                }
                // 订单号
                String poOrder = tOngoodsshelve.getWmsorderid();
                // 根据物料Id和订单号获取EBS内订单
                List<TEbsOrder> targetOrders;
                // 先查询本地数据库中是否已经缓存过
                TEbsOrder queryOrder = new TEbsOrder();
                queryOrder.setPhaSegment1(poOrder);// 订单号
                queryOrder.setItemId(itemId);
                List<TEbsOrder> ebsOrders = itEbsOrderService.selectTEbsOrderList(queryOrder);
                logger.info("查询到的本地缓存订单：{}", JSON.toJSONString(ebsOrders));
                if (ebsOrders.size() > 0) {// 本地数据库中缓存过
                    targetOrders = ebsOrders;
                } else {
                    targetOrders = getLinesAll(itemId, poOrder, token.get("access_token").toString());
                    logger.info("通过ebs查询到的订单信息：{}", JSON.toJSONString(targetOrders));
                    if (targetOrders == null) {
                        return "当前入库物料在EBS中没有对应订单！";
                    }
                    // 插入ebsOrder表
                    for (TEbsOrder targetOrder : targetOrders) {
                        itEbsOrderService.insertTEbsOrder(targetOrder);
                    }
                }
                // 当前任务的入库数量
                double tempInQuantity = tOngoodsshelve.getShelfNum().doubleValue();
                for (TEbsOrder targetOrder : targetOrders) {
                    // 获取数量
                    double msQuantity = targetOrder.getMsQuantity();
                    if (msQuantity >= tempInQuantity) {
                        // 更新本地的可接收数量
                        targetOrder.setMsQuantity(msQuantity - tempInQuantity);
                        // 物料描述
                        tOngoodsshelve.setGoodsname(targetOrder.getItemDescription());
                        // 单位
                        tOngoodsshelve.setGoodsMeasureId(targetOrder.getUnitMeasLookupCode());
                        // itemID
                        tOngoodsshelve.setGoodsTypeid(targetOrder.getItemId().toString());
                        // 供应商名称
                        tOngoodsshelve.setCustomerId(targetOrder.getVendorName());
                        // 更新剩余入库数量
                        tempInQuantity = 0;
                        break;
                    } else {
                        // 更新本地的可接收数量
                        targetOrder.setMsQuantity(0.0);
                        // 物料描述
                        tOngoodsshelve.setGoodsname(targetOrder.getItemDescription());
                        // 单位
                        tOngoodsshelve.setGoodsMeasureId(targetOrder.getUnitMeasLookupCode());
                        // itemID
                        tOngoodsshelve.setGoodsTypeid(targetOrder.getItemId().toString());
                        // 供应商名称
                        tOngoodsshelve.setCustomerId(targetOrder.getVendorName());
                        // 更新剩余入库数量
                        tempInQuantity -= msQuantity;
                    }
                }
                if (tempInQuantity > 0) {
                    // 报错信息：入库数量超过EBS内订单数量。这条订单无法同步EBS。
                    return "入库数量超过EBS内订单可接收数量。</br>这条订单无法同步EBS。";
                } else {
                    for (TEbsOrder targetOrder : targetOrders) {
                        // 更新EBS缓存的订单信息
                        itEbsOrderService.updateTEbsOrder(targetOrder);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("出现异常：{}", JSON.toJSONString(e));
            return "出现异常";
        }

        return null;
    }

    /**
     * 结束入库
     */
    @Log(title = "入库", businessType = BusinessType.INSERT)
    @PostMapping(value = "/finishNoErpIn",consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public AjaxResult finishNoErpIn(@RequestBody List<TOngoodsshelf> tOngoodsshelves) throws Exception {
        logger.info("接收到入库请求:{}",tOngoodsshelves);
        if(tOngoodsshelves.size() == 0){
            logger.error("提交入库的数据为空");
            return error();
        }
        // 入库id
        String lotId = OrderCodeFactory.getOrderCode("RK", "");
        // 创建日期
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SysUser sysUser = new SysUser();
        if (StringUtils.isEmpty(tOngoodsshelves.get(0).getUserName())) {
            // 获取用户名
            sysUser = ShiroUtils.getCurrentUser();
        } else {
            sysUser.setUserName(tOngoodsshelves.get(0).getUserName());
        }
        // 获取token
        JSONObject token = JSON.parseObject(HttpUtils.httpPostJson(configService.selectConfigByKey("token_ip"), "", ""));
        for (TOngoodsshelf s:
                tOngoodsshelves) {
            s.setAgvsts("0");
            s.setTasktype("0");
            s.setLotId(lotId);
            s.setOrderId(initOrderId());
            s.setCreateDate(sdf.format(date));
            s.setInstatus("0");
            s.setUserName(sysUser.getUserName());
            // 设置子库ID
            s.setWhseloc("121-108");
            // 合格
            s.setAccStatus("0");
            JSONObject dataGetInvItemId = getInvItemId(s.getGoodsid(), token.get("access_token").toString());
            // 物料描述
            s.setGoodsname(dataGetInvItemId.getString("itemDesc"));
            // 单位
            s.setGoodsMeasureId(dataGetInvItemId.getString("primaryUnitOfMeasure"));
            // itemID
            s.setGoodsTypeid(dataGetInvItemId.getString("inventoryItemId"));
        }
        return toAjax(tOngoodsshelfService.insertTOngoodsshelfValues(tOngoodsshelves));
    }

    /**
     * 更新库存
     */
    @Log(title = "更新库存", businessType = BusinessType.INSERT)
    @PostMapping(value = "/MistockIn",consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    public AjaxResult MistockIn(@RequestBody TOngoodsshelf tOngoodsshelve) throws Exception {
        // 查找对应任务
        TOngoodsshelf temp = tOngoodsshelfService.selectTOngoodsshelfByLotId(tOngoodsshelve.getLotId());
        logger.info("根据lotId{}查询到的入库任务信息：{}", tOngoodsshelve.getLotId(), JSON.toJSONString(temp));
        // 将任务插入备份表
        TOngoodsshelfBak tempBak = new TOngoodsshelfBak();
        tempBak.setWmsorderid(temp.getWmsorderid());
        tempBak.setGoodsid(temp.getGoodsid());
        tempBak.setGoodsname(temp.getGoodsname());
        tempBak.setProduclotid(temp.getProduclotid());
        tempBak.setShelfNum(temp.getShelfNum());
        tempBak.setProductionDate(temp.getProductionDate());
        tempBak.setExpirationDate(temp.getExpirationDate());
        tempBak.setProviderId(temp.getProviderId());
        tempBak.setWgh(temp.getWgh());
        tempBak.setLocationId(temp.getLocationId());
        tempBak.setInstand(temp.getInstand());
        tempBak.setCtl(temp.getCtl());
        tempBak.setUserName(temp.getUserName());
        tempBak.setCreateDate(temp.getCreateDate());
        tempBak.setLotId(temp.getLotId());
        tempBak.setStoNum(temp.getStoNum());
        tempBak.setAccNum(temp.getAccNum());
        tempBak.setStockNum(temp.getStockNum());
        tempBak.setOndate(temp.getOndate());
        tempBak.setOnshelfuserid(temp.getOnshelfuserid());
        tempBak.setStorageId(temp.getStorageId());
        tempBak.setStorageAreaId(temp.getStorageAreaId());
        tempBak.setUpgoodsId(temp.getUpgoodsId());
        tempBak.setHasvolume(temp.getHasvolume());
        tempBak.setGoodsTypeid(temp.getGoodsTypeid());
        tempBak.setStorageMode(temp.getStorageMode());
        tempBak.setGoodsvolume(temp.getGoodsvolume());
        tempBak.setBarcode(temp.getBarcode());
        tempBak.setCustomerId(temp.getCustomerId());
        tempBak.setPlcid(temp.getPlcid());
        tempBak.setHigh(temp.getHigh());
        tempBak.setInstatus(temp.getInstatus());
        tempBak.setUnit(temp.getUnit());
        tempBak.setBaozhiqi(temp.getBaozhiqi());
        tempBak.setWhseloc(temp.getWhseloc());
        tempBak.setDecid(temp.getDecid());
        tempBak.setTasktype(temp.getTasktype());
        tempBak.setGoodsMeasureId(temp.getGoodsMeasureId());
        tempBak.setPackingNum(temp.getPackingNum());
        tempBak.setDamageNum(temp.getDamageNum());
        tempBak.setDamageLocation(temp.getDamageLocation());
        tempBak.setWarehousingId(temp.getWarehousingId());
        tempBak.setNetWeigh(temp.getNetWeigh());
        tempBak.setRoughWeight(temp.getRoughWeight());
        tempBak.setScaleUnit(temp.getScaleUnit());
        tempBak.setTotalVolume(temp.getTotalVolume());
        tempBak.setTotalRoughWeight(temp.getTotalRoughWeight());
        tempBak.setTotalNetWeigh(temp.getTotalNetWeigh());
        tempBak.setTotalMoney(temp.getTotalMoney());
        tempBak.setFlag(temp.getFlag());
        tempBak.setStandard(temp.getStandard());
        tempBak.setInnerBatchNo(temp.getInnerBatchNo());
        tempBak.setPrintsts(temp.getPrintsts());
        tempBak.setPrintcs(temp.getPrintcs());
        tempBak.setPurchasetype(temp.getPurchasetype());
        tempBak.setAccStatus(temp.getAccStatus());
        tempBak.setManualTrayState(temp.getManualTrayState());
        tempBak.setAcceId(temp.getAcceId());
        tempBak.setSpec(temp.getSpec());
        tempBak.setBatchno(temp.getBatchno());
        tempBak.setPrintusid(temp.getPrintusid());
        tempBak.setAgvsts(temp.getAgvsts());
        tempBak.setAgvbgn(temp.getAgvbgn());
        tempBak.setAgvend(temp.getAgvend());
        tempBak.setOrderId(temp.getOrderId());

        // 插入库存表
        TMiStock stockTemp = new TMiStock();
        stockTemp.setShelvesNum(temp.getShelfNum());
        stockTemp.setSts("0");
        stockTemp.setFlag("0");
        stockTemp.setStockId(String.valueOf(temp.getPlcid()));
        stockTemp.setStorageId("SCC");
        stockTemp.setGoodsId(temp.getGoodsid());
        stockTemp.setGoodsName(temp.getGoodsname());
        stockTemp.setGoodsTypeid(temp.getGoodsTypeid());
        stockTemp.setAreaId(temp.getLotId());
        stockTemp.setCtl(temp.getCtl());
        stockTemp.setLocationId(temp.getLocationId());
        stockTemp.setProduclotid(temp.getProduclotid());
        stockTemp.setProviderId(temp.getProviderId());
        stockTemp.setPutinId(new GUID().toString());
        stockTemp.setWareDate(new Date());
        stockTemp.setBarcode(temp.getBarcode());
        stockTemp.setWgh(temp.getWgh());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        stockTemp.setProductionDate(sdf.parse("20" + temp.getProductionDate()));
        stockTemp.setExpirationDate(sdf.parse("20" + temp.getExpirationDate()));
        stockTemp.setCustomerId(temp.getCustomerId());
        stockTemp.setWhseloc(temp.getWhseloc());
        stockTemp.setGoodsMeasureId(temp.getGoodsMeasureId());

        try {
            // 插入任务备份表
            tOngoodsshelfBakService.insertTOngoodsshelfBak(tempBak);
            logger.info("插入入库任务记录成功：{}", JSON.toJSONString(tempBak));
            // 删除入库任务
            tOngoodsshelfService.deleteTOngoodsshelfByLotId(temp.getLotId());
            logger.info("删除入库任务成功：{}", JSON.toJSONString(temp));
            // 插入库存
            tMiStockService.insertTMiStock(stockTemp);
            logger.info("插入库存成功：{}", JSON.toJSONString(stockTemp));
        } catch (Exception e) {
            return error(JSON.toJSONString(e));
        }
        return success();
    }

    /**
     * 生成订单号
     */
    private String initOrderId() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        return "SJD" + sdf.format(date) + (int)(Math.random() * 10);
    }

    /**
     * 新增保存入库任务单
     */
    @RequiresPermissions("business:ongoodsshelf:add")
    @Log(title = "入库任务单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(TOngoodsshelf tOngoodsshelf)
    {
        return toAjax(tOngoodsshelfService.insertTOngoodsshelf(tOngoodsshelf));
    }

    /**
     * 修改入库任务单
     */
    @RequiresPermissions("business:ongoodsshelf:edit")
    @GetMapping("/edit/{lotId}")
    public String edit(@PathVariable("lotId") String lotId, ModelMap mmap)
    {
        TOngoodsshelf tOngoodsshelf = tOngoodsshelfService.selectTOngoodsshelfByLotId(lotId);
        mmap.put("tOngoodsshelf", tOngoodsshelf);
        return prefix + "/edit";
    }

    /**
     * 修改保存入库任务单
     */
    @RequiresPermissions("business:ongoodsshelf:edit")
    @Log(title = "入库任务单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TOngoodsshelf tOngoodsshelf)
    {
        return toAjax(tOngoodsshelfService.updateTOngoodsshelf(tOngoodsshelf));
    }

    /**
     * 空托入库
     */

    @Log(title = "空托入库",businessType = BusinessType.INSERT)
    @GetMapping("/emptyPalletIn")
    @ResponseBody
    public AjaxResult emptyPalletIn(){
        logger.info("空托入库开始");
        TOngoodsshelf tOngoodsshelf = new TOngoodsshelf();
        tOngoodsshelf.setTasktype("0");
        tOngoodsshelf.setLotId(OrderCodeFactory.getOrderCode("RK", ""));
        tOngoodsshelf.setGoodsid("000000000");
        tOngoodsshelf.setShelfNum(BigDecimal.ONE);
        tOngoodsshelf.setWgh("0");
        tOngoodsshelf.setInstatus("0");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        tOngoodsshelf.setCreateDate(sdf.format(new Date()));
        // 获取用户名
        SysUser sysUser = ShiroUtils.getCurrentUser();
        tOngoodsshelf.setUserName(sysUser.getUserName());
        return toAjax(tOngoodsshelfService.insertTOngoodsshelf(tOngoodsshelf));
    }

    /**
     * 空托出库
     */
    @Log(title = "空托出库",businessType = BusinessType.INSERT)
    @GetMapping("/emptyPalletOut")
    @ResponseBody
    public AjaxResult emptyPalletOut(){
        logger.info("空托出库开始");
        TCkOrderdetail tCkOrderdetail = new TCkOrderdetail();
        tCkOrderdetail.setCkId(OrderCodeFactory.getOrderCode("CK",null));
        tCkOrderdetail.setGoodId("000000000");
        tCkOrderdetail.setCreateTime(new Date());
        tCkOrderdetail.setPickNum(BigDecimal.ONE);
        tCkOrderdetail.setStatus("0");
        tCkOrderdetail.setAddtime(new Date());
        // 获取用户名
        SysUser sysUser = ShiroUtils.getCurrentUser();
        tCkOrderdetail.setUserName(sysUser.getUserName());
        return toAjax(tckOrderdetailService.insertTCkOrderdetail(tCkOrderdetail));
    }

    private List<TConveyorStatus> getTConveyorStatus(){
        SysUser sysUser = ShiroUtils.getCurrentUser();
        String loginIp = ShiroUtils.getIp();
        TConveyorStatus status = new TConveyorStatus();
        status.setPcip(loginIp);
        List<TConveyorStatus> tConveyorStatuses = tConveyorStatusService.selectTConveyorStatusList(status);
        return tConveyorStatuses;
    }

    /**
     * 删除入库任务单
     */
    @RequiresPermissions("business:ongoodsshelf:remove")
    @Log(title = "入库任务单", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(tOngoodsshelfService.deleteTOngoodsshelfByLotIds(ids));
    }

    /**
     * 创建参数Json(写入ebs)
     * @return
     */
    public JSONObject createJsonWmsRcvProc(TEbsOrder dataGetAll, TOngoodsshelf tOngoodsshelve) throws ParseException {
        // 创建系统参数
        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", "wmsRcvProc");
        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("organizationId", configService.selectConfigByKey("organizationId"));
        businessData.put("poHeaderId", dataGetAll.getPoHeaderId());
        businessData.put("poLineId", dataGetAll.getPoLineId());
        businessData.put("lineLocationId", dataGetAll.getLineLocationId());
        businessData.put("poDistributionId", dataGetAll.getPoDistributionId());
        businessData.put("itemId", dataGetAll.getItemId());
        businessData.put("quantity", tOngoodsshelve.getShelfNum());
        businessData.put("subInventory", "");
//        businessData.put("subInventory", tOngoodsshelve.getWhseloc());
        businessData.put("locatorId", null);
//        businessData.put("locatorId", EbsUtils.LOCATOR_AREA_MAP.get(tOngoodsshelve.getWhseloc()));
        if (!"不控制".equals(dataGetAll.getLotControl())) {
            businessData.put("lotNumber", tOngoodsshelve.getProduclotid());
        }
        businessData.put("receiptDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        businessData.put("expirationDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new SimpleDateFormat("yyyyMMdd").parse("20" + tOngoodsshelve.getExpirationDate())));
        businessData.put("OriginationDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new SimpleDateFormat("yyyyMMdd").parse("20" + tOngoodsshelve.getProductionDate())));

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

    /**
     * 获取物料ID
     * @param goodsId 物料编码
     * @return
     */
    public JSONObject getInvItemId (String goodsId, String token) {
        String paramsGetInvItemId = JSON.toJSONString(createJsonGetInvItemInfosForPcbAps(goodsId));
        logger.info("通过EBS查询物料ID参数：{}", paramsGetInvItemId);
        String resultGetInvItemId = "";
        try {
            resultGetInvItemId = HttpUtils.httpPostJson(configService.selectConfigByKey("ebs_ip"), paramsGetInvItemId, token);
        } catch (Exception e) {
            // 接口失败
            return null;
        }
        JSONObject resultJsonGetInvItemId = (JSONObject) JSON.parseObject(resultGetInvItemId).get("obj");
        return JSON.parseArray(resultJsonGetInvItemId.getString("rows"), JSONObject.class).get(0);
    }

    /**
     * 根据物料ID和订单号获取EBS内订单
     * @param itemId
     * @param poOrder
     * @return
     */
    public List<TEbsOrder> getLinesAll(int itemId, String poOrder, String token) {
        String paramsGetAll = JSON.toJSONString(createJsonGetLinesAll(itemId, poOrder));
        logger.info("通过EBS查询订单参数：{}", paramsGetAll);
        String resultGetAll = "";
        try {
            resultGetAll = HttpUtils.httpPostJson(configService.selectConfigByKey("ebs_ip"), paramsGetAll, token);
        } catch (Exception e) {
            // 接口失败
            return null;
        }
        JSONObject resultJsonGetAll = (JSONObject) JSON.parseObject(resultGetAll).get("obj");
        if (resultJsonGetAll.getIntValue("total") < 1) {
            return null;
        }
        return JSON.parseArray(resultJsonGetAll.getString("rows"), TEbsOrder.class);
    }

    /**
     * 创建参数Json(获取物料ID)
     * @return
     */
    public JSONObject createJsonGetInvItemInfosForPcbAps(String itemCode) {
        // 创建系统参数
        JSONObject systemParams = new JSONObject();
        systemParams.put("requestId", new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()));
        systemParams.put("application", "PCB_APS");
        systemParams.put("sourceSystem", "APS");
        systemParams.put("targetSystem", "EBS");
        systemParams.put("serviceName", "getInvItemInfosForPcbAps");
        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("organizationId", configService.selectConfigByKey("organizationId"));
        baseQueryParams.put("startPosition", 1);
        baseQueryParams.put("rowsCnt", 500);

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

        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(根据物料ID和订单号获取EBS内订单)
     * @return
     */
    public JSONObject createJsonGetLinesAll(int itemId, String poOrder) {
        // 创建系统参数
        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", "getLinesAll");
        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("organizationId", configService.selectConfigByKey("organizationId"));

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

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

}
