package com.ruoyi.web.controller.app;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.app.domain.*;
import com.ruoyi.app.domain.DTO.OtherStockInRequest;
import com.ruoyi.app.domain.DTO.PickCompleteReq;
import com.ruoyi.app.service.*;
import com.ruoyi.app.service.impl.AppPendingStorageServiceImpl;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.AppConstants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.OrderCodeFactory;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.web.controller.section.EnhanceDataList;
import com.ruoyi.web.domain.*;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.client.RestTemplate;

/**
 * 【请填写功能名称】Controller
 *
 * @author ruoyi
 * @date 2025-01-15
 */
@RestController
@RequestMapping("/app/task")
public class AppTaskController extends BaseController
{
    @Autowired
    private IAppTaskService appTaskService;
    @Autowired
    private IAppLocationService appLocationService;
    @Autowired
    private IAppWcsTaskService appWcsTaskService;
    @Autowired
    private IAppWcsTaskBakService appWcsTaskBakService;
    @Autowired
    private IAppPmsOrderInService appPmsOrderInService;
    @Autowired
    private IAppTaskBakService appTaskBakService;
    @Autowired
    private IAppStockService appStockService;
    @Autowired
    private IAppPendingStorageService appPendingStorageService;

    private final List<Integer> wcsTaskStatusList = Arrays.asList(1, 2, 3, 4, 5, 100, 998, 999);
    @Autowired
    private AppPendingStorageServiceImpl appPendingStorageServiceImpl;

    @Autowired
    private IAppVehicleService appVehicleService;
    @Autowired
    private IAppPmsOrderOutService appPmsOrderOutService;
    /**
     * 查询【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:task:list')")
    @GetMapping("/list")
    @EnhanceDataList(entityType = AppTask.class)
    public TableDataInfo list(AppTask appTask)
    {
        startPage();
        List<AppTask> list = appTaskService.selectAppTaskList(appTask);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:task:export')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AppTask appTask)
    {
        List<AppTask> list = appTaskService.selectAppTaskList(appTask);
        ExcelUtil<AppTask> util = new ExcelUtil<AppTask>(AppTask.class);
        util.exportExcel(response, list, "【请填写功能名称】数据");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:task:query')")
    @GetMapping(value = "/{taskId}")
    public AjaxResult getInfo(@PathVariable("taskId") String taskId)
    {
        return success(appTaskService.selectAppTaskByTaskId(taskId));
    }

    /**
     * 新增【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:task:add')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AppTask appTask)
    {
        return toAjax(appTaskService.insertAppTask(appTask));
    }

    /**
     * 修改【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:task:edit')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AppTask appTask)
    {
        return toAjax(appTaskService.updateAppTask(appTask));
    }

    /**
     * 删除【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:task:remove')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @DeleteMapping("/{taskIds}")
    public AjaxResult remove(@PathVariable String[] taskIds)
    {
        return toAjax(appTaskService.deleteAppTaskByTaskIds(taskIds));
    }

    /**
     * 执行任务
     */
    @ApiOperation("生成库位")
//    @Log(title = "执行任务", businessType = BusinessType.INSERT)
    @PostMapping("/executeTask")
    @Anonymous
    public AjaxResult executeTask(@RequestBody AppTask appTask)
    {

        // 设置库位
        AppLocation appLocation = appLocationService.requestLocation(1);
        appLocation.setLocationStatus(1);
//        appLocation.setIsWorking(1);
        appLocationService.updateAppLocation(appLocation);
        // 将对应的任务设置为可以下发状态




        return success(appLocation);
    }

    /**
     * 反馈任务状态
     */
    @ApiOperation("生成库位")
    @Log(title = "执行任务", skipAuth = true)
    @PostMapping("/receiveTaskResult")
    @Anonymous
    public AjaxResult receiveTaskResult(@RequestBody TaskResultFeedRequest feedBackRequest)
    {
        // 判断请求参数是否齐全
        if (feedBackRequest == null
        || StringUtils.isEmpty(feedBackRequest.getTaskId())
        || feedBackRequest.getTaskStatus() == null
        || StringUtils.isEmpty(feedBackRequest.getVehicleNo())) {
            return error("缺少请求数据。");
        }
        // 判断任务状态是否正确
        if (!wcsTaskStatusList.contains(feedBackRequest.getTaskStatus())) {
            return error("任务状态码反馈不正确。");
        }
        // 查询任务号
        AppWcsTask thisFbWcsTask = appWcsTaskService.selectAppWcsTaskByWcsTaskId(feedBackRequest.getTaskId());
        if (thisFbWcsTask == null) {
            return error("反馈的任务号不存在。");
        }
        // 判断反馈的任务号与数据库中是否一致
        if (Objects.equals(thisFbWcsTask.getWcsTaskStatus(), feedBackRequest.getTaskStatus())) {
            return error("请勿重复反馈相同任务状态。");
        }
        AppTask wmsTaskQuery = new AppTask();
        wmsTaskQuery.setWcsTaskId(feedBackRequest.getTaskId());
        List<AppTask> thisWmsTaskList = appTaskService.selectAppTaskList(wmsTaskQuery);
        if (Arrays.asList(1, 2, 3, 4, 5).contains(feedBackRequest.getTaskStatus())) {
            // 这些任务状态只需要更新任务状态即可
            thisFbWcsTask.setWcsTaskStatus(feedBackRequest.getTaskStatus());
            appWcsTaskService.updateAppWcsTask(thisFbWcsTask);
            if (thisWmsTaskList != null && !thisWmsTaskList.isEmpty()) {
                // 更新wms任务状态
                thisWmsTaskList.forEach(appTask -> appTask.setTaskStatus(2));// 执行中
                appTaskService.batchUpdateAppTask(thisWmsTaskList);
            }
            return success("反馈任务执行中成功。");
        }
        if (100 == feedBackRequest.getTaskStatus()) {
            // 删除wcs任务，并添加任务记录
            thisFbWcsTask.setFinishTime(new Date());
            thisFbWcsTask.setWcsTaskStatus(100);
            appWcsTaskBakService.insertAppWcsTaskBak(thisFbWcsTask.toAppWcsTaskBak());
            appWcsTaskService.deleteAppWcsTaskByWcsTaskId(feedBackRequest.getTaskId());
            // 任务完成，更新对应的wms任务状态，
            if (thisWmsTaskList != null && !thisWmsTaskList.isEmpty()) {
                // 更新wms任务状态
                thisWmsTaskList.forEach(appTask -> appTask.setTaskStatus(5));// 任务完成
                appTaskService.batchUpdateAppTask(thisWmsTaskList);
            }
            return success("反馈任务完成成功。");
        }
        if (998 == feedBackRequest.getTaskStatus()) {
            // 任务取消
            thisFbWcsTask.setFinishTime(new Date());
            thisFbWcsTask.setWcsTaskStatus(998);
            appWcsTaskBakService.insertAppWcsTaskBak(thisFbWcsTask.toAppWcsTaskBak());
            appWcsTaskService.deleteAppWcsTaskByWcsTaskId(feedBackRequest.getTaskId());
            // 任务取消，更新对应的wms任务状态
            if (thisWmsTaskList != null && !thisWmsTaskList.isEmpty()) {
                // 更新wms任务状态
                thisWmsTaskList.forEach(appTask -> appTask.setTaskStatus(8));// wcs取消任务
                appTaskService.batchUpdateAppTask(thisWmsTaskList);
            }
            return success("反馈任务取消成功。");
        }
        if (999 == feedBackRequest.getTaskStatus()) {
            // 任务异常
            thisFbWcsTask.setFinishTime(new Date());
            thisFbWcsTask.setWcsTaskStatus(999);
            appWcsTaskService.updateAppWcsTask(thisFbWcsTask);
            // 任务异常，更新对应的wms任务状态
            if (thisWmsTaskList != null && !thisWmsTaskList.isEmpty()) {
                // 更新wms任务状态
                thisWmsTaskList.forEach(appTask -> appTask.setTaskStatus(9));// 任务异常
                appTaskService.batchUpdateAppTask(thisWmsTaskList);
            }
            return success("反馈任务异常成功。");
        }

        return error("处理任务反馈错误。");
    }

