package com.ruoyi.web.controller.business;

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.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
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 java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @author liangzhou
 * @Description 任务监视画面
 */
@Controller
@RequestMapping("/business/taskMonitor")
public class TaskController extends BaseController {

    private String prefix = "business/taskMonitor";

    @Autowired
    private ITOngoodsshelfService tOngoodsshelfService;

    @Autowired
    private ITCkPickingwavegoodsService tCkPickingwavegoodsService;

    @Autowired
    private ITBaseStorageAreaLocationService locationService;

    @Autowired
    private ITMiStockService stockService;

    @Autowired
    private ITEbsOrderService itEbsOrderService;

    @Autowired
    private ITTaskMoveService taskMoveService;

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

    @RequiresPermissions("business:taskMonitor:view")
    @GetMapping("/moveTask")
    public String moveTask(ModelMap mmap)
    {
        mmap.put("moveTaskMonitor", new TTaskMove());
        return prefix + "/moveTaskMonitor";
    }

    /**
     * 查询库存列表
     */
    @RequiresPermissions("business:taskMonitor:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Task taskMonitor)
    {
        startPage();
        // 如果任务Id非空
        if (StringUtils.isNotEmpty(taskMonitor.getTaskId())) {
            return getDataTable(selectTaskByTaskId(taskMonitor.getTaskId()));
        }

        return getDataTable(selectTask());
    }

    /**
     * 查询库存列表
     */
    @RequiresPermissions("business:taskMonitor:list")
    @PostMapping("/moveTask/list")
    @ResponseBody
    public TableDataInfo moveTaskList(TTaskMove moveTask)
    {
        startPage();
        LambdaQueryWrapper<TTaskMove> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(moveTask.getVehicleId())) {
            queryWrapper.eq(TTaskMove::getVehicleId, moveTask.getVehicleId());
        }

        return getDataTable(taskMoveService.list(queryWrapper));
    }

    /**
     * 修改移库任务状态
     */
    @Log(title = "修改移库任务状态", businessType = BusinessType.UPDATE)
    @PostMapping("/moveTask/changeMoveTask")
    @ResponseBody
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    public AjaxResult changeMoveTask(TTaskMove moveTask) {
        if (moveTask == null || StringUtils.isEmpty(moveTask.getTaskId()) || moveTask.getTaskStatus() == null) {
            return error("缺少必填项");
        }
        TTaskMove needUpdateTask = taskMoveService.getOne(
                new LambdaQueryWrapper<TTaskMove>()
                        .eq(TTaskMove::getTaskId, moveTask.getTaskId())
        );
        if (needUpdateTask == null) {
            return error("移库任务不存在");
        }
        if (moveTask.getTaskStatus() == 0 || moveTask.getTaskStatus() == 2) {// 重置或者完成任务
            needUpdateTask.setTaskStatus(moveTask.getTaskStatus());
            try {
                taskMoveService.update(needUpdateTask, new LambdaUpdateWrapper<TTaskMove>().eq(TTaskMove::getTaskId, moveTask.getTaskId()));
                return success("更改移库任务状态成功");
            } catch (Exception e) {
                // 回滚事务
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return error("更改移库任务状态发生异常");
            }
        }
        if (moveTask.getTaskStatus() == 9) {// 取消任务
            try {
                // 恢复库存状态
                LambdaUpdateWrapper<TMiStock> stockUpdateWrapper = new LambdaUpdateWrapper<TMiStock>()
                        .set(TMiStock::getFlag, "0")
                        .eq(TMiStock::getCtl, needUpdateTask.getVehicleId());
                stockService.update(stockUpdateWrapper);
                // 还原库位状态
                LambdaUpdateWrapper<TBaseStorageAreaLocation> locationUpdateWrapper = new LambdaUpdateWrapper<TBaseStorageAreaLocation>()
                        .set(TBaseStorageAreaLocation::getStatus, "0")
                        .eq(TBaseStorageAreaLocation::getLocationId, needUpdateTask.getDestination());
                locationService.update(locationUpdateWrapper);
                // 删除移库任务
                taskMoveService.remove(new LambdaQueryWrapper<TTaskMove>().eq(TTaskMove::getTaskId, moveTask.getTaskId()));
                return success("取消移库任务成功");
            } catch (Exception e) {
                // 回滚事务
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return error("取消移库任务发生异常");
            }
        }
        return error("没有可进行的操作");
    }

