package com.wms.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wms.annotation.MyLog;
import com.wms.constants.enums.ResponseCode;
import com.wms.entity.app.ResponseEntity;
import com.wms.entity.app.dto.PageDto;
import com.wms.entity.app.dto.StockOfGoodsDto;
import com.wms.entity.app.dto.extend.KanbanEntity;
import com.wms.entity.app.request.*;
import com.wms.entity.app.vo.*;
import com.wms.entity.table.*;
import com.wms.service.*;
import com.wms.utils.HttpUtils;
import com.wms.utils.StringUtils;
import com.wms.utils.excel.vo.ClcKanbanRequirementExcelVo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.joda.time.LocalDate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.wms.utils.StringUtils.convertJsonString;

/**
 * WMS库存控制类
 *
 * @author 梁州
 * &#064;date  2023/2/14
 */
@Controller
@CrossOrigin
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@RequestMapping(value = "/wms/kateWork")
public class KateWorkQueryController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * DBS服务
     */
    private final KateDBSService kateDBSService;
    /**
     * 工单服务
     */
    private final KateOrdersService kateOrderService;
    /**
     * 站台配置服务
     */
    private final WorkStationConfigService workStationConfigService;
    /**
     * 库存服务
     */
    private final StockService stockService;
    /**
     * 工作流服务
     */
    private final WorkFlowService workFlowService;
    /**
     * 工作总结服务
     */
    private final WorkSummaryService workSummaryService;
    /**
     * 物料服务
     */
    private final GoodsService goodsService;
    /**
     * 看板服务
     */
    private final KanbanService kanbanService;
    /**
     * 站台服务
     */
    private final StandService standService;
    /**
     * 库位配置服务
     */
    private final ELocationConfigLastService eLocationConfigLastService;
    /**
     * 请求头部信息
     */
    private final HttpServletRequest servletRequest;

    /**
     * 查询DBS
     */
    @PostMapping("/getDbs")
    @ResponseBody
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    public String getDbs(@RequestBody DbsQuery dbsQuery) {
        logger.info("接收到查询Dbs请求：{}，请求ip：{}", convertJsonString(dbsQuery), HttpUtils.getIpAddr(servletRequest));
        ResponseEntity response = new ResponseEntity();
        try {
            Page<KateDBS> page = dbsQuery.toMpPage();
            Page<KateDBS> dbsPage = kateDBSService.page(page, new LambdaQueryWrapper<KateDBS>()
                    .like(StringUtils.isNotEmpty(dbsQuery.getWorkOrder()), KateDBS::getWorkOrder, dbsQuery.getWorkOrder()));

            PageDto<DbsVo> pageDto = PageDto.of(dbsPage, dbs -> BeanUtil.copyProperties(dbs, DbsVo.class));
            response.setCode(ResponseCode.OK.getCode());
            response.setMessage("查询DBS成功");
            response.setReturnData(pageDto);
            return convertJsonString(response);
        } catch (Exception e) {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("查询DBS发生异常：{}", convertJsonString(e));
            response.setCode(ResponseCode.ERROR.getCode());
            response.setMessage("查询DBS发生异常");
            return convertJsonString(response);
        }
    }


    /**
     * 更新DBS
     *
     * @param dbsQuery 修改参数
     * @return 结果
     */
    @PostMapping("/updateDbs")
    @ResponseBody
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    @MyLog(logTitle = "更新DBS", logMethod = "updateDbs")
    public String updateDbs(@RequestBody DbsQuery dbsQuery) {
        logger.info("接收到更新DBS请求：{}，请求ip：{}", convertJsonString(dbsQuery), HttpUtils.getIpAddr(servletRequest));
        // 创建响应信息
        ResponseEntity rsp = new ResponseEntity();
        try {
            if (StringUtils.isEmpty(dbsQuery.getDbsId())) {// id为空，不允许执行
                logger.error("请求的id为空，不允许修改。");
                rsp.setCode(ResponseCode.ERROR.getCode());
                rsp.setMessage("请求的id为空，不允许修改。");
                return convertJsonString(rsp);
            }
            boolean updateResult = kateDBSService.update(new LambdaUpdateWrapper<KateDBS>()
                    .set(dbsQuery.getWorkSequence() != null, KateDBS::getWorkSequence, dbsQuery.getWorkSequence())
                    .set(dbsQuery.getDbsStatus() != null, KateDBS::getDbsStatus, dbsQuery.getDbsStatus())
                    .set(StringUtils.isNotEmpty(dbsQuery.getMachineNo()), KateDBS::getMachineNo, dbsQuery.getMachineNo())
                    .set(dbsQuery.getPlanStartDate() != null, KateDBS::getPlanStartDate, dbsQuery.getPlanStartDate())
                    .set(KateDBS::getLastUpdateTime, LocalDateTime.now())
                    .set(KateDBS::getLastUpdateUser, dbsQuery.getUserName())
                    .eq(KateDBS::getDbsId, dbsQuery.getDbsId()));
            if (updateResult) {
                logger.info("更新Dbs成功。");
                rsp.setCode(ResponseCode.OK.getCode());
                rsp.setMessage("更新Dbs成功。");
            } else {
                logger.error("更新Dbs失败。");
                rsp.setCode(ResponseCode.ERROR.getCode());
                rsp.setMessage("更新Dbs失败。");
            }
            return convertJsonString(rsp);
        } catch (Exception e) {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.info("更新Dbs发生异常：{}", convertJsonString(e));
            // 返回其他异常
            rsp.setCode(ResponseCode.ERROR.getCode());
            rsp.setMessage("更新Dbs发生异常");
            return convertJsonString(rsp);
        }
    }

    /**
     * 删除Dbs
     *
     * @param dbsQuery dbs查询参数
     * @return 结果
     */
    @PostMapping("/deleteDbs")
    @ResponseBody
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    @MyLog(logTitle = "删除dbs", logMethod = "deleteDbs")
    public String deleteDbs(@RequestBody DbsQuery dbsQuery) {
        logger.info("接收到删除dbs请求：{}，请求ip：{}", convertJsonString(dbsQuery), HttpUtils.getIpAddr(servletRequest));
        // 创建响应信息
        ResponseEntity rsp = new ResponseEntity();
        try {
            if (StringUtils.isEmpty(dbsQuery.getDbsId())) {// id为空，不允许执行
                logger.error("请求的id为空，不允许删除。");
                rsp.setCode(ResponseCode.ERROR.getCode());
                rsp.setMessage("请求的id为空，不允许删除。");
                return convertJsonString(rsp);
            }
            // 删除数据
            if (kateDBSService.remove(new LambdaQueryWrapper<KateDBS>().eq(KateDBS::getDbsId, dbsQuery.getDbsId()))) {
                // 返回成功
                logger.info("删除dbs成功");
                rsp.setCode(ResponseCode.OK.getCode());
                rsp.setMessage("删除dbs成功");
            } else {
                // 返回失败
                logger.error("删除dbs失败");
                rsp.setCode(ResponseCode.ERROR.getCode());
                rsp.setMessage("删除dbs失败");
            }
            return convertJsonString(rsp);
        } catch (Exception e) {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.info("删除dbs发生异常：{}", convertJsonString(e));
            // 返回其他异常
            rsp.setCode(ResponseCode.ERROR.getCode());
            rsp.setMessage("删除dbs发生异常");
            return convertJsonString(rsp);
        }
    }

    /**
     * 查询工单
     */
    @PostMapping("/getOrders")
    @ResponseBody
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    public String getOrders(@RequestBody KateOrdersQuery kateOrdersQuery) {
        logger.info("接收到查询工单请求：{}，请求ip：{}", convertJsonString(kateOrdersQuery), HttpUtils.getIpAddr(servletRequest));
        ResponseEntity response = new ResponseEntity();
        try {
            Page<KateOrders> page = kateOrdersQuery.toMpPage();
            Page<KateOrders> ordersPage = kateOrderService.page(page, new LambdaQueryWrapper<KateOrders>()
                    .like(StringUtils.isNotEmpty(kateOrdersQuery.getWorkOrder()), KateOrders::getWorkOrder, kateOrdersQuery.getWorkOrder())
                    .like(StringUtils.isNotEmpty(kateOrdersQuery.getGoodsId()), KateOrders::getGoodsId, kateOrdersQuery.getGoodsId())
                    .like(StringUtils.isNotEmpty(kateOrdersQuery.getSupplyArea()), KateOrders::getSupplyArea, kateOrdersQuery.getSupplyArea()));

            PageDto<KateOrdersVo> pageDto = PageDto.of(ordersPage, orders -> BeanUtil.copyProperties(orders, KateOrdersVo.class));
            response.setCode(ResponseCode.OK.getCode());
            response.setMessage("查询工单成功");
            response.setReturnData(pageDto);
            return convertJsonString(response);
        } catch (Exception e) {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("查询工单发生异常：{}", convertJsonString(e));
            response.setCode(ResponseCode.ERROR.getCode());
            response.setMessage("查询工单发生异常");
            return convertJsonString(response);
        }
    }


    /**
     * 更新工单
     *
     * @param kateOrdersQuery 修改参数
     * @return 结果
     */
    @PostMapping("/updateOrders")
    @ResponseBody
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    @MyLog(logTitle = "更新工单", logMethod = "updateOrders")
    public String updateOrders(@RequestBody KateOrdersQuery kateOrdersQuery) {
        logger.info("接收到更新工单请求：{}，请求ip：{}", convertJsonString(kateOrdersQuery), HttpUtils.getIpAddr(servletRequest));
        // 创建响应信息
        ResponseEntity rsp = new ResponseEntity();
        try {
            if (StringUtils.isEmpty(kateOrdersQuery.getOrderId())) {// id为空，不允许执行
                logger.error("请求的id为空，不允许修改。");
                rsp.setCode(ResponseCode.ERROR.getCode());
                rsp.setMessage("请求的id为空，不允许修改。");
                return convertJsonString(rsp);
            }
            boolean updateResult = kateOrderService.update(new LambdaUpdateWrapper<KateOrders>()
                    .set(kateOrdersQuery.getOrderStatus() != null, KateOrders::getOrderStatus, kateOrdersQuery.getOrderStatus())
                    .set(kateOrdersQuery.getLackQuantity() != null, KateOrders::getLackQuantity, kateOrdersQuery.getLackQuantity())
                    .set(kateOrdersQuery.getPickedQuantity() != null, KateOrders::getPickedQuantity, kateOrdersQuery.getPickedQuantity())
                    .set(kateOrdersQuery.getRequirementQuantity() != null, KateOrders::getRequirementQuantity, kateOrdersQuery.getRequirementQuantity())
                    .set(kateOrdersQuery.getOrderStatus() == 4, KateOrders::getFinishTime, LocalDateTime.now())
                    .set(kateOrdersQuery.getOrderStatus() == 4, KateOrders::getUserName, kateOrdersQuery.getUserName())
                    .eq(KateOrders::getOrderId, kateOrdersQuery.getOrderId()));
            if (updateResult) {
                logger.info("更新工单成功。");
                rsp.setCode(ResponseCode.OK.getCode());
                rsp.setMessage("更新工单成功。");
            } else {
                logger.error("更新工单失败。");
                rsp.setCode(ResponseCode.ERROR.getCode());
                rsp.setMessage("更新工单失败。");
            }
            return convertJsonString(rsp);
        } catch (Exception e) {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.info("更新工单发生异常：{}", convertJsonString(e));
            // 返回其他异常
            rsp.setCode(ResponseCode.ERROR.getCode());
            rsp.setMessage("更新工单发生异常");
            return convertJsonString(rsp);
        }
    }

    /**
     * 删除工单
     *
     * @param kateOrdersQuery 查询参数
     * @return 结果
     */
    @PostMapping("/deleteOrders")
    @ResponseBody
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    @MyLog(logTitle = "删除工单", logMethod = "deleteOrders")
    public String deleteOrders(@RequestBody KateOrdersQuery kateOrdersQuery) {
        logger.info("接收到删除工单请求：{}，请求ip：{}", convertJsonString(kateOrdersQuery), HttpUtils.getIpAddr(servletRequest));
        // 创建响应信息
        ResponseEntity rsp = new ResponseEntity();
        try {
            if (StringUtils.isEmpty(kateOrdersQuery.getOrderId())) {// id为空，不允许执行
                logger.error("请求的id为空，不允许删除。");
                rsp.setCode(ResponseCode.ERROR.getCode());
                rsp.setMessage("请求的id为空，不允许删除。");
                return convertJsonString(rsp);
            }
            // 删除数据
            if (kateOrderService.remove(new LambdaQueryWrapper<KateOrders>().eq(KateOrders::getOrderId, kateOrdersQuery.getOrderId()))) {
                // 返回成功
                logger.info("删除工单成功");
                rsp.setCode(ResponseCode.OK.getCode());
                rsp.setMessage("删除工单成功");
            } else {
                // 返回失败
                logger.error("删除工单失败");
                rsp.setCode(ResponseCode.ERROR.getCode());
                rsp.setMessage("删除工单失败");
            }
            return convertJsonString(rsp);
        } catch (Exception e) {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.info("删除工单发生异常：{}", convertJsonString(e));
            // 返回其他异常
            rsp.setCode(ResponseCode.ERROR.getCode());
            rsp.setMessage("删除工单发生异常");
            return convertJsonString(rsp);
        }
    }

    /**
     * 查询工站配置
     */
    @PostMapping("/getStationConfigs")
    @ResponseBody
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    public String getStationConfigs(@RequestBody StationConfigQuery stationConfigQuery) {
        logger.info("接收到查询工站配置：{}，请求ip：{}", convertJsonString(stationConfigQuery), HttpUtils.getIpAddr(servletRequest));
        ResponseEntity response = new ResponseEntity();
        try {
            Page<WorkStationConfig> page = stationConfigQuery.toMpPage();
            Page<WorkStationConfig> configsPage = workStationConfigService.page(page, new LambdaQueryWrapper<WorkStationConfig>()
                    .like(StringUtils.isNotEmpty(stationConfigQuery.getWorkStation()), WorkStationConfig::getWorkStation, stationConfigQuery.getWorkStation())
                    .like(StringUtils.isNotEmpty(stationConfigQuery.getSmallBox()), WorkStationConfig::getSmallBox, stationConfigQuery.getSmallBox()));
            PageDto<StationConfigVo> pageDto = PageDto.of(configsPage, StationConfigVo::of);
            response.setCode(ResponseCode.OK.getCode());
            response.setMessage("查询工站配置");
            response.setReturnData(pageDto);
            return convertJsonString(response);
        } catch (Exception e) {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("查询工站配置发生异常：{}", convertJsonString(e));
            response.setCode(ResponseCode.ERROR.getCode());
            response.setMessage("查询工站配置发生异常");
            return convertJsonString(response);
        }
    }

    /**
     * 更新工站配置
     *
     * @param stationConfigQuery 修改参数
     * @return 结果
     */
    @PostMapping("/updateStationConfigs")
    @ResponseBody
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    @MyLog(logTitle = "更新工站配置", logMethod = "updateStationConfigs")
    public String updateStationConfigs(@RequestBody StationConfigQuery stationConfigQuery) {
        logger.info("接收到更新工站配置请求：{}，请求ip：{}", convertJsonString(stationConfigQuery), HttpUtils.getIpAddr(servletRequest));
        // 创建响应信息
        ResponseEntity rsp = new ResponseEntity();
        try {
            if (StringUtils.isEmpty(stationConfigQuery.getConfigId())) {// id为空，不允许执行
                logger.error("请求的id为空，不允许修改。");
                rsp.setCode(ResponseCode.ERROR.getCode());
                rsp.setMessage("请求的id为空，不允许修改。");
                return convertJsonString(rsp);
            }
            boolean updateResult = workStationConfigService.update(new LambdaUpdateWrapper<WorkStationConfig>()
                    .set(WorkStationConfig::getLastUpdateUser, stationConfigQuery.getUserName())
                    .set(WorkStationConfig::getLastUpdateTime, LocalDateTime.now())
                    .set(stationConfigQuery.getOrderQuantity() != null && stationConfigQuery.getOrderQuantity() > 0, WorkStationConfig::getOrderQuantity, stationConfigQuery.getOrderQuantity())
                    .set(StringUtils.isNotEmpty(stationConfigQuery.getWorkStation()), WorkStationConfig::getWorkStation, stationConfigQuery.getWorkStation())
                    .set(stationConfigQuery.getStartDateAdjust() != null, WorkStationConfig::getStartDateAdjust, stationConfigQuery.getStartDateAdjust())
                    .eq(WorkStationConfig::getConfigId, stationConfigQuery.getConfigId()));
            if (updateResult) {
                logger.info("更新更新工站配置成功。");
                rsp.setCode(ResponseCode.OK.getCode());
                rsp.setMessage("更新更新工站配置成功。");
            } else {
                logger.error("更新更新工站配置失败。");
                rsp.setCode(ResponseCode.ERROR.getCode());
                rsp.setMessage("更新更新工站配置失败。");
            }
            return convertJsonString(rsp);
        } catch (Exception e) {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.info("更新更新工站配置发生异常：{}", convertJsonString(e));
            // 返回其他异常
            rsp.setCode(ResponseCode.ERROR.getCode());
            rsp.setMessage("更新更新工站配置发生异常");
            return convertJsonString(rsp);
        }
    }

    /**
     * 删除工站配置
     *
     * @param stationConfigQuery 查询参数
     * @return 结果
     */
    @PostMapping("/deleteStationConfigs")
    @ResponseBody
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    @MyLog(logTitle = "删除工站配置", logMethod = "deleteStationConfigs")
    public String deleteStationConfigs(@RequestBody StationConfigQuery stationConfigQuery) {
        logger.info("接收到删除工站配置请求：{}，请求ip：{}", convertJsonString(stationConfigQuery), HttpUtils.getIpAddr(servletRequest));
        // 创建响应信息
        ResponseEntity rsp = new ResponseEntity();
        try {
            if (StringUtils.isEmpty(stationConfigQuery.getConfigId())) {// id为空，不允许执行
                logger.error("请求的id为空，不允许删除。");
                rsp.setCode(ResponseCode.ERROR.getCode());
                rsp.setMessage("请求的id为空，不允许删除。");
                return convertJsonString(rsp);
            }
            // 删除数据
            if (workStationConfigService.remove(new LambdaQueryWrapper<WorkStationConfig>().eq(WorkStationConfig::getConfigId, stationConfigQuery.getConfigId()))) {
                // 返回成功
                logger.info("删除工站配置成功");
                rsp.setCode(ResponseCode.OK.getCode());
                rsp.setMessage("删除工站配置成功");
            } else {
                // 返回失败
                logger.error("删除工站配置失败");
                rsp.setCode(ResponseCode.ERROR.getCode());
                rsp.setMessage("删除工站配置失败");
            }
            return convertJsonString(rsp);
        } catch (Exception e) {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.info("删除工站配置发生异常：{}", convertJsonString(e));
            // 返回其他异常
            rsp.setCode(ResponseCode.ERROR.getCode());
            rsp.setMessage("删除工站配置发生异常");
            return convertJsonString(rsp);
        }
    }

    /**
     * 获取CLC看板需求
     */
    @PostMapping("/getClcKanbanRequirement")
    @ResponseBody
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    @MyLog(logTitle = "获取CLC看板需求", logMethod = "getClcKanbanRequirement")
    public String getClcKanbanRequirement(@RequestBody ClcKanbanRequirementRequest request) {
        logger.info("获取CLC看板需求：{}，请求ip：{}", convertJsonString(request), HttpUtils.getIpAddr(servletRequest));
        ResponseEntity response = new ResponseEntity();
        try {
            // 返回的Vo
            ClcKanbanRequirementVo clcKanbanVo = new ClcKanbanRequirementVo();
            // 查询物料库存信息
            List<StockOfGoodsDto> stockOfGoodsDtoList = stockService.selectSumOfGoods("");
            if (stockOfGoodsDtoList == null || stockOfGoodsDtoList.isEmpty()) {
                clcKanbanVo.setAllZero();
            } else {
                BigDecimal TotalNumOfType = BigDecimal.ZERO;// 总需求类型数量
                BigDecimal TotalNumOfPc = BigDecimal.ZERO;// 总需求Pc数量
                BigDecimal TotalNumOfBox = BigDecimal.ZERO;// 总需求盒数
                BigDecimal NumOfTypeOf810 = BigDecimal.ZERO;// #810的料号数量
                BigDecimal NumOfTypeOf811 = BigDecimal.ZERO;// #811的料号数量
                BigDecimal NumOfTypeOf911 = BigDecimal.ZERO;// #911的料号数量
                BigDecimal NumOfTypeOf822 = BigDecimal.ZERO;// #822的料号数量
                BigDecimal NumOfPcOf810 = BigDecimal.ZERO;// #810零件数量
                BigDecimal NumOfPcOf811 = BigDecimal.ZERO;// #811零件数量
                BigDecimal NumOfPcOf911 = BigDecimal.ZERO;// #911零件数量
                BigDecimal NumOfPcOf822 = BigDecimal.ZERO;// #822零件数量
                BigDecimal NumOfBoxOf810 = BigDecimal.ZERO;// #810需求盒数
                BigDecimal NumOfBoxOf811 = BigDecimal.ZERO;// #811需求盒数
                BigDecimal NumOfBoxOf911 = BigDecimal.ZERO;// #911需求盒数
                BigDecimal NumOfBoxOf822 = BigDecimal.ZERO;// #822需求盒数
                for (StockOfGoodsDto stockOfGoodsDto : stockOfGoodsDtoList) {
                    if (Objects.equals(stockOfGoodsDto.getFeedType(), "PULL")) {
                        // 剩余数量少于补货点时，需要补货
                        if (stockOfGoodsDto.getRemainNumSum().compareTo(stockOfGoodsDto.getFeedPoint()) <= 0) {
                            TotalNumOfType = TotalNumOfType.add(BigDecimal.ONE);
                            BigDecimal targetNum = stockOfGoodsDto.getNumOfKanban().multiply(stockOfGoodsDto.getNumOfPerKanban());
                            // 计算需要多少个看板
                            BigDecimal needKanbanQuantity = targetNum.subtract(stockOfGoodsDto.getRemainNumSum()).divide(stockOfGoodsDto.getNumOfPerKanban(), 0, RoundingMode.FLOOR);
                            TotalNumOfPc = TotalNumOfPc.add(needKanbanQuantity.multiply(stockOfGoodsDto.getNumOfPerKanban()));
                            TotalNumOfBox = TotalNumOfBox.add(needKanbanQuantity);
                            if (stockOfGoodsDto.getBoxType().contains("810")) {
                                NumOfTypeOf810 = NumOfTypeOf810.add(BigDecimal.ONE);
                                NumOfPcOf810 = NumOfPcOf810.add(needKanbanQuantity.multiply(stockOfGoodsDto.getNumOfPerKanban()));
                                NumOfBoxOf810 = NumOfBoxOf810.add(needKanbanQuantity);
                            } else if (stockOfGoodsDto.getBoxType().contains("811")) {
                                NumOfTypeOf811 = NumOfTypeOf811.add(BigDecimal.ONE);
                                NumOfPcOf811 = NumOfPcOf811.add(needKanbanQuantity.multiply(stockOfGoodsDto.getNumOfPerKanban()));
                                NumOfBoxOf811 = NumOfBoxOf811.add(needKanbanQuantity);
                            } else if (stockOfGoodsDto.getBoxType().contains("911")) {
                                NumOfTypeOf911 = NumOfTypeOf911.add(BigDecimal.ONE);
                                NumOfPcOf911 = NumOfPcOf911.add(needKanbanQuantity.multiply(stockOfGoodsDto.getNumOfPerKanban()));
                                NumOfBoxOf911 = NumOfBoxOf911.add(needKanbanQuantity);
                            } else if (stockOfGoodsDto.getBoxType().contains("822")) {
                                NumOfTypeOf822 = NumOfTypeOf822.add(BigDecimal.ONE);
                                NumOfPcOf822 = NumOfPcOf822.add(needKanbanQuantity.multiply(stockOfGoodsDto.getNumOfPerKanban()));
                                NumOfBoxOf822 = NumOfBoxOf822.add(needKanbanQuantity);
                            }
                        }
                    }
                }
                // 设定Vo实体
                clcKanbanVo.setTotalNumOfType(TotalNumOfType);
                clcKanbanVo.setTotalNumOfPc(TotalNumOfPc);
                clcKanbanVo.setTotalNumOfBox(TotalNumOfBox);
                clcKanbanVo.setNumOfBoxOf811(NumOfBoxOf811);
                clcKanbanVo.setNumOfBoxOf810(NumOfBoxOf810);
                clcKanbanVo.setNumOfBoxOf911(NumOfBoxOf911);
                clcKanbanVo.setNumOfBoxOf822(NumOfBoxOf822);
                clcKanbanVo.setNumOfPcOf811(NumOfPcOf811);
                clcKanbanVo.setNumOfPcOf810(NumOfPcOf810);
                clcKanbanVo.setNumOfPcOf911(NumOfPcOf911);
                clcKanbanVo.setNumOfPcOf822(NumOfPcOf822);
                clcKanbanVo.setNumOfTypeOf811(NumOfTypeOf811);
                clcKanbanVo.setNumOfTypeOf810(NumOfTypeOf810);
                clcKanbanVo.setNumOfTypeOf911(NumOfTypeOf911);
                clcKanbanVo.setNumOfTypeOf822(NumOfTypeOf822);
            }

            logger.info("获取CLC看板需求成功。");
            response.setCode(ResponseCode.OK.getCode());
            response.setMessage("获取CLC看板需求成功。");
            response.setReturnData(clcKanbanVo);
            return convertJsonString(response);
        } catch (Exception e) {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("获取CLC看板需求发生异常：{}", convertJsonString(e));
            response.setCode(ResponseCode.ERROR.getCode());
            response.setMessage("获取CLC看板需求发生异常");
            return convertJsonString(response);
        }
    }

    /**
     * 生成CLC看板需求
     */
    @PostMapping("/genClcKanbanRequirement")
    @ResponseBody
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    @MyLog(logTitle = "生成CLC看板需求", logMethod = "genClcKanbanRequirement")
    public String genClcKanbanRequirement(@RequestBody KanbanRequest request) {
        logger.info("生成CLC看板需求：{}，请求ip：{}", convertJsonString(request), HttpUtils.getIpAddr(servletRequest));
        ResponseEntity response = new ResponseEntity();
        try {
            // 查询所有pull的物料
            List<Goods> pullGoodsList = goodsService.list(new LambdaQueryWrapper<Goods>()
                    .eq(Goods::getFeedingType, "PULL"));
            if (pullGoodsList == null || pullGoodsList.isEmpty()) {
                logger.error("没有PULL的物料信息。");
                response.setCode(ResponseCode.ERROR.getCode());
                response.setMessage("没有PULL的物料信息。");
                return convertJsonString(response);
            }
            // 查询所有的库存信息
            List<StockOfGoodsDto> stockOfGoodsDtoList = stockService.selectSumOfGoods("");
            // 将库存信息转换为Map
            Map<String, StockOfGoodsDto> stockOfGoodsDtoMap = stockOfGoodsDtoList.stream().collect(Collectors.toMap(StockOfGoodsDto::getGoodsId, stockOfGoodsDto -> stockOfGoodsDto));
            List<Kanban> dealKanbanList = new ArrayList<>();
            for (Goods pullGoods : pullGoodsList) {
                if (pullGoods.getKanbanList() == null || pullGoods.getKanbanList().isEmpty()) {
                    // 没有看板数据，不需要生成看板需求
                    continue;
                }
                // 目标数量
                BigDecimal targetNum = pullGoods.getKanbanNum().multiply(pullGoods.getQuantityPerKanban());
                BigDecimal remainNum = BigDecimal.ZERO;
                // 判断是否包含请求物料
                if (stockOfGoodsDtoMap.containsKey(pullGoods.getGoodsId())) {
                    // 筛选出当前库存
                    StockOfGoodsDto stockOfGoodsDto = stockOfGoodsDtoMap.get(pullGoods.getGoodsId());
                    remainNum = stockOfGoodsDto.getRemainNumSum();
                }
                // 计算需要多少个看板
                BigDecimal needKanbanQuantity = targetNum.subtract(remainNum).divide(pullGoods.getQuantityPerKanban(), 0, RoundingMode.FLOOR);
                // 看板表中当前物料的所有看板
                List<Kanban> kanbanList = kanbanService.list(new LambdaQueryWrapper<Kanban>()
                        .eq(Kanban::getGoodsId, pullGoods.getGoodsId())
                        .orderByAsc(Kanban::getKanbanStatus)
                        .orderByAsc(Kanban::getLastPullTime));
                List<Kanban> emptyKanbanList = kanbanList.stream().filter(kanban -> kanban.getKanbanStatus() == 0).toList();
                // 扣除之前就有的空看板
                needKanbanQuantity = needKanbanQuantity.subtract(BigDecimal.valueOf(emptyKanbanList.size()));
                // 之前的满看板
                List<Kanban> fullKanbanList = kanbanList.stream().filter(kanban -> kanban.getKanbanStatus() == 1).toList();
                for (Kanban kanban : fullKanbanList) {
                    if (needKanbanQuantity.compareTo(BigDecimal.ZERO) <= 0) {
                        break;
                    }
                    kanban.setKanbanStatus(0);
                    kanban.setLastRequestTime(LocalDateTime.now());
                    kanban.setLastRequestUser(request.getUserName());
                    // 添加更新列表
                    dealKanbanList.add(kanban);
                    // 更新需求看板的数量
                    needKanbanQuantity = needKanbanQuantity.subtract(BigDecimal.ONE);
                }
            }
            // 更新看板表
            kanbanService.updateBatchById(dealKanbanList);

            logger.info("生成CLC看板需求成功。");
            response.setCode(ResponseCode.OK.getCode());
            response.setMessage("生成CLC看板需求成功。");
            return convertJsonString(response);
        } catch (Exception e) {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("生成CLC看板需求发生异常：{}", convertJsonString(e));
            response.setCode(ResponseCode.ERROR.getCode());
            response.setMessage("生成CLC看板需求发生异常");
            return convertJsonString(response);
        }
    }

    /**
     * 查询所有看板信息
     */
    @PostMapping("/getClcKanbanByPage")
    @ResponseBody
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    @MyLog(logTitle = "查询所有看板信息", logMethod = "getClcKanbanByPage")
    public String getClcKanbanByPage(@RequestBody KanbanRequest request) {
        logger.info("接收到查询所有看板信息请求：{}，请求ip：{}", convertJsonString(request), HttpUtils.getIpAddr(servletRequest));
        ResponseEntity response = new ResponseEntity();
        try {
            Page<Kanban> page = request.toMpPage();
            LambdaQueryWrapper<Kanban> queryWrapper = new LambdaQueryWrapper<Kanban>()
                    .like(StringUtils.isNotEmpty(request.getGoodsId()), Kanban::getGoodsId, request.getGoodsId())
                    .eq(request.getKanbanStatus() != null, Kanban::getKanbanStatus, request.getKanbanStatus());
            if (request.getLastPullTime() != null) {
                // 设置收货
                queryWrapper.likeRight(Kanban::getLastPullTime, request.getLastPullTime().toString().substring(0, 10));
            }
            Page<Kanban> kanbanPage = kanbanService.page(page, queryWrapper);
            PageDto<KanbanVo> pageDto = PageDto.of(kanbanPage, kanban -> BeanUtil.copyProperties(kanban, KanbanVo.class));
            logger.info("查询所有看板信息成功。");
            response.setCode(ResponseCode.OK.getCode());
            response.setMessage("查询所有看板信息成功。");
            response.setReturnData(pageDto);
            return convertJsonString(response);
        } catch (Exception e) {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("查询所有看板信息发生异常：{}", convertJsonString(e));
            response.setCode(ResponseCode.ERROR.getCode());
            response.setMessage("查询所有看板信息发生异常。");
            return convertJsonString(response);
        }
    }

    /**
     * 查询工作流
     */
    @PostMapping("/getWorkFlows")
    @ResponseBody
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    @MyLog(logTitle = "查询工作流", logMethod = "getWorkFlows")
    public String getWorkFlows(@RequestBody WorkFlowQuery workFlowQuery) {
        logger.info("接收到查询工作流请求：{}，请求ip：{}", convertJsonString(workFlowQuery), HttpUtils.getIpAddr(servletRequest));
        ResponseEntity response = new ResponseEntity();
        try {
            Page<WorkFlow> page = workFlowQuery.toMpPage();
            Page<WorkFlow> workFlowsPage = workFlowService.page(page, new LambdaQueryWrapper<WorkFlow>()
                    .eq(workFlowQuery.getLightStatus() != null, WorkFlow::getLightStatus, workFlowQuery.getLightStatus())
                    .eq(workFlowQuery.getWorkStatus() != null, WorkFlow::getWorkStatus, workFlowQuery.getWorkStatus())
                    .like(StringUtils.isNotEmpty(workFlowQuery.getWorkStation()), WorkFlow::getWorkStation, workFlowQuery.getWorkStation())
                    .like(StringUtils.isNotEmpty(workFlowQuery.getWorkOrder()), WorkFlow::getWorkOrder, workFlowQuery.getWorkOrder())
                    .like(StringUtils.isNotEmpty(workFlowQuery.getWorkCenter()), WorkFlow::getWorkCenter, workFlowQuery.getWorkCenter())
                    .like(StringUtils.isNotEmpty(workFlowQuery.getGoodsId()), WorkFlow::getGoodsId, workFlowQuery.getGoodsId()));
            PageDto<WorkFlowVo> pageDto = PageDto.of(workFlowsPage, workFlow -> BeanUtil.copyProperties(workFlow, WorkFlowVo.class));
            logger.info("查询工作流成功。");
            response.setCode(ResponseCode.OK.getCode());
            response.setMessage("查询工作流成功。");
            response.setReturnData(pageDto);
            return convertJsonString(response);
        } catch (Exception e) {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("查询工作流发生异常：{}", convertJsonString(e));
            response.setCode(ResponseCode.ERROR.getCode());
            response.setMessage("查询工作流发生异常");
            return convertJsonString(response);
        }
    }

    /**
     * 更新工作流信息
     *
     * @param workFlowQuery 请求参数
     * @return 结果
     */
    @PostMapping("/updateWorkFlows")
    @ResponseBody
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    @MyLog(logTitle = "更新工作流", logMethod = "updateWorkFlows")
    public String updateWorkFlows(@RequestBody WorkFlowQuery workFlowQuery) {
        logger.info("接收到更新工作流请求：{}，请求ip：{}", convertJsonString(workFlowQuery), HttpUtils.getIpAddr(servletRequest));
        // 创建响应信息
        ResponseEntity rsp = new ResponseEntity();
        try {
            if (StringUtils.isEmpty(workFlowQuery.getWorkFlowId())) {// id为空，不允许执行
                logger.error("请求的id为空，不允许修改。");
                rsp.setCode(ResponseCode.ERROR.getCode());
                rsp.setMessage("请求的id为空，不允许修改。");
                return convertJsonString(rsp);
            }
            if (workFlowService.update(workFlowQuery.toWorkFlowPo(), new LambdaQueryWrapper<WorkFlow>().eq(WorkFlow::getWorkFlowId, workFlowQuery.getWorkFlowId()))) {
                // 返回成功
                logger.info("更新工作流信息成功。");
                rsp.setCode(ResponseCode.OK.getCode());
                rsp.setMessage("更新工作流信息成功。");
            } else {
                // 返回失败
                logger.error("更新工作流信息失败。");
                rsp.setCode(ResponseCode.ERROR.getCode());
                rsp.setMessage("更新工作流信息失败。");
            }
            return convertJsonString(rsp);
        } catch (Exception e) {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.info("更新工作流信息发生异常：{}", convertJsonString(e));
            // 返回其他异常
            rsp.setCode(ResponseCode.ERROR.getCode());
            rsp.setMessage("更新工作流信息发生异常");
            return convertJsonString(rsp);
        }
    }

    /**
     * 查询工作总结
     */
    @PostMapping("/getWorkSummary")
    @ResponseBody
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    @MyLog(logTitle = "查询工作总结", logMethod = "getWorkSummary")
    public String getWorkSummary(@RequestBody WorkSummaryQuery workSummaryQuery) {
        logger.info("接收到查询工作总结请求：{}，请求ip：{}", convertJsonString(workSummaryQuery), HttpUtils.getIpAddr(servletRequest));
        ResponseEntity response = new ResponseEntity();
        try {
            Page<WorkSummary> page = workSummaryQuery.toMpPage();
            Page<WorkSummary> workSummaryPage = workSummaryService.page(page, new LambdaQueryWrapper<WorkSummary>()
                    .eq(workSummaryQuery.getLackStatus() != null, WorkSummary::getLackStatus, workSummaryQuery.getLackStatus())
                    .eq(workSummaryQuery.getWorkDate() != null, WorkSummary::getWorkDate, workSummaryQuery.getWorkDate())
                    .like(StringUtils.isNotEmpty(workSummaryQuery.getWorkStation()), WorkSummary::getWorkStation, workSummaryQuery.getWorkStation())
                    .like(StringUtils.isNotEmpty(workSummaryQuery.getWorkOrder()), WorkSummary::getWorkOrder, workSummaryQuery.getWorkOrder())
                    .like(StringUtils.isNotEmpty(workSummaryQuery.getWorkCenter()), WorkSummary::getWorkCenter, workSummaryQuery.getWorkCenter())
                    .like(StringUtils.isNotEmpty(workSummaryQuery.getGoodsId()), WorkSummary::getGoodsId, workSummaryQuery.getGoodsId()));
            PageDto<WorkSummaryVo> pageDto = PageDto.of(workSummaryPage, workSummary -> BeanUtil.copyProperties(workSummary, WorkSummaryVo.class));
            logger.info("查询工作总结成功。");
            response.setCode(ResponseCode.OK.getCode());
            response.setMessage("查询工作总结成功。");
            response.setReturnData(pageDto);
            return convertJsonString(response);
        } catch (Exception e) {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("查询工作总结发生异常：{}", convertJsonString(e));
            response.setCode(ResponseCode.ERROR.getCode());
            response.setMessage("查询工作总结发生异常");
            return convertJsonString(response);
        }
    }

    /**
     * 查询整理大盒子列表
     */
    @PostMapping("/getBigBoxList")
    @ResponseBody
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    @MyLog(logTitle = "查询整理大盒子列表", logMethod = "getBigBoxList")
    public String getBigBoxList(@RequestBody BigBoxQuery bigBoxQuery) {
        logger.info("接收到查询整理大盒子列表请求：{}，请求ip：{}", convertJsonString(bigBoxQuery), HttpUtils.getIpAddr(servletRequest));
        ResponseEntity response = new ResponseEntity();
        try {
            // 获取站台号
            String standId = "";
            if (StringUtils.isNotEmpty(bigBoxQuery.getStandId())) {
                // 站台号从请求参数中获取
                standId = bigBoxQuery.getStandId();
            } else {
                // 站台号从ip获取
                Stand standOfIp = standService.getOne(new LambdaQueryWrapper<Stand>()
                        .eq(Stand::getStandIp, HttpUtils.getIpAddr(servletRequest))
                        .eq(Stand::getStandType, 2)
                        .last("limit 1"));
                if (standOfIp != null && StringUtils.isNotEmpty(standOfIp.getStandId())) {
                    standId = standOfIp.getStandId();
                }
            }
            if (StringUtils.isEmpty(standId)) {
                logger.error("请求参数缺少站台号。");
                response.setCode(ResponseCode.ERROR.getCode());
                response.setMessage("请求参数缺少站台号。");
                return convertJsonString(response);
            }
            // 返回结果
            Map<String, BigBoxVo> bigBoxVoMap = new HashMap<>();
            // 查询到当前站台所有的大盒子
            List<WorkStationConfig> stationConfigs = workStationConfigService.list(new LambdaQueryWrapper<WorkStationConfig>()
                    .eq(WorkStationConfig::getWorkStation, standId));
            for (WorkStationConfig currentBigBoxConfig : stationConfigs) {
                // 当前配置的工单数/大盒子
                int orderQuantity = currentBigBoxConfig.getOrderQuantity();
                // 查询这个大盒子对应的小盒子
                List<String> smallBoxListOfAll = stationConfigs.stream().map(WorkStationConfig::getSmallBox).distinct().toList();
                // 找出本次工作中的标签位
                List<ELocationConfigLast> eConfigLastList = eLocationConfigLastService.list(new LambdaQueryWrapper<ELocationConfigLast>()
                        .eq(ELocationConfigLast::getWorkStation, standId)
                        .in(ELocationConfigLast::getWorkCenter, smallBoxListOfAll));
                if (eConfigLastList.isEmpty()) {
                    continue;
                }
                // 设置返回结果
                int boxQuantity = 0;
                if (orderQuantity <= 0) {
                    boxQuantity = 1;
                } else {
                    // 根据这些小盒子号找到对应的工单
                    List<String> orderIds = eConfigLastList.stream().map(ELocationConfigLast::getWorkOrder).distinct().toList();
                    boxQuantity = boxQuantity + (orderIds.size() / orderQuantity);
                }
                // 键
                String key = currentBigBoxConfig.getWorkStation() + "_" + currentBigBoxConfig.getBigBox();
                if (bigBoxVoMap.containsKey(key)) {
                    BigBoxVo bigBoxVo = bigBoxVoMap.get(key);
                    bigBoxVo.setBoxQuantity(bigBoxVo.getBoxQuantity() + boxQuantity);
                    bigBoxVoMap.replace(key, bigBoxVo);
                } else {
                    BigBoxVo bigBoxVo = new BigBoxVo();
                    bigBoxVo.setStandId(standId);
                    bigBoxVo.setBigBoxNo(currentBigBoxConfig.getBigBox());
                    bigBoxVo.setBoxQuantity(boxQuantity);
                    bigBoxVoMap.put(key, bigBoxVo);
                }
            }

            response.setCode(ResponseCode.OK.getCode());
            response.setMessage("查询整理大盒子列表成功。");
            response.setReturnData(bigBoxVoMap.values());
            return convertJsonString(response);
        } catch (Exception e) {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("查询整理大盒子列表发生异常：{}", convertJsonString(e));
            response.setCode(ResponseCode.ERROR.getCode());
            response.setMessage("查询整理大盒子列表发生异常");
            return convertJsonString(response);
        }
    }
}