    /**
     * 接受wcs请求的入库请求
     * WCS 请求此接口
     * @param wcsStackerTask wcs请求的信息
     * @return 返回的任务
     */
    @ApiOperation("接受wcs请求的入库请求")
    @PostMapping("/sendLocation")
    @Transactional(rollbackFor = Exception.class)
    @Anonymous
    public AjaxResult sendLocation(@RequestBody WcsLocationRequest wcsStackerTask)
    {
        if(ObjectUtil.isEmpty(wcsStackerTask.getPoint())||
        ObjectUtil.isEmpty(wcsStackerTask.getVehicleNo())){
            return error("缺少请求数据");
        }
        AppPendingStorage appPendingStorage = new AppPendingStorage();
        appPendingStorage.setVehicleNo(wcsStackerTask.getVehicleNo());
        List<AppPendingStorage> appPendingStorages = appPendingStorageService.selectAppPendingStorageList(appPendingStorage);
        if(appPendingStorages == null || appPendingStorages.isEmpty()){
            return error("该载具似乎还未码盘");
        }
        AppTask appTask = new AppTask();
        appTask.setVehicleId(wcsStackerTask.getVehicleNo());
        List<AppTask> appTasks = appTaskService.selectAppTaskList(appTask);
        if(!appTasks.isEmpty()){
            return error("此托盘任务已存在");
        }

        AppTask appTask2 = new AppTask();
        BeanUtils.copyProperties(wcsStackerTask, appTask2);
        appTask2.setTaskId("RK"+System.currentTimeMillis());
        appTask2.setWcsTaskId("RK"+System.currentTimeMillis());
        appTask2.setTaskStatus(1);
        appTask2.setTaskType(1);
        appTask2.setOrigin(wcsStackerTask.getPoint());
        appTask2.setTaskPriority(1);
        String location = appLocationService.sendLocation();
        appTask2.setDestination(location);
        appTask2.setVehicleId(wcsStackerTask.getVehicleNo());
        int i1 = appTaskService.insertAppTask(appTask2);
        if(i1 == 0 ){
            return error("wms生成入库任务异常");
        }
        AppWcsTask appTask1 = new AppWcsTask();
        BeanUtils.copyProperties(wcsStackerTask, appTask);
        appTask1.setWcsTaskId(appTask2.getTaskId());
        appTask1.setWcsTaskStatus(1);
        appTask1.setWcsTaskType(appTask2.getTaskType());
        appTask1.setOrigin("101");
        appTask1.setTaskPriority(appTask2.getTaskPriority());
        appTask1.setDestination(location);
        appTask1.setSendTime(new Date());
        appTask1.setVehicleId(appTask2.getVehicleId());
        int i = appWcsTaskService.insertAppWcsTask(appTask1);
        if(i == 0 ){
            return error("wcs生成入库任务异常");
        }

        WcsDate wcsDate = new WcsDate();
        wcsDate.setTaskId(appTask2.getTaskId());
        wcsDate.setUser("WMS");
        wcsDate.setVehicleNo(wcsStackerTask.getVehicleNo());
        wcsDate.setDestination(location);
        return success(wcsDate);
    }