    /**
     * 删除任务
     */
    @Log(title = "删除任务", businessType = BusinessType.DELETE)
    @PostMapping("/delTask")
    @ResponseBody
    public AjaxResult delTask(Task taskMonitor) {
        try {
            if (taskMonitor.getTaskMode().equals("1")) {
                // 查询到需要删除的任务
                TOngoodsshelf targetTask = tOngoodsshelfService.selectTOngoodsshelfByLotId(taskMonitor.getTaskNo());
                // 删除入库任务
                tOngoodsshelfService.deleteTOngoodsshelfByLotId(targetTask.getLotId());
                // 恢复库位状态
                TBaseStorageAreaLocation targetLocation = locationService.selectTBaseStorageAreaLocationByLocationId(targetTask.getLocationId());
                targetLocation.setStatus("0");
                locationService.updateTBaseStorageAreaLocation(targetLocation);
                // 查询本地缓存的对应的订单信息
                TEbsOrder ebsOrder = new TEbsOrder();
                ebsOrder.setPhaSegment1(targetTask.getWmsorderid());// 订单号
                ebsOrder.setItemId(Integer.valueOf(targetTask.getGoodsTypeid()));
                // 删除本地缓存的订单
                itEbsOrderService.deleteTEbsOrder(ebsOrder);
            } else {
                // 查询到需要删除的任务
                TCkPickingwavegoods targetTask = tCkPickingwavegoodsService.selectTCkPickingwavegoodsByPickingid(taskMonitor.getTaskNo());
                // 删除出库任务
                tCkPickingwavegoodsService.deleteTCkPickingwavegoodsByPickingid(targetTask.getPickingid());
                // 恢复库存状态
                TMiStock query = new TMiStock();
                query.setLocationId(targetTask.getLocId());
                query.setCtl(targetTask.getCtl());
                List<TMiStock> targetStockList = stockService.selectTMiStockList(query);
                if (targetStockList.size() < 1) {
                    return error("0");
                }
                TMiStock targetStock = targetStockList.get(0);
                targetStock.setFlag("0");
                stockService.updateTMiStock(targetStock);
            }
        } catch (Exception e) {
            return error("-1");
        }
        return success("1");
    }

    /**
     * 已处理任务
     */
    @Log(title = "已处理任务", businessType = BusinessType.UPDATE)
    @PostMapping("/solveTask")
    @ResponseBody
    public AjaxResult solveTask(Task taskMonitor) {
        try {
            if (taskMonitor.getTaskMode().equals("1")) {
                // 查询到需要的任务
                TOngoodsshelf targetTask = tOngoodsshelfService.selectTOngoodsshelfByLotId(taskMonitor.getTaskNo());
                // 更新入库任务状态为已完成
                targetTask.setInstatus("2");
                tOngoodsshelfService.updateTOngoodsshelf(targetTask);
            } else {
                // 查询到需要删除的任务
                TCkPickingwavegoods targetTask = tCkPickingwavegoodsService.selectTCkPickingwavegoodsByPickingid(taskMonitor.getTaskNo());
                // 更新出库任务状态为完成
                targetTask.setOutstatus("2");
                tCkPickingwavegoodsService.updateTCkPickingwavegoods(targetTask);
            }
        } catch (Exception e) {
            return error("-1");
        }
        return success("1");
    }

    /**
     * 已处理任务
     */
    @Log(title = "已处理任务", businessType = BusinessType.UPDATE)
    @PostMapping("/agvComplete")
    @ResponseBody
    public AjaxResult agvComplete(Task taskMonitor) {
        try {
            if (taskMonitor.getTaskMode().equals("1")) {
                // 查询到需要的任务
                TOngoodsshelf targetTask = tOngoodsshelfService.selectTOngoodsshelfByLotId(taskMonitor.getTaskNo());
                // 更新AGV任务状态为已完成
                targetTask.setAgvsts("2");
                tOngoodsshelfService.updateTOngoodsshelf(targetTask);
            }
        } catch (Exception e) {
            return error("-1");
        }
        return success("1");
    }

