package com.wms.service.business.serviceImplements;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wms.constants.enums.ConfigMapKeyEnum;
import com.wms.entity.app.dto.WorkCenterAndOrderDto;
import com.wms.entity.table.*;
import com.wms.service.*;
import com.wms.service.business.IWmsTaskService;
import com.wms.service.business.IWorkService;
import com.wms.utils.StringUtils;
import com.wms.utils.WmsUtils;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
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 java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.wms.config.InitLocalConfig.*;
import static com.wms.constants.WmsConstants.MYSQL_JSON_CI;
import static com.wms.utils.StringUtils.convertJsonString;

/**
 * 工作服务接口的实现
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class WorkServiceImplements implements IWorkService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final WorkStationConfigService workStationConfigService;// 工作站配置服务
    private final WorkFlowService workFlowService;// 工作流服务
    private final KateDBSService kateDBSService;// DBS服务
    private final KateOrdersService kateOrdersService;// 工单服务
    private final ETagLocationService eTagLocationService;// 电子标签服务
    private final ELocationConfigService eLocationConfigService;// 电子标签配置服务
    private final GoodsToStationService goodsToStationService;// 站台要料服务
    private final WorkSummaryService workSummaryService;// 工作总结服务
    private final ELocationConfigLastService eLocationConfigLastService;// 上一次标签配置的服务
    private final StockService stockService;// 库存服务
    private final IWmsTaskService wmsTaskService;// 任务服务
    private final PickTaskService pickTaskService;// 拣选任务服务
    private final List<String> workCreatingStations = new ArrayList<>();// 当前正在创建任务的站台
    private final List<String> workDoingStations = new ArrayList<>();// 当前正在执行任务的站台
    private final List<String> workFinishingStations = new ArrayList<>();// 当前正在完成任务的站台

//    /**
//     * 新版创建工作
//     * @param workStation 工作站台
//     * @throws Exception 异常
//     */
//    @Override
//    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
//    public void createWork(String workStation) throws Exception {
//        if (workCreatingStations.contains(workStation)) {
//            // 当前站台正在创建任务
//            return;
//        } else {
//            // 添加站台
//            workCreatingStations.add(workStation);
//        }
//        if (StringUtils.isEmpty(workStation)) {
//            // 站台号为空
//            return;
//        }
//        try {
//            // 先判断当日是否是工作日
//            if (!localWorkDateList.contains(LocalDate.now())) {
//                return;
//            }
//            // 先查看当前站台已经生成的工作流是否为空
//            List<WorkFlow> currentWorkFlowList = workFlowService.list(new LambdaQueryWrapper<WorkFlow>()
//                    .eq(WorkFlow::getWorkStation, workStation));
//            // 当前站台的工作流中还存在其他任务
//            if (currentWorkFlowList != null && !currentWorkFlowList.isEmpty()) {
//                return;
//            }
//            // 当前站台分配的工位
//            List<WorkFlow> currentStationWorkFlows = new ArrayList<>();
//            // 先找MWL机型
//            findWorks(workStation, currentStationWorkFlows, "MWL");
//            if (currentStationWorkFlows.isEmpty()) {
//                // 找非MWL机型
//                findWorks(workStation, currentStationWorkFlows, "NOT_MWL");
//            }
//            // 如果当前站台有任务
//            if (!currentStationWorkFlows.isEmpty()) {
//                // 将工作流列表添加进数据库
//                workFlowService.saveBatch(currentStationWorkFlows);
//                // 获得工单列表
//                List<String> workOrderList = new ArrayList<>();
//                // 获得工单以及小工位列表
//                List<String> boxNoList = new ArrayList<>();
//                // 要料Map
//                Map<String, BigDecimal> needGoodsMap = new HashMap<>();
//                for (WorkFlow tempWorkflow : currentStationWorkFlows) {
//                    // 添加工单
//                    if (!workOrderList.contains(tempWorkflow.getWorkOrder())) {
//                        workOrderList.add(tempWorkflow.getWorkOrder());
//                    }
//                    // 添加盒子配置
//                    String boxNo = tempWorkflow.getWorkOrder() + "@" + tempWorkflow.getWorkCenter();
//                    if (!boxNoList.contains(boxNo)) {
//                        boxNoList.add(boxNo);
//                    }
//                    // 添加要料信息
//                    if (!needGoodsMap.containsKey(tempWorkflow.getGoodsId())) {
//                        // 添加物料信息
//                        needGoodsMap.put(tempWorkflow.getGoodsId(), tempWorkflow.getNeedNum());
//                    } else {
//                        // 增加需求数量
//                        needGoodsMap.replace(tempWorkflow.getGoodsId(), needGoodsMap.get(tempWorkflow.getGoodsId()).add(tempWorkflow.getNeedNum()));
//                    }
//                }
//                // 站台要料
//                List<GoodsToStation> goodsToStationList = new ArrayList<>();
//                for (String goodsId : needGoodsMap.keySet()) {
//                    GoodsToStation goodsToStation = new GoodsToStation();
//                    goodsToStation.setGoodsId(goodsId);
//                    goodsToStation.setWorkStation(workStation);
//                    goodsToStation.setDistributeStatus(0);
//                    goodsToStation.setDistributedNum(BigDecimal.ZERO);
//                    goodsToStation.setTotalNum(needGoodsMap.get(goodsId));
//                    goodsToStationList.add(goodsToStation);
//                }
//                // 将站台要料列表存进数据库
//                goodsToStationService.saveBatch(goodsToStationList);
//                // 更新工单表
//                List<String> orderIds = currentStationWorkFlows.stream().map(WorkFlow::getOrderId).distinct().toList();
//                if (!orderIds.isEmpty()) {
//                    kateOrdersService.update(new LambdaUpdateWrapper<KateOrders>()
//                            .set(KateOrders::getOrderStatus, 1)
//                            .in(KateOrders::getOrderId, orderIds)
//                            .eq(KateOrders::getOrderStatus, 0));
//                }
//                // 更新dbs表
//                if (!workOrderList.isEmpty()) {
//                    kateDBSService.update(new LambdaUpdateWrapper<KateDBS>()
//                            .set(KateDBS::getDbsStatus, 1)
//                            .in(KateDBS::getWorkOrder, workOrderList)
//                            .eq(KateDBS::getDbsStatus, 0));
//                }
//                // 电子标签库位配置
//                List<ELocationConfig> eLocationConfigList = new ArrayList<>();
//                // 查找到当前站台所有可用的电子标签
//                List<ETagLocation> eTagLocationList = eTagLocationService.list(new LambdaQueryWrapper<ETagLocation>()
//                        .eq(ETagLocation::getWorkStation, workStation)
//                        .eq(ETagLocation::getELocationStatus, 0)
//                        .orderByAsc(ETagLocation::getSequenceId));
//                if (eTagLocationList.isEmpty() || eTagLocationList.size() < boxNoList.size()) {
//                    throw new Exception("站台：" + workStation + "没有足够可用的电子标签位!");
//                }
//                for (ETagLocation eTagLocation : eTagLocationList) {
//                    if (!boxNoList.isEmpty()) {
//                        String tempBoxNo = boxNoList.get(0);
//                        ELocationConfig eLocationConfig = new ELocationConfig();
//                        eLocationConfig.setWorkOrder(tempBoxNo.split("@")[0]);
//                        eLocationConfig.setWorkCenter(tempBoxNo.split("@")[1]);
//                        eLocationConfig.setWorkStation(workStation);
//                        eLocationConfig.setELocationId(eTagLocation.getELocationId());
//                        eLocationConfig.setOrderBoxNo(tempBoxNo);
//                        // 添加配置
//                        eLocationConfigList.add(eLocationConfig);
//                        // 移除已经分配的盒子
//                        boxNoList.remove(tempBoxNo);
//                    }
//                }
//                // 将电子标签库位配置存进数据库
//                eLocationConfigService.saveBatch(eLocationConfigList);
//            }
//        } catch (Exception e) {
//            logger.error("创建站台：{}工作发生异常：{}", workStation, convertJsonString(e));
//            // 回滚事务
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//        } finally {
//            // 当前站台创建任务完成
//            workCreatingStations.remove(workStation);
//        }
//    }

    @Override
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    public void createWork(String workStation) throws Exception {
        if (workCreatingStations.contains(workStation)) {
            // 当前站台正在创建任务
            return;
        } else {
            // 添加站台
            workCreatingStations.add(workStation);
        }
        if (StringUtils.isEmpty(workStation)) {
            // 站台号为空
            return;
        }
        try {
            // 先查看当前站台已经生成的工作流是否为空
            List<WorkFlow> currentWorkFlowList = workFlowService.list(new LambdaQueryWrapper<WorkFlow>()
                    .eq(WorkFlow::getWorkStation, workStation)
                    .ne(WorkFlow::getWorkStatus, 0));
            // 当前站台的工作流中还存在其他任务
            if (currentWorkFlowList != null && !currentWorkFlowList.isEmpty()) {
                return;
            }
            // 查询是否有已经分配好的电子标签库位信息
            List<ELocationConfig> oldELocationConfigList = eLocationConfigService.list(new LambdaQueryWrapper<ELocationConfig>()
                    .eq(ELocationConfig::getWorkStation, workStation));
            if (oldELocationConfigList != null && !oldELocationConfigList.isEmpty()) {
                return;
            }
            // 查询所有待下发的
            List<WorkFlow> currentStationWorkFlows = workFlowService.list(new LambdaQueryWrapper<WorkFlow>()
                    .eq(WorkFlow::getWorkStatus, 0)
                    .eq(WorkFlow::getWorkStation, workStation));
            // 如果当前站台有任务
            if (!currentStationWorkFlows.isEmpty()) {
                // 获得工单以及小工位列表
                List<String> boxNoList = new ArrayList<>();
                // 要料Map
                Map<String, BigDecimal> needGoodsMap = new HashMap<>();
                for (WorkFlow tempWorkflow : currentStationWorkFlows) {
                    // 添加盒子配置
                    String boxNo = tempWorkflow.getWorkOrder() + "@" + tempWorkflow.getWorkCenter();
                    if (!boxNoList.contains(boxNo)) {
                        boxNoList.add(boxNo);
                    }
                    // 添加要料信息
                    if (!needGoodsMap.containsKey(tempWorkflow.getGoodsId())) {
                        // 添加物料信息
                        needGoodsMap.put(tempWorkflow.getGoodsId(), tempWorkflow.getNeedNum());
                    } else {
                        // 增加需求数量
                        needGoodsMap.replace(tempWorkflow.getGoodsId(), needGoodsMap.get(tempWorkflow.getGoodsId()).add(tempWorkflow.getNeedNum()));
                    }
                }
                // 站台要料
                List<GoodsToStation> goodsToStationList = new ArrayList<>();
                for (String goodsId : needGoodsMap.keySet()) {
                    GoodsToStation goodsToStation = new GoodsToStation();
                    goodsToStation.setConfigId(goodsId + "_" + workStation);
                    goodsToStation.setGoodsId(goodsId);
                    goodsToStation.setWorkStation(workStation);
                    goodsToStation.setDistributeStatus(0);
                    goodsToStation.setDistributedNum(BigDecimal.ZERO);
                    goodsToStation.setTotalNum(needGoodsMap.get(goodsId));
                    goodsToStationList.add(goodsToStation);
                }
                // 将站台要料列表存进数据库
                goodsToStationService.saveOrUpdateBatch(goodsToStationList);
                // 电子标签库位配置
                List<ELocationConfig> eLocationConfigList = new ArrayList<>();
                // 查找到当前站台所有可用的电子标签
                List<ETagLocation> eTagLocationList = eTagLocationService.list(new LambdaQueryWrapper<ETagLocation>()
                        .eq(ETagLocation::getWorkStation, workStation)
                        .eq(ETagLocation::getELocationStatus, 0)
                        .orderByAsc(ETagLocation::getSequenceId));
                if (eTagLocationList.isEmpty() || eTagLocationList.size() < boxNoList.size()) {
                    throw new Exception("站台：" + workStation + "没有足够可用的电子标签位!");
                }
                for (ETagLocation eTagLocation : eTagLocationList) {
                    if (!boxNoList.isEmpty()) {
                        String tempBoxNo = boxNoList.get(0);
                        ELocationConfig eLocationConfig = new ELocationConfig();
                        eLocationConfig.setWorkOrder(tempBoxNo.split("@")[0]);
                        eLocationConfig.setWorkCenter(tempBoxNo.split("@")[1]);
                        eLocationConfig.setWorkStation(workStation);
                        eLocationConfig.setELocationId(eTagLocation.getELocationId());
                        eLocationConfig.setOrderBoxNo(tempBoxNo);
                        // 添加配置
                        eLocationConfigList.add(eLocationConfig);
                        // 移除已经分配的盒子
                        boxNoList.remove(tempBoxNo);
                    }
                }
                // 将电子标签库位配置存进数据库
                eLocationConfigService.saveBatch(eLocationConfigList);
                // 更新工作流状态
                List<String> workFlowIds = currentStationWorkFlows.stream().map(WorkFlow::getWorkFlowId).distinct().toList();
                workFlowService.update(new LambdaUpdateWrapper<WorkFlow>()
                        .set(WorkFlow::getWorkStatus, 1)
                        .in(WorkFlow::getWorkFlowId, workFlowIds)
                        .eq(WorkFlow::getWorkStatus, 0));
            }
        } catch (Exception e) {
            logger.error("创建站台：{}工作发生异常：{}", workStation, convertJsonString(e));
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            // 当前站台创建任务完成
            workCreatingStations.remove(workStation);
        }
    }