    @ApiOperation("任务反馈")
    @PostMapping("/taskResult")
    @Anonymous
    @Transactional
    public AjaxResult taskResult(@RequestBody TaskResultFeedRequest taskResultFeedRequest)
    {
        if(ObjectUtil.isEmpty(taskResultFeedRequest.getTaskId()) ||
                ObjectUtil.isEmpty(taskResultFeedRequest.getVehicleNo())){
            return error("缺少请求数据");
        }
        AppTask appTask1 = appTaskService.selectAppTaskByTaskId(taskResultFeedRequest.getTaskId());
        if(ObjectUtil.isEmpty(appTask1)){
            return error("wms任务不存在");
        }
        AppWcsTask appWcsTask = appWcsTaskService.selectAppWcsTaskByWcsTaskId(taskResultFeedRequest.getTaskId());
        if(ObjectUtil.isEmpty(appWcsTask)){
            return error("wcs任务不存在");
        }
        if(ObjectUtil.isNotEmpty(taskResultFeedRequest.getTaskStatus())){
            if(!wcsTaskStatusList.contains(taskResultFeedRequest.getTaskStatus())){
                return error("缺少请求数据");
            }
            AppTask appTask = new AppTask();
            appTask.setTaskId(taskResultFeedRequest.getTaskId());
            appTask.setTaskStatus(taskResultFeedRequest.getTaskStatus());
            int i = appTaskService.updateAppTask(appTask);
            if (i == 0 ){
                return error("wms更新任务信息失败");
            }
            AppWcsTask appWcsTask1 = new AppWcsTask();
            appWcsTask1.setWcsTaskId(taskResultFeedRequest.getTaskId());
            appWcsTask1.setWcsTaskStatus(taskResultFeedRequest.getTaskStatus());
            int i1 = appWcsTaskService.updateAppWcsTask(appWcsTask1);
            if (i1 == 0 ){
                return error("wcs更新任务信息失败");
            }
        }
        //wcs反馈
        if(taskResultFeedRequest.getTaskStatus() == 100){
            AppTask appTask = new AppTask();
            appTask.setVehicleId(taskResultFeedRequest.getVehicleNo());
            List<AppTask> appTasks = appTaskService.selectAppTaskList(appTask);
            AppWcsTask appWcsTask1 = new AppWcsTask();
            appWcsTask1.setVehicleId(taskResultFeedRequest.getVehicleNo());
            List<AppWcsTask> appWcsTasks = appWcsTaskService.selectAppWcsTaskList(appWcsTask1);

            if(ObjectUtil.isEmpty(appTasks)){
                return error("该托盘不存在wms任务");
            }
            if(ObjectUtil.isEmpty(appWcsTasks)){
                return error("该托盘不存在wcs任务");
            }
            for (AppWcsTask appWcsTask3 : appWcsTasks) {
                //wcs移存到历史表中
                AppWcsTask appWcsTask2 = appWcsTaskService.selectAppWcsTaskByWcsTaskId(appWcsTask3.getWcsTaskId());
                AppWcsTaskBak appWcsTask4 = new AppWcsTaskBak();
                BeanUtils.copyProperties(appWcsTask2, appWcsTask4);
                appWcsTask4.setFinishTime(new Date());
                appWcsTaskBakService.insertAppWcsTaskBak(appWcsTask4);
                appWcsTaskService.deleteAppWcsTaskByWcsTaskId(appWcsTask2.getWcsTaskId());
            }
            for(AppTask appTask2 : appTasks){
                if(ObjectUtil.isEmpty(appTask2.getGoodsId())){
                    return error("此托盘未绑定物料");
                }
                AppPmsOrderIn appPmsOrderIn = new AppPmsOrderIn();
                appPmsOrderIn.setGoodsId(appTask2.getGoodsId());
                List<AppPmsOrderIn> appPmsOrderIns = appPmsOrderInService.selectAppPmsOrderInList(appPmsOrderIn);
                if(ObjectUtil.isEmpty(appPmsOrderIns)){
                    return error("该物料任务单不存在");
                }

                //物料操作数量
                BigDecimal opNum = appTask2.getOpNum();

                String url = "http://localhost:9430/app/task/kk";
                RestTemplate restTemplate = new RestTemplate();
                SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
                //连接超时时间
                factory.setConnectTimeout(5000);
                // 读取超时时间
                factory.setReadTimeout(10000);
                restTemplate.setRequestFactory(factory);
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);

                PmsOrderInRequest orderInRequest = new PmsOrderInRequest();
                orderInRequest.setOrderId(appPmsOrderIns.get(0).getOrderId());
                orderInRequest.setGoodsId(appPmsOrderIns.get(0).getGoodsId());
                if(ObjectUtil.isNotEmpty(appTask2.getOpNum())){
                    orderInRequest.setGoodsNum(appTask2.getOpNum().intValue());
                }else{
                    orderInRequest.setGoodsNum(appPmsOrderIns.get(0).getGoodsNum().intValue());
                }
                orderInRequest.setGoodsCode(appPmsOrderIns.get(0).getGoodsCode());
                orderInRequest.setSpare1(appPmsOrderIns.get(0).getSpare1());
                orderInRequest.setSpare2(appPmsOrderIns.get(0).getSpare2());


                //修改库位状态
                AppLocation appLocation = new AppLocation();
                appLocation.setLocationId(appTask2.getDestination());
                appLocation.setLocationStatus(2);
                appLocationService.updateAppLocation(appLocation);
                //更新库存
                AppStock appStock = new AppStock();
                appStock.setStockId(appTask2.getGoodsId());
                appStock.setGoodsId(appTask2.getGoodsId());
                appStock.setVehicleId(appTask2.getVehicleId());
                appStock.setLocationId(appTask2.getDestination());
                appStock.setOriginNum(BigDecimal.valueOf(orderInRequest.getGoodsNum()));
                appStock.setGoodsUnit(appPmsOrderIns.get(0).getUnit());
                appStockService.insertAppStock(appStock);
                //wms移存到历史表
                AppTaskBak appTaskBak = new AppTaskBak();
                BeanUtils.copyProperties(appTask2, appTaskBak);
                appTaskBak.setCreateTime(new Date());
                appTaskBak.setOpNum(BigDecimal.valueOf(orderInRequest.getGoodsNum()));
                appTaskBak.setFinishTime(new Date());
                appTaskBakService.insertAppTaskBak(appTaskBak);
                appTaskService.deleteAppTaskByTaskId(appTask2.getTaskId());
                //更新pms任务表
                AppPmsOrderIn appPmsOrderIn1 = new AppPmsOrderIn();
                appPmsOrderIn1.setGoodsId(appTask2.getGoodsId());
                appPmsOrderIn1.setOrderStatus(Long.valueOf(0));
                List<AppPmsOrderIn> appPmsOrderIns1 = appPmsOrderInService.selectAppPmsOrderInList(appPmsOrderIn1);
                if(ObjectUtil.isEmpty(appPmsOrderIns1)){
                    return error("物料未绑定托盘");
                }
                AppPmsOrderIn appPmsOrderIn2 = appPmsOrderIns1.get(0);
                appPmsOrderIn2.setOrderStatus(2L);
                appPmsOrderIn2.setUsedNum(BigDecimal.valueOf(orderInRequest.getGoodsNum()));
                appPmsOrderIn2.setRemainingNum(appPmsOrderIn2.getGoodsNum().subtract(BigDecimal.valueOf(orderInRequest.getGoodsNum())));
                int i1 = appPmsOrderInService.updateAppPmsOrderIn(appPmsOrderIn2);
                if(i1 == 0 ){
                    return error("pms任务表更新失败");
                }
                //更新码盘表
                AppPendingStorage appPendingStorage = new AppPendingStorage();
                appPendingStorage.setGoodsId(appTask2.getGoodsId());
                appPendingStorage.setStatus(1);
                List<AppPendingStorage> appPendingStorages = appPendingStorageServiceImpl.selectAppPendingStorageList(appPendingStorage);
                if(ObjectUtil.isEmpty(appPendingStorages)){
                    return error("未查询到码盘信息");
                }
                AppPendingStorage appPendingStorage1 = appPendingStorages.get(0);
                appPendingStorage1.setStatus(3);
                appPendingStorage1.setGoodsNum(BigDecimal.valueOf(orderInRequest.getGoodsNum()));
                appPendingStorage1.setUpdateTime(new Date());
                int i = appPendingStorageServiceImpl.updateAppPendingStorage(appPendingStorage1);
                if(i == 0){
                    return error("码盘表信息更新失败");
                }

                HttpEntity<PmsOrderInRequest> requestEntity = new HttpEntity<>(orderInRequest, headers);
                String response = restTemplate.postForObject(url, requestEntity, String.class);
                boolean contains = response.contains("200");
                if(!contains){
                    return error("上报pms失败");
                }

            }

        }
        return AjaxResult.success("成功");
    }
    @PostMapping("/kk")
    @Anonymous
    public AjaxResult kk(@RequestBody PmsOrderInRequest orderInRequest)
    {
        return success();
    }

    /**
     * 出库单出库请求
     * appPmsOrderOutList 出库单列表
     * @return 结果
     */
    @ApiOperation("请求出库")
    @PostMapping("/createOutRequestByPmsOrders")
    @Transactional(rollbackFor = Exception.class)
    @Anonymous
    public AjaxResult createOutRequestByPmsOrders(@RequestBody List<AppPmsOrderOut> appPmsOrderOutList)
    {
        // 判断是否为空
        if (CollectionUtils.isEmpty(appPmsOrderOutList)) {
            return error("出库单明细不能为空");
        }
        //如果物料编码重复，报异常
        // 判断goodsId是否重复
        if (appPmsOrderOutList.stream().map(AppPmsOrderOut::getGoodsId).distinct().count() != appPmsOrderOutList.size()) {
            return error("出库单明细不能有重复物料编码");
        }

        //
        logger.info("请求出库单明细：{}", appPmsOrderOutList);
        //value: 以托盘号为key，该托盘出库该物料的出库数量为value的map
        Map<String,Map<String,BigDecimal>> goodsMap = new HashMap<String,Map<String,BigDecimal>>();
        for(AppPmsOrderOut appPmsOrderOut: appPmsOrderOutList){
            if(AppConstants.OUT_ORDER_STATUS_2.equals(appPmsOrderOut.getOrderStatus())){
                logger.info("已出库完成的忽略：{}",appPmsOrderOut.getGoodsId());
               throw new RuntimeException("有出库单已全部出库，请重新选择");
            }
            if("1".equals(appPmsOrderOut.getIsLock())){
                logger.info("已锁定的忽略：{}",appPmsOrderOut.getGoodsId());
                throw new RuntimeException("有出库单已锁定，请重新选择");
            }
            if(appPmsOrderOut.getShelvesNum() == null || appPmsOrderOut.getShelvesNum().compareTo(BigDecimal.ZERO) == 0){
                logger.info("出库数量为0，忽略：{}",appPmsOrderOut.getGoodsId());
                throw new RuntimeException("出库数量不能为0，请确认");
            }
            //存储每个托盘的需要出的数量
            Map<String,BigDecimal> ctlMap = new HashMap<>();
            //根据物料ID查询库存，按照先进先出的原则，按上架时间倒叙查询
            AppStock tMiStock = new AppStock();
            tMiStock.setGoodsId(appPmsOrderOut.getGoodsId());

            List<AppStock> appStocks = appStockService.selectStockByGoodsId(tMiStock);

            if(appStocks.size() == 0){
                logger.warn("未找到该物料库存：{}",appPmsOrderOut.getGoodsId());
                throw new RuntimeException("未找到该物料库存："+appPmsOrderOut.getGoodsId());
            }
            //本次出库数量
            BigDecimal shelvesNum = appPmsOrderOut.getShelvesNum();
            BigDecimal total = BigDecimal.ZERO;
            for(AppStock appStock : appStocks){
                total = total.add(appStock.getOriginNum());
                if(appPmsOrderOut.getPickNum() == null){
                    appPmsOrderOut.setPickNum(BigDecimal.ZERO);
                }
                if(shelvesNum.compareTo(total) == 0){
                    ctlMap.put(appStock.getVehicleId(),appStock.getOriginNum());
                    appPmsOrderOut.setPickNum(appPmsOrderOut.getPickNum().add(appStock.getOriginNum()));
                    break;
                }else if(shelvesNum.compareTo(total) > 0){
                    ctlMap.put(appStock.getVehicleId(),appStock.getOriginNum());
                    appPmsOrderOut.setPickNum(appPmsOrderOut.getPickNum().add(appStock.getOriginNum()));
                }else{
                    //小于0
                    BigDecimal subtract = total.subtract(shelvesNum);
                    BigDecimal subtract1 = appStock.getOriginNum().subtract(subtract);
                    ctlMap.put(appStock.getVehicleId(),subtract1);
                    appPmsOrderOut.setPickNum(appPmsOrderOut.getPickNum().add(subtract1));
                    break;
                }
            }
            //存储在大的map中
            goodsMap.put(appPmsOrderOut.getGoodsId(),ctlMap);
            logger.info("更新累计出库数量：{}",appPmsOrderOut);
            appPmsOrderOut.setIsLock("1");
            appPmsOrderOutService.updatePickNum(appPmsOrderOut);
        }

        //创建出库任务
        /**
         * 假如 物料A 需要出库的托盘为1 ，3 ，8
         * 物料B 需要出库的托盘为1，5
         * 则本次出库的总的任务为4个，1，3，5，8
         * 根据这个逻辑进行开发
         */

        //lambda表达式遍历
        //蒋map进行转换，转换为以托盘为大key，以物料和数量为小map的map
        Map<String,Map<String,BigDecimal>> ctlGoodsMap = new HashMap<>();
        goodsMap.forEach((goodsId,ctlMap) -> {
            ctlMap.forEach((vehicleId,shelvNum) ->{
                AtomicBoolean isExist = new AtomicBoolean(false);
                ctlGoodsMap.forEach((key,value) -> {
                    if(vehicleId.equals(key)){
                        isExist.set(true);
                        value.put(goodsId,shelvNum);
                    }
                });

                if(!isExist.get()){
                    Map<String,BigDecimal> map = new HashMap<>();
                    map.put(goodsId,shelvNum);
                    ctlGoodsMap.put(vehicleId,map);
                }

            });
        });

        logger.info("生成以托盘号为主键的map：{}",ctlGoodsMap);

        //根据每个托盘创建出库任务
        //1. 判断出库任务是否已产生该托盘的任务
        //获取订单号
        String orderId = appPmsOrderOutList.get(0).getOrderId();
        ctlGoodsMap.forEach((key,value) ->{
            List<AppTask> appTasks = getAppTaskByVehicleId(key,null);
            if(!CollectionUtils.isEmpty(appTasks)){
                logger.error("该托盘已产生任务：{}",key);
                throw new RuntimeException("该托盘已产生任务："+key);
            }

            //出库
            setCk(key,value,orderId);

        });

        return success("处理出库请求成功，并已生成出库任务。");
    }

    private List<AppTask> getAppTaskByVehicleId(String vehicleId,String locationId) {
        AppTask appTask =new AppTask();
        appTask.setVehicleId(vehicleId);
        appTask.setLocationId(locationId);
        if(StringUtils.isBlank(locationId)) {
            appTask.setTaskType(AppConstants.TASK_TYPE_OUT);
        }
        //判断该托盘是否产生任务
        return appTaskService.selectAppTaskList(appTask);
    }

    private void setCk(String vehicleId,Map<String,BigDecimal> map,String orderId) {
        AppStock appStock = new AppStock();
        appStock.setVehicleId(vehicleId);
        //该托盘的所有物料
        List<AppStock> appStocks = appStockService.selectAppStockList(appStock);
        //设置packingNum为空
        appStocks.forEach(appStock1 -> {
            appStock1.setPackingNum(null);
        });


        logger.info("该库位:{},库存列表为：{}", vehicleId, appStocks);
        //判断是否需要移库
        String locId = appStocks.get(0).getLocationId();
        int sts = appStocks.get(0).getStockStatus();
        if (sts == 1) {
            logger.error("该库存为冻结状态，请确认！");
            throw new RuntimeException("该库存为冻结状态，请确认！");
        }
        if (StringUtils.isBlank(locId)) {
            throw new RuntimeException("获取库位异常");
        }
        boolean isTransfer = false;
        //根据库位查询库位信息
        AppLocation appLocation = appLocationService.selectAppLocationByLocationId(locId);
        if (appLocation.getwDepth() == 2) {
            //判断01是否有货
            String locationId = locId.substring(0, locId.length() - 1) + "01";
            List<AppTask> appTasks = getAppTaskByVehicleId(null, locationId);
            if (!CollectionUtils.isEmpty(appTasks)) {
                logger.error(locationId + "有任务执行，请稍后再试");
                throw new RuntimeException(locationId + "有任务执行，请稍后再试！");
            }

            AppLocation areaLocation = new AppLocation();
            areaLocation.setLocationStatus(1);
            areaLocation.setLocationId(locationId);
            String transferCtl = StringUtils.EMPTY;
            List<AppLocation> tBaseStorageAreaLocations = appLocationService.selectAppLocationList(areaLocation);
            if (tBaseStorageAreaLocations.size() > 0) {
                AppStock AppStock1 = new AppStock();
                AppStock1.setLocationId(locationId);
                List<AppStock> tMiStocks1 = appStockService.selectAppStockList(AppStock1);
                if (tMiStocks1.size() > 0) {
                    transferCtl = tMiStocks1.get(0).getVehicleId();
                    isTransfer = true;
                }
            } else {
                AppStock tMiStock1 = new AppStock();
                tMiStock1.setLocationId(locationId);
                List<AppStock> tMiStocks1 = appStockService.selectAppStockList(tMiStock1);
                if (tMiStocks1.size() > 0) {
                    transferCtl = tMiStocks1.get(0).getVehicleId();
                    int sts1 = tMiStocks1.get(0).getStockStatus();
                    if (sts1 == 1) {
                        logger.error(locId + "：产生出库任务失败");
                        throw new RuntimeException(locId + "：产生出库任务失败");
                    }
                    isTransfer = true;
                }
            }
            //移库
            if (isTransfer) {
//                    查询空闲库位
                List<AppLocation> tBaseStorageAreaLocationList = appLocationService.selectFreeLoc();
                if (CollectionUtils.isEmpty(tBaseStorageAreaLocationList)) {
                    logger.error("没有空闲库位");
                    throw new RuntimeException("没有空闲库位移库");
                }

                String toLoc = StringUtils.EMPTY;
                for (AppLocation tBaseStorageAreaLocation : tBaseStorageAreaLocationList) {
                    //如果在浅货位，需要判断深货位是否有货
                    String tempLocationId = tBaseStorageAreaLocation.getLocationId();
                    if (tBaseStorageAreaLocation.getwDepth() == 1) {
                        String locationY = tempLocationId.substring(0, tempLocationId.length() - 1) + "02";
                        AppStock tMiStock5 = new AppStock();
                        tMiStock5.setLocationId(locationY);
                        List<AppStock> tMiStocks5 = appStockService.selectAppStockList(tMiStock5);
                        if (CollectionUtils.isEmpty(tMiStocks5)) {
                            logger.warn("深货位无库存，切换：{}", locationY);
                            continue;
                        }
                        //判断任务表有没有该库位
                        List<AppTask> appTasks5 = getAppTaskByVehicleId(null, locationY);
                        if (!CollectionUtils.isEmpty(appTasks5)) {
                            logger.warn("深货位有任务，切换：{}", locationY);
                            continue;
                        }
                        toLoc = tBaseStorageAreaLocation.getLocationId();
                        break;
                    } else {
                        //判断该库位如果是在深库位，需要判断浅库位是否有货
                        String locationY = tempLocationId.substring(0, tempLocationId.length() - 1) + "01";
                        //
                        AppStock tMiStock5 = new AppStock();
                        tMiStock5.setLocationId(locationY);
                        List<AppStock> tMiStocks5 = appStockService.selectAppStockList(tMiStock5);
                        if (!CollectionUtils.isEmpty(tMiStocks5)) {
                            logger.warn("浅货位有库存，切换：{}", locationY);
                            continue;
                        }
                        //判断任务表有没有该库位
                        List<AppTask> appTasks5 = getAppTaskByVehicleId(null, locationY);
                        if (!CollectionUtils.isEmpty(appTasks5)) {
                            logger.warn("浅货位有任务，切换：{}", locationY);
                            continue;
                        }

                        toLoc = tBaseStorageAreaLocation.getLocationId();
                        break;
                    }
                }
                if (StringUtils.isBlank(toLoc)) {
                    logger.error("没有找到移库地址，出库失败");
                    throw new RuntimeException("没有找到移库地址，出库失败");
                }
                //创建出库任务
                AppTask appTask = new AppTask();
                String yc = OrderCodeFactory.getOrderCode("YK", "");
                appTask.setTaskId(yc);
                appTask.setTaskType(AppConstants.TASK_TYPE_TRANSFER);
                appTask.setLocationId(locationId);
                appTask.setOrigin(locationId);
                appTask.setDestination(toLoc);
                appTask.setVehicleId(transferCtl);
                appTask.setTaskStatus(AppConstants.LOCATION_STATUS_ENABLE);
                appTask.setUpdateTime(new Date());
                appTask.setCreateTime(new Date());
                LoginUser loginUser = SecurityUtils.getLoginUser();
                appTask.setCreateBy(loginUser == null ? "移库任务" : loginUser.getUsername());

                appTaskService.insertAppTask(appTask);
                logger.info("生成移库任务=====》》》》》从{},到{}", locationId, toLoc);
                //冻结库位
                AppLocation tBaseStorageAreaLocation = new AppLocation();
                tBaseStorageAreaLocation.setLocationStatus(AppConstants.LOCATION_STATUS_DISABLE);
                tBaseStorageAreaLocation.setIsWorking(AppConstants.LOCATION_STATUS_DISABLE);
                tBaseStorageAreaLocation.setLocationId(toLoc);

                appLocationService.updateAppLocation(tBaseStorageAreaLocation);
                //锁定库存
                AppStock tMiStock3 = new AppStock();
                tMiStock3.setVehicleId(transferCtl);
                tMiStock3.setStockStatus(AppConstants.LOCATION_STATUS_DISABLE);
                appStockService.updateSts(tMiStock3);

            }
        }
        //设置库存里面的出库数量

        for (String key : map.keySet()) {
            BigDecimal requiredNum = map.get(key);
            BigDecimal totalNum = BigDecimal.ZERO;
            for (AppStock tMiStock1 : appStocks) {
                if (tMiStock1.getGoodsId().equals(key)) {
                    BigDecimal availableStock = tMiStock1.getOriginNum(); // 当前库存数量
                    totalNum = totalNum.add(tMiStock1.getOriginNum());
                    // 判断是否达到或者超过所需出库数量
                    if (totalNum.compareTo(requiredNum) >= 0) {
                        // 如果累加的数量已经达到或超过所需数量
                        BigDecimal excess = totalNum.subtract(requiredNum); // 超出的数量
                        tMiStock1.setPackingNum(availableStock.subtract(excess)); // 设置本次出库的数量
                        break; // 不再继续循环，已经处理完所需的数量
                    } else {
                        // 如果当前库存不足以满足所需出库数量
                        tMiStock1.setPackingNum(availableStock); // 设置出库的数量为当前库存
                    }
                }
            }
        }
        boolean isExist = false;
        for (AppStock tMiStock1 : appStocks) {
            if(tMiStock1.getPackingNum() != null) {
                if (tMiStock1.getOriginNum().compareTo(tMiStock1.getPackingNum()) > 0) {
                    isExist = true;
                    break;
                }
            }

        }
        //CkType ： 1.零捡 2：全量 3移库
        //boxtype：1：不需要出库 2：零捡 3：全出
        if (isExist) {
            appStocks.forEach(e -> {
                e.setCkType(1);
            });
        } else {
            appStocks.forEach(e -> {
                e.setCkType(2);
            });
        }
        //是否需要冻结库存
        //更新库存
        for (AppStock tMiStock1 : appStocks) {
            tMiStock1.setUpdateTime(new Date());
            tMiStock1.setStockStatus(AppConstants.LOCATION_STATUS_DISABLE);
            appStockService.updateAppStock(tMiStock1);
        }
        //创建出库任务
        for (AppStock tMiStock1 : appStocks) {
            if(tMiStock1.getPackingNum() != null) {
                String code = OrderCodeFactory.getOrderCode("CK", "");
                AppTask appTask = new AppTask();
                appTask.setGoodsId(tMiStock1.getGoodsId());
                //图号
                appTask.setVehicleId(tMiStock1.getVehicleId());
                appTask.setTaskStatus(AppConstants.LOCATION_STATUS_ENABLE);
                appTask.setTaskType(AppConstants.TASK_TYPE_OUT);
                appTask.setTaskId(code);
                appTask.setOrigin(tMiStock1.getLocationId());
                appTask.setLocationId(tMiStock1.getLocationId());
                appTask.setOpNum(tMiStock1.getPackingNum());
                appTask.setStockNum(tMiStock1.getOriginNum());
                appTask.setCkType(tMiStock1.getCkType());

                appTaskService.insertAppTask(appTask);
            }

        }
    }
    /**
     * 请求出库
     * @param outRequest 出库请求
     * @return 结果
     */
    @ApiOperation("请求出库")
    @PostMapping("/createOutRequest")
    @Transactional(rollbackFor = Exception.class)
    @Anonymous
    public AjaxResult createOutRequest(@RequestBody TaskOutRequest outRequest)
    {
        logger.info("请求出库：{}", JSON.toJSONString(outRequest));
        // 判断请求数据完整性
        if (outRequest == null || StringUtils.isEmpty(outRequest.getGoodsId())
        || outRequest.getNeedNum() == null || outRequest.getNeedNum().compareTo(BigDecimal.ZERO) <= 0) {
            return error("请求参数不完整。");
        }
        handleOutRequest(outRequest);
//        if (totalNeedNum.compareTo(outRequest.getNeedNum()) == 0) {
//            // 没有库存
//            return error("没有库存");
//        } else if (totalNeedNum.compareTo(BigDecimal.ZERO) > 0) {
//            return error("库存不足");
//        } else {
//            return success("处理出库请求成功，并已生成出库任务。");
//        }
        return success("处理出库请求成功，并已生成出库任务。");
    }

    private void handleOutRequest(TaskOutRequest outRequest) {
        // 根据需求查询库存（正常）
        AppStock stockQuery = new AppStock();
        stockQuery.setGoodsId(outRequest.getGoodsId());
        stockQuery.setStockStatus(0);
        List<AppStock> appStocks = appStockService.selectAppStockList(stockQuery);
        BigDecimal totalNeedNum = outRequest.getNeedNum();
        for (AppStock appStock : appStocks) {
            // 需求够了
            if (totalNeedNum.compareTo(BigDecimal.ZERO) <= 0) {
                break;
            }
            AppLocation moveLocation = outerLocation(appStock.getLocationId());
            String preTaskId = "";
            AppTask moveTask = new AppTask();
            if (moveLocation != null) {
                if (StringUtils.isEmpty(moveLocation.getLocationId())) {
                    continue;
                }
                // 查询这个位置有没有任务
                AppTask inTaskQuery = new AppTask();
                inTaskQuery.setDestination(moveLocation.getLocationId());
                List<AppTask> inTasks = appTaskService.selectAppTaskList(inTaskQuery);
                if (inTasks != null && !inTasks.isEmpty()) {
                    moveTask.setPreTask(inTasks.get(0).getTaskId());
                    preTaskId = IdUtils.fastUUID();
                } else {
                    // 判断origin
                    AppTask outTaskQuery = new AppTask();
                    outTaskQuery.setOrigin(moveLocation.getLocationId());
                    List<AppTask> outTasks = appTaskService.selectAppTaskList(outTaskQuery);
                    if (outTasks == null || outTasks.isEmpty()) {
                        preTaskId = IdUtils.fastUUID();
                    }
                }
                // 需要创建移库任务
                if (StringUtils.isNotEmpty(preTaskId)) {
                    AppLocation moveDestination = appLocationService.requestLocation(moveLocation.getEquipmentId());
                    if (moveDestination == null) {
                        continue;
                    }
                    // 创建移库任务
                    moveTask.setTaskId(IdUtils.fastUUID());
                    moveTask.setTaskType(3);
                    moveTask.setTaskStatus(0);
                    moveTask.setTaskPriority(1);
                    moveTask.setVehicleId(moveLocation.getVehicleId());
                    moveTask.setOrigin(moveLocation.getLocationId());
                    moveTask.setDestination(moveDestination.getLocationId());
                    moveTask.setCreateTime(new Date());
                    moveTask.setOpUser("system");
                    appTaskService.insertAppTask(moveTask);
                    moveDestination.setIsWorking(1);
                    moveDestination.setLocationStatus(1);
                    moveDestination.setVehicleId(moveLocation.getVehicleId());
                    appLocationService.updateAppLocation(moveDestination);
                }
            }
            // 计算需求
            BigDecimal opNum;
            BigDecimal stockNum = appStock.getRemainNum();
            if (appStock.getRemainNum().compareTo(totalNeedNum) >= 0) {
                opNum = totalNeedNum;
                totalNeedNum = BigDecimal.ZERO;
                appStock.setRemainNum(appStock.getRemainNum().subtract(totalNeedNum));
            } else {
                opNum = appStock.getRemainNum();
                totalNeedNum = totalNeedNum.subtract(appStock.getRemainNum());
                appStock.setRemainNum(BigDecimal.ZERO);
            }
            appStock.setStockStatus(1);// 设置状态出库中
            // 生成出库任务，并将此任务的preTask设置为移库任务
            AppTask outTask = new AppTask();
            outTask.setTaskId(IdUtils.fastUUID());
            outTask.setTaskType(2);
            outTask.setTaskStatus(0);
            outTask.setTaskPriority(1);
            outTask.setVehicleId(appStock.getVehicleId());
            outTask.setOrigin(appStock.getLocationId());
            if(StringUtils.isNotEmpty(outRequest.getStand())) {
                outTask.setDestination(outRequest.getStand());
            }
            outTask.setCreateTime(new Date());
            outTask.setGoodsId(appStock.getGoodsId());
            outTask.setOpNum(opNum);
            outTask.setStockNum(stockNum);
            outTask.setOpUser("");// TODO 需要设定
            outTask.setPreTask(preTaskId);
            outTask.setRemark(outRequest.getRemark());
            appTaskService.insertAppTask(outTask);
            // 更新库存
            appStockService.updateAppStock(appStock);
        }

    }

    /**
     * 判断是否需要生成移库任务
     * @param targetLocationId 目标库位
     * @return 结果
     */
    private AppLocation outerLocation(String targetLocationId) {
        AppLocation moveLocation = new AppLocation();
        // 查询到目标库位
        AppLocation targetLocation = appLocationService.selectAppLocationByLocationId(targetLocationId);
        if (targetLocation == null) {
            return null;
        }
        if (targetLocation.getwDepth() == 1) {
            // 深度1不需要移库
            return null;
        } else {
            // 判断深度为1的库位是否被占用
            AppLocation depth1LocationQuery = new AppLocation();
            depth1LocationQuery.setEquipmentId(targetLocation.getEquipmentId());
            depth1LocationQuery.setwLayer(targetLocation.getwLayer());
            depth1LocationQuery.setwRow(targetLocation.getwRow());
            depth1LocationQuery.setwCol(targetLocation.getwCol());
            depth1LocationQuery.setwDepth(1);
            List<AppLocation> depth1Locations = appLocationService.selectAppLocationList(depth1LocationQuery);
            if (depth1Locations == null || depth1Locations.isEmpty()) {
                return moveLocation;
            }
            AppLocation depth1Location = depth1Locations.get(0);
            if (depth1Location.getIsLock() == 1) {
                return moveLocation;
            }
            if (depth1Location.getLocationStatus() == 1) {
                return depth1Location;
            } else {
                return null;
            }
        }
    }

    /**
     * 请求载具码盘
     * @param otherStockInRequest 请求的数据
     * @return 请求结果
     */
    @Anonymous
    @PostMapping("/createInRequest")
    public AjaxResult createInRequest(@RequestBody OtherStockInRequest otherStockInRequest) {
        return _createInRequest(otherStockInRequest.getData(), otherStockInRequest.getVehicleNo());
    }

    private AjaxResult _createInRequest(List<AppPendingStorageRequest> appPendingStorageRequestList, String vehicleNo) {
        AppVehicle appVehicle = appVehicleService.selectAppVehicleByVehicleId(vehicleNo);
        if(appVehicle == null) {
            logger.error("载具{}查询数据库失败", vehicleNo);
            return error("数据服务异常，请重试");
        }
        if (appVehicle.getVehicleStatus() == 1) {
            logger.error("载具{}已经在库存中，请勿重复入库！", vehicleNo);
            return error("该托盘已经在库存中，请勿重复入库！");
        }
        AppTask taskQuery = new AppTask();
        taskQuery.setVehicleId(vehicleNo);
        List<AppTask> sameTaskList = appTaskService.selectAppTaskList(taskQuery);
        if (!sameTaskList.isEmpty()) {
            logger.error("载具{}存在其他任务，请勿重复入库！", vehicleNo);
            return error("该载具存在其他任务，请勿重复入库！");
        }
        for (AppPendingStorageRequest appPendingStorageRequest : appPendingStorageRequestList) {
            AppTask appTask = new AppTask();
            appTask.setTaskId("RK"+System.currentTimeMillis());
            appTask.setWcsTaskId("RK"+System.currentTimeMillis());
            appTask.setTaskType(1);
            appTask.setTaskStatus(0);
            appTask.setOrigin("-");
            appTask.setTaskPriority(1);
            appTask.setVehicleId(vehicleNo);
            appTask.setGoodsId(appPendingStorageRequest.getGoodsId());
            appTask.setOpNum(BigDecimal.valueOf(1));
            appTask.setOpUser("user");
            String destination = appLocationService.sendLocation();
            appTask.setDestination(destination);
            appTaskService.insertAppTask(appTask);

            AppLocation location_update = new AppLocation();
            location_update.setLocationStatus(1);
            location_update.setLocationId(destination);
            location_update.setUpdateTime(new Date());
            appLocationService.updateAppLocation(location_update);
        }
        appVehicle.setIsEmpty(0L);
        appVehicle.setVehicleStatus(1L);
        appVehicle.setLastInTime(new Date());
        appVehicleService.updateAppVehicle(appVehicle);
        return AjaxResult.success("创建入库任务成功");
    }

    /**
     * 获取取货任务
     * @param vehicleNo 载具号
     * @return 结果
     */
    @Anonymous
    @GetMapping("/getPickTask")
    public AjaxResult getPickTask(@RequestParam("vehicleNo") String vehicleNo) {
        if(StringUtils.isEmpty(vehicleNo)) {
            return error("载具号不能为空");
        }
        AppTask selectVehicleTask = new AppTask();
        selectVehicleTask.setVehicleId(vehicleNo);
        selectVehicleTask.setTaskStatus(4);
        List<AppTask> selectedAppTaskList = appTaskService.selectAppTaskList(selectVehicleTask);
        if (selectedAppTaskList == null) {
            return error("数据服务异常，请重试");
        }
        return success(selectedAppTaskList);
    }

    @Anonymous
    @PostMapping("/pickComplete")
    public AjaxResult pickComplete(@RequestBody List<PickCompleteReq> requests) {
        for(PickCompleteReq request : requests) {
            if(request == null || StringUtils.isEmpty(request.getTaskId()) || request.getPickNum() == null) {
                return error("请求参数不能为空");
            }
            if(request.getPickNum().compareTo(BigDecimal.ZERO) <= 0) {
                return error("捡货数量必须大于0");
            }
            // 检查这个taskId是否存在
            AppTask selectTask = appTaskService.selectAppTaskByTaskId(request.getTaskId());
            if (selectTask == null) {
                return error("数据服务异常，请重试");
            }
            if (selectTask.getTaskType() != 2) {
                return error("该任务不是拣货任务，请检查！");
            }
            if (selectTask.getTaskStatus() != 4) {
                return error("该任务状态不是待捡货，请检查！");
            }
        }
        for(PickCompleteReq request : requests) {
            // 更新捡货任务数量
            AppTask updatePickNum = new AppTask();
            updatePickNum.setTaskId(request.getTaskId());
            updatePickNum.setOpNum(request.getPickNum());
            updatePickNum.setTaskStatus(5);
            updatePickNum.setOpUser(request.getPicker());
            int updateAppTask = appTaskService.updateAppTask(updatePickNum);
            if (updateAppTask == 0) {
                return error("数据服务异常，请重试");
            }
        }
        return success("捡货成功");
    }
}
