package com.wms_main.service.controller.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wms_main.constant.enums.wcs.WcsStackerTaskStatusEnums;
import com.wms_main.constant.enums.wms.WmsStackerTaskStatusEnums;
import com.wms_main.dao.*;
import com.wms_main.model.dto.request.wms.OutsUpdateRequest;
import com.wms_main.model.dto.request.wms.WmsTaskRequest;
import com.wms_main.model.dto.response.wms.BaseWmsApiResponse;
import com.wms_main.model.po.*;
import com.wms_main.repository.utils.ConvertUtils;
import com.wms_main.repository.utils.StringUtils;
import com.wms_main.service.controller.ITaskOperationControllerService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * 任务操作控制类 服务实现
 */
@Service
@RequiredArgsConstructor
public class TaskOperationControllerServiceImpl implements ITaskOperationControllerService {
    private final ITAppTaskService appTaskService;// wms任务服务
    private final ITAppTaskBakService appTaskBakService;// wms任务记录服务
    private final ITAppWcsTaskService appWcsTaskService;// wcs任务服务
    private final ITAppWcsTaskBakService appWcsTaskBakService;// wcs任务记录服务
    private final ITAppOutsService appOutsService;// 出库单服务
    private final ITAppOutsRecordService appOutsRecordService;// 出库单记录服务
    private final ITAppPickPlanService appPickPlanService;// 拣选计划服务
    private final ITAppPickTaskService appPickTaskService;// 拣选任务服务

    /**
     * 删除wms任务
     *
     * @param wmsTaskRequest 请求参数
     * @return 删除结果
     */
    @Override
    public BaseWmsApiResponse deleteWmsTask(WmsTaskRequest wmsTaskRequest) {
        if (wmsTaskRequest == null) {
            return BaseWmsApiResponse.error("请求参数不能为NULL");
        }
        if (StringUtils.isEmpty(wmsTaskRequest.getTaskId())) {
            return BaseWmsApiResponse.error("请求参数不完整，缺少taskId。");
        }
        // 查询对应的任务
        List<TAppTask> tasks = appTaskService.list(new LambdaQueryWrapper<TAppTask>()
                .eq(TAppTask::getTaskId, wmsTaskRequest.getTaskId()));
        if (tasks == null || tasks.isEmpty()) {
            return BaseWmsApiResponse.error("未查询到对应的任务");
        }
        TAppTask targetTask = tasks.getFirst();
        return appTaskService.removeById(targetTask.getTaskId()) ? BaseWmsApiResponse.success("删除任务成功。") : BaseWmsApiResponse.error("删除任务失败。");
    }