//    /**
//     * 新版开始工作
//     * @param workStation 工作站台
//     * @throws Exception 异常
//     */
//    @Override
//    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
//    public void doWork(String workStation) throws Exception {
//        if (workDoingStations.contains(workStation)) {
//            // 当前站台正在创建任务
//            return;
//        } else {
//            // 添加站台
//            workDoingStations.add(workStation);
//        }
//        try {
//            // 查找当前站台未开始的工作流
//            List<WorkFlow> currentWorkFlowList = workFlowService.list(new LambdaQueryWrapper<WorkFlow>()
//                    .eq(WorkFlow::getWorkStation, workStation)
//                    .ne(WorkFlow::getWorkStatus, 2));
//            // 没有可做的任务
//            if (currentWorkFlowList == null || currentWorkFlowList.isEmpty()) {
//                return;
//            }
//            // 查站台要料表---未分配以及分配但未完全分配
//            List<GoodsToStation> goodsToStationList = goodsToStationService.list(new LambdaQueryWrapper<GoodsToStation>()
//                    .eq(GoodsToStation::getWorkStation, workStation));
//            List<GoodsToStation> notFinishedGoodsList = goodsToStationList.stream().filter(goodsToStation -> goodsToStation.getDistributeStatus() < 2).toList();
//            if (notFinishedGoodsList.isEmpty()) {
//                // 查询是否还有这个站台的拣选任务
//                if (!pickTaskService.exists(new LambdaQueryWrapper<PickTask>()
//                        .eq(PickTask::getStandId, workStation))) {
//                    // 需要重新分配的goodsToStationsList
//                    Map<String, GoodsToStation> needDistributeGoodsMap = new HashMap<>();
//                    // 需要完成的工作流
//                    List<WorkFlow> needFinishWorkFlowList = new ArrayList<>();
//                    // 所有缺料的分配
//                    List<String> lackGoodsIdList = goodsToStationList.stream().filter(goodsToStation -> goodsToStation.getDistributeStatus() == 3).map(GoodsToStation::getGoodsId).distinct().toList();
//                    // 不缺料的分配
//                    Map<String, GoodsToStation> noLackGoodsMap = goodsToStationList.stream().filter(goodsToStation -> goodsToStation.getDistributeStatus() == 2).collect(Collectors.toMap(GoodsToStation::getGoodsId, goodsToStation -> goodsToStation));
//                    // 查询当前工作流中所有缺料的数据行
//                    for (WorkFlow notFinishedWorkFlow : currentWorkFlowList) {
//                        if (notFinishedWorkFlow.getPickedNum().compareTo(notFinishedWorkFlow.getNeedNum()) < 0) {
//                            // 缺料时，判断是否当前物料在缺料列表中
//                            if (lackGoodsIdList.contains(notFinishedWorkFlow.getGoodsId())) {
//                                // 缺料，添加到需要分配的列表中
//                                notFinishedWorkFlow.setWorkStatus(2);
//                                notFinishedWorkFlow.setFinishTime(LocalDateTime.now());
//                                notFinishedWorkFlow.setOpUser("系统自动完成");
//                                needFinishWorkFlowList.add(notFinishedWorkFlow);
//                            } else {
//                                BigDecimal needNum = notFinishedWorkFlow.getNeedNum().subtract(notFinishedWorkFlow.getPickedNum());
//                                if (needDistributeGoodsMap.containsKey(notFinishedWorkFlow.getGoodsId())) {
//                                    // 减少分配数量
//                                    GoodsToStation oldGoodsToStation = needDistributeGoodsMap.get(notFinishedWorkFlow.getGoodsId());
//                                    oldGoodsToStation.setDistributedNum(oldGoodsToStation.getDistributedNum().subtract(needNum));
//                                    oldGoodsToStation.setDistributeStatus(1);
//                                    needDistributeGoodsMap.replace(notFinishedWorkFlow.getGoodsId(), oldGoodsToStation);
//                                } else {
//                                    if (noLackGoodsMap.containsKey(notFinishedWorkFlow.getGoodsId())) {
//                                        GoodsToStation newGoodsToStation = noLackGoodsMap.get(notFinishedWorkFlow.getGoodsId());
//                                        newGoodsToStation.setDistributedNum(newGoodsToStation.getDistributedNum().subtract(needNum));
//                                        newGoodsToStation.setDistributeStatus(1);
//                                        needDistributeGoodsMap.put(notFinishedWorkFlow.getGoodsId(), newGoodsToStation);
//                                    } else {
//                                        GoodsToStation goodsToStation = new GoodsToStation();
//                                        goodsToStation.setConfigId(notFinishedWorkFlow.getGoodsId() + "_" + workStation);
//                                        goodsToStation.setGoodsId(notFinishedWorkFlow.getGoodsId());
//                                        goodsToStation.setWorkStation(workStation);
//                                        goodsToStation.setDistributeStatus(0);
//                                        goodsToStation.setDistributedNum(BigDecimal.ZERO);
//                                        goodsToStation.setTotalNum(needNum);
//                                        needDistributeGoodsMap.put(notFinishedWorkFlow.getGoodsId(), goodsToStation);
//                                    }
//                                }
//                            }
//                        } else {
//                            // 不缺料，直接完成
//                            notFinishedWorkFlow.setWorkStatus(2);
//                            notFinishedWorkFlow.setFinishTime(LocalDateTime.now());
//                            notFinishedWorkFlow.setOpUser("系统自动完成");
//                            needFinishWorkFlowList.add(notFinishedWorkFlow);
//                        }
//                    }
//                    // 保存重新分配的goodsToStationList
//                    goodsToStationService.saveOrUpdateBatch(needDistributeGoodsMap.values());
//                    // 保存需要完成的工作流
//                    workFlowService.updateBatchById(needFinishWorkFlowList);
//                }
//                return;
//            }
//            for (GoodsToStation goodsToStation : notFinishedGoodsList) {
//                // 当前物料当前站台需求数量
//                BigDecimal needNum = goodsToStation.getTotalNum().subtract(goodsToStation.getDistributedNum());
//                if (needNum.compareTo(BigDecimal.ZERO) == 0) {
//                    // 需求数量为0
//                    continue;
//                }
//                // 判断实际库存是否充足
//                List<Stock> stockList = stockService.list(new LambdaQueryWrapper<Stock>()
//                        .apply("goods_related ->> '$.goodsId' = {0}" + MYSQL_JSON_CI, goodsToStation.getGoodsId())
//                        .apply("goods_related ->> '$.remainNum' > 0"));
//                if (stockList == null || stockList.isEmpty()) {
//                    goodsToStation.setDistributeStatus(3);
//                    continue;
//                }
//                // 判断当前物料是否在流转中
//                needNum = wmsTaskService.callGoods(goodsToStation.getGoodsId(), needNum, workStation);
//                // 判断此时需求数量是否为0
//                if (needNum.compareTo(BigDecimal.ZERO) <= 0) {
//                    // 分配完成
//                    goodsToStation.setDistributeStatus(2);
//                } else {
//                    needNum = wmsTaskService.callStocks(goodsToStation.getGoodsId(), needNum, workStation);
//                    if (needNum.compareTo(BigDecimal.ZERO) > 0) {
//                        // 已分配但未完全分配
//                        goodsToStation.setDistributeStatus(1);
//                    } else {
//                        // 分配完成
//                        goodsToStation.setDistributeStatus(2);
//                    }
//                }
//                // 更新已分配数量
//                goodsToStation.setDistributedNum(goodsToStation.getTotalNum().subtract(needNum));
//            }
//            goodsToStationService.updateBatchById(notFinishedGoodsList);
//            // 更新工作流状态
//            List<String> workFlowIds = currentWorkFlowList.stream().map(WorkFlow::getWorkFlowId).distinct().toList();
//            List<String> orderIds = currentWorkFlowList.stream().map(WorkFlow::getOrderId).distinct().toList();
//            List<String> goodsIds = currentWorkFlowList.stream().map(WorkFlow::getGoodsId).distinct().toList();
//            List<String> smallBoxes = currentWorkFlowList.stream().map(WorkFlow::getWorkCenter).distinct().toList();
//            workFlowService.update(new LambdaUpdateWrapper<WorkFlow>()
//                    .set(WorkFlow::getWorkStatus, 1)
//                    .in(WorkFlow::getWorkFlowId, workFlowIds)
//                    .eq(WorkFlow::getWorkStatus, 0));
//            // 更新工单表状态
//            kateOrdersService.update(new LambdaUpdateWrapper<KateOrders>()
//                    .set(KateOrders::getOrderStatus, 2)
//                    .in(KateOrders::getOrderId, orderIds)
//                    .in(KateOrders::getGoodsId, goodsIds)
//                    .in(KateOrders::getSupplyArea, smallBoxes)
//                    .eq(KateOrders::getOrderStatus, 1));
//        } catch (Exception e) {
//            logger.error("执行站台：{}工作发生异常：{}", workStation, convertJsonString(e));
//            // 回滚事务
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//        } finally {
//            // 当前站台创建任务完成
//            workDoingStations.remove(workStation);
//        }
//    }

    @Override
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    public void doWork(String workStation) throws Exception {
        if (workDoingStations.contains(workStation)) {
            // 当前站台正在创建任务
            return;
        } else {
            // 添加站台
            workDoingStations.add(workStation);
        }
        try {
            // 查找当前站台未开始的工作流
            List<WorkFlow> currentWorkFlowList = workFlowService.list(new LambdaQueryWrapper<WorkFlow>()
                    .eq(WorkFlow::getWorkStation, workStation)
                    .eq(WorkFlow::getWorkStatus, 1));
            // 没有可做的任务
            if (currentWorkFlowList == null || currentWorkFlowList.isEmpty()) {
                return;
            }
            // 查站台要料表---未分配以及分配但未完全分配
            List<GoodsToStation> goodsToStationList = goodsToStationService.list(new LambdaQueryWrapper<GoodsToStation>()
                    .eq(GoodsToStation::getWorkStation, workStation));
            List<GoodsToStation> notFinishedGoodsList = goodsToStationList.stream().filter(goodsToStation -> goodsToStation.getDistributeStatus() < 2).toList();
            if (notFinishedGoodsList.isEmpty()) {
                // 查询是否还有这个站台的拣选任务
                if (!pickTaskService.exists(new LambdaQueryWrapper<PickTask>()
                        .eq(PickTask::getStandId, workStation))) {
                    // 需要重新分配的goodsToStationsList
                    Map<String, GoodsToStation> needDistributeGoodsMap = new HashMap<>();
                    // 需要完成的工作流
                    List<WorkFlow> needFinishWorkFlowList = new ArrayList<>();
                    // 所有缺料的分配
                    List<String> lackGoodsIdList = goodsToStationList.stream().filter(goodsToStation -> goodsToStation.getDistributeStatus() == 3).map(GoodsToStation::getGoodsId).distinct().toList();
                    // 不缺料的分配
                    Map<String, GoodsToStation> noLackGoodsMap = goodsToStationList.stream().filter(goodsToStation -> goodsToStation.getDistributeStatus() == 2).collect(Collectors.toMap(GoodsToStation::getGoodsId, goodsToStation -> goodsToStation));
                    // 查询当前工作流中所有缺料的数据行
                    for (WorkFlow notFinishedWorkFlow : currentWorkFlowList) {
                        if (notFinishedWorkFlow.getPickedNum().compareTo(notFinishedWorkFlow.getNeedNum()) < 0) {
                            // 缺料时，判断是否当前物料在缺料列表中
                            if (lackGoodsIdList.contains(notFinishedWorkFlow.getGoodsId())) {
                                // 缺料，添加到需要分配的列表中
                                notFinishedWorkFlow.setWorkStatus(2);
                                notFinishedWorkFlow.setFinishTime(LocalDateTime.now());
                                notFinishedWorkFlow.setOpUser("系统自动完成");
                                needFinishWorkFlowList.add(notFinishedWorkFlow);
                            } else {
                                BigDecimal needNum = notFinishedWorkFlow.getNeedNum().subtract(notFinishedWorkFlow.getPickedNum());
                                if (needDistributeGoodsMap.containsKey(notFinishedWorkFlow.getGoodsId())) {
                                    // 减少分配数量
                                    GoodsToStation oldGoodsToStation = needDistributeGoodsMap.get(notFinishedWorkFlow.getGoodsId());
                                    oldGoodsToStation.setDistributedNum(oldGoodsToStation.getDistributedNum().subtract(needNum));
                                    oldGoodsToStation.setDistributeStatus(1);
                                    needDistributeGoodsMap.replace(notFinishedWorkFlow.getGoodsId(), oldGoodsToStation);
                                } else {
                                    if (noLackGoodsMap.containsKey(notFinishedWorkFlow.getGoodsId())) {
                                        GoodsToStation newGoodsToStation = noLackGoodsMap.get(notFinishedWorkFlow.getGoodsId());
                                        newGoodsToStation.setDistributedNum(newGoodsToStation.getDistributedNum().subtract(needNum));
                                        newGoodsToStation.setDistributeStatus(1);
                                        needDistributeGoodsMap.put(notFinishedWorkFlow.getGoodsId(), newGoodsToStation);
                                    } else {
                                        GoodsToStation goodsToStation = new GoodsToStation();
                                        goodsToStation.setConfigId(notFinishedWorkFlow.getGoodsId() + "_" + workStation);
                                        goodsToStation.setGoodsId(notFinishedWorkFlow.getGoodsId());
                                        goodsToStation.setWorkStation(workStation);
                                        goodsToStation.setDistributeStatus(0);
                                        goodsToStation.setDistributedNum(BigDecimal.ZERO);
                                        goodsToStation.setTotalNum(needNum);
                                        needDistributeGoodsMap.put(notFinishedWorkFlow.getGoodsId(), goodsToStation);
                                    }
                                }
                            }
                        } else {
                            // 不缺料，直接完成
                            notFinishedWorkFlow.setWorkStatus(2);
                            notFinishedWorkFlow.setFinishTime(LocalDateTime.now());
                            notFinishedWorkFlow.setOpUser("系统自动完成");
                            needFinishWorkFlowList.add(notFinishedWorkFlow);
                        }
                    }
                    // 保存重新分配的goodsToStationList
                    goodsToStationService.saveOrUpdateBatch(needDistributeGoodsMap.values());
                    // 保存需要完成的工作流
                    workFlowService.updateBatchById(needFinishWorkFlowList);
                }
                return;
            }
            for (GoodsToStation goodsToStation : notFinishedGoodsList) {
                // 当前物料当前站台需求数量
                BigDecimal needNum = goodsToStation.getTotalNum().subtract(goodsToStation.getDistributedNum());
                if (needNum.compareTo(BigDecimal.ZERO) == 0) {
                    // 需求数量为0
                    continue;
                }
                // 判断实际库存是否充足
                List<Stock> stockList = stockService.list(new LambdaQueryWrapper<Stock>()
                        .apply("goods_related ->> '$.goodsId' = {0}" + MYSQL_JSON_CI, goodsToStation.getGoodsId())
                        .apply("goods_related ->> '$.remainNum' > 0"));
                if (stockList == null || stockList.isEmpty()) {
                    goodsToStation.setDistributeStatus(3);
                    continue;
                }
                // 判断当前物料是否在流转中
                needNum = wmsTaskService.callGoods(goodsToStation.getGoodsId(), needNum, workStation);
                // 判断此时需求数量是否为0
                if (needNum.compareTo(BigDecimal.ZERO) <= 0) {
                    // 分配完成
                    goodsToStation.setDistributeStatus(2);
                } else {
                    needNum = wmsTaskService.callStocks(goodsToStation.getGoodsId(), needNum, workStation);
                    if (needNum.compareTo(BigDecimal.ZERO) > 0) {
                        // 已分配但未完全分配
                        goodsToStation.setDistributeStatus(1);
                    } else {
                        // 分配完成
                        goodsToStation.setDistributeStatus(2);
                    }
                }
                // 更新已分配数量
                goodsToStation.setDistributedNum(goodsToStation.getTotalNum().subtract(needNum));
            }
            goodsToStationService.updateBatchById(notFinishedGoodsList);
        } catch (Exception e) {
            logger.error("执行站台：{}工作发生异常：{}", workStation, convertJsonString(e));
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            // 当前站台创建任务完成
            workDoingStations.remove(workStation);
        }
    }