    /**
     * 重置任务
     */
    @Log(title = "重置任务", businessType = BusinessType.UPDATE)
    @PostMapping("/rebootTask")
    @ResponseBody
    public AjaxResult rebootTask(Task taskMonitor) {
        try {
            if (taskMonitor.getTaskMode().equals("1")) {
                // 查询到需要的任务
                TOngoodsshelf targetTask = tOngoodsshelfService.selectTOngoodsshelfByLotId(taskMonitor.getTaskNo());
                // 更新入库任务状态为已完成
                targetTask.setInstatus("0");
                tOngoodsshelfService.updateTOngoodsshelf(targetTask);
            } else {
                // 查询到需要删除的任务
                TCkPickingwavegoods targetTask = tCkPickingwavegoodsService.selectTCkPickingwavegoodsByPickingid(taskMonitor.getTaskNo());
                // 更新出库任务状态为完成
                targetTask.setOutstatus("0");
                tCkPickingwavegoodsService.updateTCkPickingwavegoods(targetTask);
            }
        } catch (Exception e) {
            return error("-1");
        }
        return success("1");
    }

    /**
     * 根据任务Id查找任务
     * @param taskId
     * @return
     */
    public List<Task> selectTaskByTaskId(String taskId) {
        // 获取入库任务列表
        TOngoodsshelf tOngoodsshelf = new TOngoodsshelf();
        tOngoodsshelf.setPlcid(Long.valueOf(taskId));
        List<TOngoodsshelf> inTaskList = tOngoodsshelfService.selectTOngoodsshelfList(tOngoodsshelf);
        // 获取出库任务列表
        TCkPickingwavegoods tCkPickingwavegoods = new TCkPickingwavegoods();
        tCkPickingwavegoods.setPlcid(taskId);
        List<TCkPickingwavegoods> outTaskList = tCkPickingwavegoodsService.selectTCkPickingwavegoodsList(tCkPickingwavegoods);

        return setTask(inTaskList, outTaskList);
    }

    /**
     * 查询所有任务
     * @return
     */
    public List<Task> selectTask() {
        // 获取入库任务列表
        List<TOngoodsshelf> inTaskList = tOngoodsshelfService.selectTOngoodsshelfList(new TOngoodsshelf());
        // 获取出库任务列表
        List<TCkPickingwavegoods> outTaskList = tCkPickingwavegoodsService.selectTCkPickingwavegoodsList(new TCkPickingwavegoods());

        return setTask(inTaskList, outTaskList);
    }

    /**
     * 根据入库任务，出库任务设置任务列表
     * @param inTaskList
     * @param outTaskList
     * @return
     */
    private List<Task> setTask(List<TOngoodsshelf> inTaskList, List<TCkPickingwavegoods> outTaskList) {
        // 生成任务监控列表
        List<Task> taskList = new ArrayList<Task>();
        // 日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 入库任务插入任务列表
        for (TOngoodsshelf inTask : inTaskList) {
            Task tempTask = new Task();
            // 任务编号
            tempTask.setTaskNo(inTask.getLotId());
            // 任务时间
            tempTask.setTaskTime(inTask.getCreateDate());
            // 任务ID
            tempTask.setTaskId(String.valueOf(inTask.getPlcid()));
            // 物料编号
            tempTask.setGoodsId(inTask.getGoodsid());
            // 数量
            tempTask.setOpNumber(inTask.getShelfNum());
            // 起始货位
            tempTask.setStartLocation(inTask.getInstand());
            // 目标货位
            tempTask.setTargetLocation(inTask.getLocationId());
            // 托盘号
            tempTask.setCtl(inTask.getCtl());
            // 任务模式
            tempTask.setTaskMode("1");
            // 任务状态
            tempTask.setStatus(inTask.getInstatus());

            taskList.add(tempTask);
        }

        // 出库任务插入任务列表
        for (TCkPickingwavegoods outTask : outTaskList) {
            Task tempTask = new Task();
            // 任务编号
            tempTask.setTaskNo(outTask.getPickingid());
            // 任务时间
            tempTask.setTaskTime(sdf.format(outTask.getCreateTime()));
            // 任务ID
            tempTask.setTaskId(outTask.getPlcid());
            // 物料编号
            tempTask.setGoodsId(outTask.getGoodId());
            // 数量
            tempTask.setOpNumber(outTask.getPickingNum());
            // 起始货位
            tempTask.setStartLocation(outTask.getLocId());
            // 目标货位
            tempTask.setTargetLocation(outTask.getOutstand());
            // 托盘号
            tempTask.setCtl(outTask.getCtl());
            // 任务模式
            tempTask.setTaskMode("2");
            // 任务状态
            tempTask.setStatus(outTask.getOutstatus());

            taskList.add(tempTask);
        }

        return taskList;
    }
}