    /**
     * 更新wms任务
     *
     * @param wmsTaskRequest 请求参数
     * @return 更新结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseWmsApiResponse updateWmsTask(WmsTaskRequest wmsTaskRequest) {
        if (wmsTaskRequest == null) {
            return BaseWmsApiResponse.error("请求参数不能为NULL");
        }
        if (StringUtils.isEmpty(wmsTaskRequest.getTaskId())) {
            return BaseWmsApiResponse.error("请求参数不完整，缺少taskId。");
        }
        // 查询对应的任务
        List<TAppTask> tasks = appTaskService.list(new LambdaQueryWrapper<TAppTask>()
                .eq(TAppTask::getTaskId, wmsTaskRequest.getTaskId()));
        if (tasks == null || tasks.isEmpty()) {
            return BaseWmsApiResponse.error("未查询到对应的任务");
        }
        TAppTask targetTask = tasks.getFirst();
        // 更新除任务状态之外的其他信息
        updateDetailInfoExceptStatus(targetTask, wmsTaskRequest);
        // 判断任务状态是否变更
        if (!Objects.equals(targetTask.getTaskStatus(), wmsTaskRequest.getTaskStatus())) {
            // 如果是取消任务
            if (Objects.equals(wmsTaskRequest.getTaskStatus(), WmsStackerTaskStatusEnums.CANCEL.getCode())) {
                // 判断当前任务状态是已发送、正在执行、已完成状态，那么不允许修改状态
                if (!Objects.equals(targetTask.getTaskStatus(), WmsStackerTaskStatusEnums.TEMP.getCode()) &&
                        !Objects.equals(targetTask.getTaskStatus(), WmsStackerTaskStatusEnums.WAIT.getCode())) {
                    return BaseWmsApiResponse.error("当前任务已生成wcs任务，如需取消，请先取消对应的wcs任务。");
                }
                // 将这个载具的任务删除，并存进备份表
                List<TAppTask> thisVehicleTasks = appTaskService.list(new LambdaQueryWrapper<TAppTask>()
                        .eq(TAppTask::getVehicleId, targetTask.getVehicleId())
                        .eq(TAppTask::getTaskType, targetTask.getTaskType()));
                List<TAppTaskBak> thisVehicleTasksBak = thisVehicleTasks.stream()
                        .map(task -> new TAppTaskBak(
                                task.getTaskId(),
                                task.getTaskType(),
                                WmsStackerTaskStatusEnums.CANCEL.getCode(),
                                task.getTaskPriority(),
                                task.getVehicleId(),
                                task.getOrigin(),
                                task.getDestination(),
                                task.getWcsTaskId(),
                                task.getCreateTime(),
                                task.getFinishTime(),
                                task.getGoodsId(),
                                task.getOpNum(),
                                task.getStockNum(),
                                task.getOpUser(),
                                task.getRemark(),
                                task.getCallStand(),
                                task.getGoodsDesc()
                        )).toList();
                if (appTaskService.removeByIds(thisVehicleTasks.stream().map(TAppTask::getTaskId).toList())) {
                    return appTaskBakService.saveBatch(thisVehicleTasksBak) ? BaseWmsApiResponse.success("取消任务成功。") : BaseWmsApiResponse.error("取消任务失败，添加任务记录失败。");
                } else {
                    return BaseWmsApiResponse.error("取消任务失败，删除任务失败。");
                }
            } else if (Objects.equals(wmsTaskRequest.getTaskStatus(), WmsStackerTaskStatusEnums.FINISH.getCode())) {
                // 将对应的wcs任务完成，并存进备份表
                List<TAppWcsTask> wcsTasks = appWcsTaskService.list(new LambdaQueryWrapper<TAppWcsTask>()
                        .eq(TAppWcsTask::getWcsTaskId, targetTask.getWcsTaskId()));
                if (wcsTasks != null && !wcsTasks.isEmpty()) {
                    TAppWcsTask wcsTask = wcsTasks.getFirst();
                    // 移除wcs任务，并向wcs备份表添加记录
                    TAppWcsTaskBak wcsTaskBak = new TAppWcsTaskBak(
                            wcsTask.getWcsTaskId(),
                            WcsStackerTaskStatusEnums.FINISH.getCode(),
                            wcsTask.getWcsTaskType(),
                            wcsTask.getTaskPriority(),
                            wcsTask.getVehicleId(),
                            wcsTask.getOrigin(),
                            wcsTask.getDestination(),
                            wcsTask.getCreateTime(),
                            wcsTask.getSendTime(),
                            wcsTask.getFinishTime(),
                            wmsTaskRequest.getUserName() + "手动完成"
                    );
                    appWcsTaskService.removeById(wcsTask.getWcsTaskId());
                    appWcsTaskBakService.save(wcsTaskBak);
                }
                // 更新这个箱子的任务为完成状态
                appTaskService.update(
                        new LambdaUpdateWrapper<TAppTask>()
                                .set(TAppTask::getTaskStatus, WmsStackerTaskStatusEnums.FINISH.getCode())
                                .eq(TAppTask::getTaskType, targetTask.getTaskType())
                                .eq(TAppTask::getVehicleId, targetTask.getVehicleId())
                );
                return BaseWmsApiResponse.success("完成任务成功。");
            } else {
                // 更新任务状态
                targetTask.setTaskStatus(wmsTaskRequest.getTaskStatus());
                // 更新任务信息
                appTaskService.updateById(targetTask);
                // 更新这个箱子其他任务的状态
                appTaskService.update(
                        new LambdaUpdateWrapper<TAppTask>()
                                .set(TAppTask::getTaskStatus, wmsTaskRequest.getTaskStatus())
                                .eq(TAppTask::getTaskType, targetTask.getTaskType())
                                .eq(TAppTask::getVehicleId, targetTask.getVehicleId())
                                .ne(TAppTask::getTaskId, targetTask.getTaskId())
                );
                // 转化wcs任务状态
                Integer wcsTaskStatus = ConvertUtils.convertWmsTaskStatusToWcsStackerTaskStatus(wmsTaskRequest.getTaskStatus());
                appWcsTaskService.update(new LambdaUpdateWrapper<TAppWcsTask>()
                        .set(TAppWcsTask::getWcsTaskStatus, wcsTaskStatus)
                        .eq(TAppWcsTask::getWcsTaskId, targetTask.getWcsTaskId()));
                return BaseWmsApiResponse.success("更新任务信息成功。");
            }
        } else {
            // 只更新数据
            return appTaskService.updateById(targetTask) ? BaseWmsApiResponse.success("更新任务信息成功。") : BaseWmsApiResponse.error("更新任务信息失败。");
        }
    }

    /**
     * 更新当前的出库单任务---取消或者完成
     *
     * @param outsUpdateRequest 请求
     * @return 处理结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseWmsApiResponse updateOutsTask(OutsUpdateRequest outsUpdateRequest) {
        // 校验参数
        if (outsUpdateRequest == null) {
            return BaseWmsApiResponse.error("请求参数不能为NULL。");
        }
        if (StringUtils.isEmpty(outsUpdateRequest.getTaskId())) {
            return BaseWmsApiResponse.error("请求缺少任务号taskId。");
        }
        if (outsUpdateRequest.getUpdateType() == null) {
            return BaseWmsApiResponse.error("请求缺少更新类型updateType。");
        }
        // 查询对应的出库单
        TAppOuts targetOuts = appOutsService.getById(outsUpdateRequest.getTaskId());
        if (targetOuts == null) {
            return BaseWmsApiResponse.error("未查询到对应的出库单。");
        }
        // 查询对应的pickPlan
        List<TAppPickPlan> pickPlansOfThisTask = appPickPlanService.list(new LambdaQueryWrapper<TAppPickPlan>()
                .eq(TAppPickPlan::getWorkIndex, targetOuts.getTaskId()));
        if (pickPlansOfThisTask != null && !pickPlansOfThisTask.isEmpty()) {
            // 查询这些plan包含的拣选任务
            List<TAppPickTask> pickTasksOfThisTask = appPickTaskService.list(new LambdaQueryWrapper<TAppPickTask>()
                    .eq(TAppPickTask::getPickStand, targetOuts.getDestination())
                    .in(TAppPickTask::getVehicleId, pickPlansOfThisTask.stream().map(TAppPickPlan::getVehicleId).distinct().toList()));
            if (pickTasksOfThisTask != null && !pickTasksOfThisTask.isEmpty()) {
                // 如果存在pickPlan且存在pickTask，那么不允许后续操作。
                return BaseWmsApiResponse.error("当前任务已经下发且未完成，不可进行后续操作。");
            }
        }
        // 根据不用的更新类型，进行操作
        if (outsUpdateRequest.getUpdateType() == 1) {// CANCEL
            // 移除这个出库单，并删除其对应的pickPlan
            appOutsService.removeById(targetOuts.getTaskId());
            appPickPlanService.remove(new LambdaQueryWrapper<TAppPickPlan>()
                    .eq(TAppPickPlan::getWorkIndex, targetOuts.getTaskId()));
        } else if (outsUpdateRequest.getUpdateType() == 2) {// FINISH
            // 移除这个出库单，生成记录，并删除对应的pickPlan
            appOutsService.removeById(targetOuts.getTaskId());
            appOutsRecordService.save(new TAppOutsRecord(
                    targetOuts.getTaskId(),
                    targetOuts.getGoodsId(),
                    targetOuts.getVehicleId(),
                    targetOuts.getNeedNum(),
                    targetOuts.getDistributeNum(),
                    targetOuts.getPickNum(),
                    targetOuts.getOutType(),
                    targetOuts.getDestination(),
                    targetOuts.getUserName(),
                    targetOuts.getReason(),
                    targetOuts.getRequestTime(),
                    targetOuts.getWorkOrder()
            ));
            appPickPlanService.remove(new LambdaQueryWrapper<TAppPickPlan>()
                    .eq(TAppPickPlan::getWorkIndex, targetOuts.getTaskId()));
        } else if (outsUpdateRequest.getUpdateType() == 3) {// REBOOT
            // 将已分配数量更改掉，并删除pickPlan
            targetOuts.setDistributeNum(targetOuts.getNeedNum() - targetOuts.getPickNum());
            appOutsService.updateById(targetOuts);
            appPickPlanService.remove(new LambdaQueryWrapper<TAppPickPlan>()
                    .eq(TAppPickPlan::getWorkIndex, targetOuts.getTaskId()));
        } else {
            return BaseWmsApiResponse.error("更新类型错误。");
        }
        return BaseWmsApiResponse.success("更新信息成功。");
    }

    /**
     * 更新详情
     *
     * @param targetTask     目标任务
     * @param wmsTaskRequest 请求信息
     */
    private void updateDetailInfoExceptStatus(TAppTask targetTask, WmsTaskRequest wmsTaskRequest) {
        targetTask.setTaskPriority(wmsTaskRequest.getTaskPriority());
        targetTask.setOrigin(wmsTaskRequest.getOrigin());
        targetTask.setDestination(wmsTaskRequest.getDestination());
        targetTask.setWcsTaskId(wmsTaskRequest.getWcsTaskId());
        targetTask.setGoodsId(wmsTaskRequest.getGoodsId());
        targetTask.setOpNum(wmsTaskRequest.getOpNum());
        targetTask.setStockNum(wmsTaskRequest.getStockNum());
        targetTask.setOpUser(wmsTaskRequest.getUserName());
        targetTask.setRemark(wmsTaskRequest.getRemark());
        targetTask.setGoodsDesc(wmsTaskRequest.getGoodsDesc());
    }
}