//    /**
//     * 新版完成工作
//     * @param workStation 工作站台
//     * @return 结果
//     * @throws Exception 异常
//     */
//    @Override
//    public String finishWork(String workStation) throws Exception {
//        if (workFinishingStations.contains(workStation)) {
//            // 当前站台正在完成工作
//            return "当前站台正在完成工作，请勿重复操作";
//        } else {
//            // 添加站台
//            workFinishingStations.add(workStation);
//        }
//        try {
//            if (workFlowService.exists(new LambdaQueryWrapper<WorkFlow>()
//                    .eq(WorkFlow::getWorkStation, workStation)
//                    .ne(WorkFlow::getWorkStatus, 2))) {
//                // 当前站台工作未全部完成
//                return "工作未全部做完，不允许确认完成。";
//            }
//            if (eLocationConfigService.exists(new LambdaQueryWrapper<ELocationConfig>()
//                    .eq(ELocationConfig::getWorkStation, workStation)
//                    .eq(ELocationConfig::getPrintStatus, 0))) {
//                // 有标签未打印
//                return "有标签未打印";
//            }
//            if (!eLocationConfigService.exists(new LambdaQueryWrapper<ELocationConfig>()
//                    .eq(ELocationConfig::getWorkStation, workStation))) {
//                // 没有标签，说明点过确认。
//                return "没有可以确认完成的工作，请勿重复点击。";
//            }
//            // 查找当前站台的标签配置
//            List<ELocationConfig> eLocationConfigList = eLocationConfigService.list(new LambdaQueryWrapper<ELocationConfig>()
//                    .eq(ELocationConfig::getWorkStation, workStation));
//            // 保存一下记录
//            List<ELocationConfigLast> eLocationConfigLastList = ELocationConfig.toLocationsConfigLastList(eLocationConfigList);
//            // 先清空之前的
//            eLocationConfigLastService.remove(new LambdaQueryWrapper<ELocationConfigLast>()
//                    .eq(ELocationConfigLast::getWorkStation, workStation));
//            eLocationConfigLastService.saveBatch(eLocationConfigLastList);
//            // 删除所有的标签配置
//            eLocationConfigService.remove(new LambdaQueryWrapper<ELocationConfig>()
//                    .eq(ELocationConfig::getWorkStation, workStation));
//            // 查询当前站台的所有工作流列表
//            List<WorkFlow> workFlowList = workFlowService.list(new LambdaQueryWrapper<WorkFlow>()
//                    .eq(WorkFlow::getWorkStation, workStation)
//                    .eq(WorkFlow::getWorkStatus, 2));
//            // workSummary列表
//            List<WorkSummary> workSummaryList = new ArrayList<>();
//            for (WorkFlow workFlow : workFlowList) {
//                WorkSummary summary = new WorkSummary();
//                summary.setWorkFlowId(workFlow.getWorkFlowId());
//                summary.setWorkStation(workFlow.getWorkStation());
//                summary.setWorkOrder(workFlow.getWorkOrder());
//                summary.setWorkCenter(workFlow.getWorkCenter());
//                summary.setGoodsId(workFlow.getGoodsId());
//                summary.setPickedNum(workFlow.getPickedNum());
//                summary.setNeedNum(workFlow.getNeedNum());
//                summary.setLackNum(workFlow.getNeedNum().subtract(workFlow.getPickedNum()));
//                summary.setWorkDate(workFlow.getCreateTime().toLocalDate().atStartOfDay());
//                summary.setWorkStatus(workFlow.getWorkStatus());
//                summary.setLackStatus(summary.getLackNum().compareTo(BigDecimal.ZERO) > 0 ? 1 : 0);
//                summary.setFinishTime(workFlow.getFinishTime());
//                summary.setOpUser(workFlow.getOpUser());
//                // 设置电子标签位置
//                List<ELocationConfig> currentBoxELocationList = eLocationConfigList.stream().filter(e ->
//                        e.getWorkOrder().equals(workFlow.getWorkOrder())
//                                && e.getWorkCenter().equals(workFlow.getWorkCenter())).toList();
//                summary.setELocationId(currentBoxELocationList.size() > 0 ? currentBoxELocationList.get(0).getELocationId() : "");
//                workSummaryList.add(summary);
//                // 更新工单表
//                kateOrdersService.update(new LambdaUpdateWrapper<KateOrders>()
//                        .set(KateOrders::getOrderStatus, 4)
//                        .set(KateOrders::getFinishTime, LocalDateTime.now())
//                        .set(KateOrders::getPickedQuantity, workFlow.getPickedNum())
//                        .set(KateOrders::getLackQuantity, workFlow.getNeedNum().subtract(workFlow.getPickedNum()))
//                        .eq(KateOrders::getOrderId, workFlow.getOrderId())
//                        .eq(KateOrders::getSupplyArea, workFlow.getWorkCenter())
//                        .eq(KateOrders::getGoodsId, workFlow.getGoodsId()));
//                // 如果当前工单已经没有未完成的工作，更新DBS状态完成
//                if (!kateOrdersService.exists(new LambdaQueryWrapper<KateOrders>()
//                        .eq(KateOrders::getOrderId, workFlow.getOrderId())
//                        .ne(KateOrders::getOrderStatus, 4))) {
//                    kateDBSService.update(new LambdaUpdateWrapper<KateDBS>()
//                            .set(KateDBS::getDbsStatus, 2)
//                            .set(KateDBS::getLastUpdateTime, LocalDateTime.now())
//                            .eq(KateDBS::getWorkOrder, workFlow.getOrderId()));
//                }
//            }
//            workSummaryService.saveBatch(workSummaryList);
//            // 移除工作流
//            workFlowService.remove(new LambdaQueryWrapper<WorkFlow>()
//                    .eq(WorkFlow::getWorkStation, workStation));
//            // 移库站台要料
//            goodsToStationService.remove(new LambdaQueryWrapper<GoodsToStation>()
//                    .eq(GoodsToStation::getWorkStation, workStation));
//        } catch (Exception e) {
//            logger.error("完成站台：{}工作发生异常：{}", workStation, convertJsonString(e));
//            throw new Exception("完成站台：" + workStation + "工作发生异常!");
//        } finally {
//            // 当前站台工作完成
//            workFinishingStations.remove(workStation);
//        }
//        return "";
//    }

    @Override
    public String finishWork(String workStation) throws Exception {
        if (workFinishingStations.contains(workStation)) {
            // 当前站台正在完成工作
            return "当前站台正在完成工作，请勿重复操作";
        } else {
            // 添加站台
            workFinishingStations.add(workStation);
        }
        try {
            if (workFlowService.exists(new LambdaQueryWrapper<WorkFlow>()
                    .eq(WorkFlow::getWorkStation, workStation)
                    .eq(WorkFlow::getWorkStatus, 1))) {
                // 当前站台工作未全部完成
                return "工作未全部做完，不允许确认完成。";
            }
            if (eLocationConfigService.exists(new LambdaQueryWrapper<ELocationConfig>()
                    .eq(ELocationConfig::getWorkStation, workStation)
                    .eq(ELocationConfig::getPrintStatus, 0))) {
                // 有标签未打印
                return "有标签未打印";
            }
            if (!eLocationConfigService.exists(new LambdaQueryWrapper<ELocationConfig>()
                    .eq(ELocationConfig::getWorkStation, workStation))) {
                // 没有标签，说明点过确认。
                return "没有可以确认完成的工作，请勿重复点击。";
            }
            // 查找当前站台的标签配置
            List<ELocationConfig> eLocationConfigList = eLocationConfigService.list(new LambdaQueryWrapper<ELocationConfig>()
                    .eq(ELocationConfig::getWorkStation, workStation));
            // 保存一下记录
            List<ELocationConfigLast> eLocationConfigLastList = ELocationConfig.toLocationsConfigLastList(eLocationConfigList);
            // 先清空之前的
            eLocationConfigLastService.remove(new LambdaQueryWrapper<ELocationConfigLast>()
                    .eq(ELocationConfigLast::getWorkStation, workStation));
            eLocationConfigLastService.saveBatch(eLocationConfigLastList);
            // 删除所有的标签配置
            eLocationConfigService.remove(new LambdaQueryWrapper<ELocationConfig>()
                    .eq(ELocationConfig::getWorkStation, workStation));
            // 查询当前站台的所有工作流列表
            List<WorkFlow> workFlowList = workFlowService.list(new LambdaQueryWrapper<WorkFlow>()
                    .eq(WorkFlow::getWorkStation, workStation)
                    .eq(WorkFlow::getWorkStatus, 2));
            // workSummary列表
            List<WorkSummary> workSummaryList = new ArrayList<>();
            for (WorkFlow workFlow : workFlowList) {
                WorkSummary summary = new WorkSummary();
                summary.setWorkFlowId(workFlow.getWorkFlowId());
                summary.setWorkStation(workFlow.getWorkStation());
                summary.setWorkOrder(workFlow.getWorkOrder());
                summary.setWorkCenter(workFlow.getWorkCenter());
                summary.setGoodsId(workFlow.getGoodsId());
                summary.setPickedNum(workFlow.getPickedNum());
                summary.setNeedNum(workFlow.getNeedNum());
                summary.setLackNum(workFlow.getNeedNum().subtract(workFlow.getPickedNum()));
                summary.setWorkDate(workFlow.getCreateTime().toLocalDate().atStartOfDay());
                summary.setWorkStatus(workFlow.getWorkStatus());
                summary.setLackStatus(summary.getLackNum().compareTo(BigDecimal.ZERO) > 0 ? 1 : 0);
                summary.setFinishTime(workFlow.getFinishTime());
                summary.setOpUser(workFlow.getOpUser());
                // 设置电子标签位置
                List<ELocationConfig> currentBoxELocationList = eLocationConfigList.stream().filter(e ->
                        e.getWorkOrder().equals(workFlow.getWorkOrder())
                                && e.getWorkCenter().equals(workFlow.getWorkCenter())).toList();
                summary.setELocationId(currentBoxELocationList.size() > 0 ? currentBoxELocationList.get(0).getELocationId() : "");
                workSummaryList.add(summary);
            }
            workSummaryService.saveBatch(workSummaryList);
            // 移除工作流
            workFlowService.remove(new LambdaQueryWrapper<WorkFlow>()
                    .eq(WorkFlow::getWorkStation, workStation));
            // 移库站台要料
            goodsToStationService.remove(new LambdaQueryWrapper<GoodsToStation>()
                    .eq(GoodsToStation::getWorkStation, workStation));
        } catch (Exception e) {
            logger.error("完成站台：{}工作发生异常：{}", workStation, convertJsonString(e));
            throw new Exception("完成站台：" + workStation + "工作发生异常!");
        } finally {
            // 当前站台工作完成
            workFinishingStations.remove(workStation);
        }
        return "";
    }

    /**
     * 先找到MWL的小工位的配置
     *
     * @param workStation 工站
     * @param workFlows   工作流/工作任务
     * @param model       机型
     */
    private void findWorks(String workStation, List<WorkFlow> workFlows, String model) {
        // 查到当前站台所有的小工位
        LambdaQueryWrapper<WorkStationConfig> stationConfigQueryWrapper = new LambdaQueryWrapper<WorkStationConfig>().eq(WorkStationConfig::getWorkStation, workStation);
        if (Objects.equals(model, "MWL")) {
            stationConfigQueryWrapper.eq(WorkStationConfig::getModel, "MWL");
        } else {
            stationConfigQueryWrapper.ne(WorkStationConfig::getModel, "MWL");
        }
        List<WorkStationConfig> currentStationConfigsOfNwl = workStationConfigService.list(stationConfigQueryWrapper);
        // 没有工站配置
        if (currentStationConfigsOfNwl == null || currentStationConfigsOfNwl.isEmpty()) {
            return;
        }
        // 今日开工的工单和小工位
        Map<String, List<WorkCenterAndOrderDto>> tasksOfTodayMap = new HashMap<>();
        // 查询当前未开始的工单
        List<KateOrders> allNewKateWorkOrders = kateOrdersService.list(new LambdaQueryWrapper<KateOrders>()
                .eq(KateOrders::getOrderStatus, 0)
                .eq(KateOrders::getSortString, configMap.get(ConfigMapKeyEnum.SLOC_FILTER_STRING.getConfigKey())));
        // 查询所有的dbs
        List<KateDBS> allKateDBS = kateDBSService.list(new LambdaQueryWrapper<KateDBS>().orderByAsc(KateDBS::getWorkSequence));
        // 根据所有小工位，查到对应的任务
        for (WorkStationConfig workConfig : currentStationConfigsOfNwl) {
            // 查询当前小工位是否已经判断过开工日期
            if (StringUtils.isEmpty(workConfig.getSmallBox()) || tasksOfTodayMap.containsKey(workConfig.getSmallBox())) {
                continue;
            }
            // 通过工单表查询到对应的工单
            List<KateOrders> kateWorkOrders = allNewKateWorkOrders.stream().filter(kateWorkOrder ->
                    kateWorkOrder.getSupplyArea().equals(workConfig.getSmallBox())).toList();
            // 当前工位没有未完成的工单
            if (kateWorkOrders.isEmpty()) {
                continue;
            }
            List<WorkCenterAndOrderDto> toDaysOrders = new ArrayList<>();
            // 防止重复查询
            Map<String, KateDBS> ordersAndDBSMap = new HashMap<>();
            for (KateOrders kateWorkOrder : kateWorkOrders) {
                if (!ordersAndDBSMap.containsKey(kateWorkOrder.getWorkOrder())) {
                    // 从DBS表查询对应的工单以及开工时间
                    KateDBS kateDBS = allKateDBS.stream().filter(tempKateDBS ->
                            tempKateDBS.getWorkOrder().equals(kateWorkOrder.getWorkOrder())).findFirst().orElse(null);
                    if (kateDBS == null || StringUtils.isEmpty(kateDBS.getWorkOrder())) {// 不存在对应的工单计划
                        continue;
                    }
                    // 判断是否是当天开工
                    int indexOfDbs = localWorkDateList.indexOf(kateDBS.getPlanStartDate().toLocalDate());
                    if (indexOfDbs == -1) {
                        // 工作日不包含此开工日期
                        continue;
                    }
                    int indexAfterAdjust = indexOfDbs + workConfig.getStartDateAdjust();
                    if (indexAfterAdjust < 0 || indexAfterAdjust >= localWorkDateList.size()) {
                        // 调整后的日期不再工作日范围
                        continue;
                    }
                    if (localWorkDateList.get(indexAfterAdjust).equals(LocalDate.now())) {
                        // 已经查询过的为了不重复查询，添加map
                        ordersAndDBSMap.put(kateWorkOrder.getWorkOrder(), kateDBS);
                        // 添加工作计划
                        WorkCenterAndOrderDto wcoDto = new WorkCenterAndOrderDto();
                        wcoDto.setWorkCenter(workConfig.getSmallBox());
                        wcoDto.setWorkOrder(kateWorkOrder.getWorkOrder());
                        wcoDto.setStartDate(LocalDateTime.now().toLocalDate().atStartOfDay());
                        wcoDto.setDbsSequence(kateDBS.getWorkSequence());
                        toDaysOrders.add(wcoDto);
                    }
                }
            }
            tasksOfTodayMap.put(workConfig.getSmallBox(), toDaysOrders);
        }
        // 判断是否有今天开工的工单和小工位
        if (!tasksOfTodayMap.isEmpty()) {
            for (String smallBoxKey : tasksOfTodayMap.keySet()) {
                List<WorkCenterAndOrderDto> currentWorkCenterAndOrderDtoList = tasksOfTodayMap.get(smallBoxKey).stream().sorted(Comparator.comparingInt(WorkCenterAndOrderDto::getDbsSequence)).toList();
                for (WorkCenterAndOrderDto currentWorkCenterAndOrderDto : currentWorkCenterAndOrderDtoList) {
                    // 通过工单表查询到对应的工单
                    List<KateOrders> kateWorkOrderList = allNewKateWorkOrders.stream().filter(kateWorkOrder ->
                            kateWorkOrder.getWorkOrder().equals(currentWorkCenterAndOrderDto.getWorkOrder())
                    && kateWorkOrder.getSupplyArea().equals(currentWorkCenterAndOrderDto.getWorkCenter())).toList();
                    for (KateOrders tempOrder : kateWorkOrderList) {
                        // 生成workFlow
                        WorkFlow tempWorkFlow = new WorkFlow();
                        tempWorkFlow.setWorkFlowId(WmsUtils.generateId("WORKFLOW_"));
                        tempWorkFlow.setOrderId(tempOrder.getOrderId());
                        tempWorkFlow.setWorkStation(workStation);
                        tempWorkFlow.setWorkOrder(tempOrder.getWorkOrder());
                        tempWorkFlow.setWorkCenter(tempOrder.getSupplyArea());
                        tempWorkFlow.setGoodsId(tempOrder.getGoodsId());
                        tempWorkFlow.setNeedNum(tempOrder.getRequirementQuantity());
                        tempWorkFlow.setCreateTime(LocalDateTime.now());
                        tempWorkFlow.setWorkStatus(0);
                        tempWorkFlow.setLightStatus(0);
                        tempWorkFlow.setPickedNum(BigDecimal.ZERO);
                        workFlows.add(tempWorkFlow);
                    }
                }
            }
        }
    }
}
