package com.wms_main.service.quartz_job.job_executor;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wms_main.constant.enums.wms.WmsStackerTaskStatusEnums;
import com.wms_main.constant.enums.wms.WmsTaskTypeEnums;
import com.wms_main.dao.ITAppTaskService;
import com.wms_main.model.po.TAppTask;
import com.wms_main.repository.utils.StringUtils;
import com.wms_main.service.business.IStackerTaskService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;

import java.util.*;

/**
 * 定时任务定义类---堆垛机任务完成类
 */
@Slf4j
@PersistJobDataAfterExecution
// 以下注解用于实现fixed_delay
@DisallowConcurrentExecution
@RequiredArgsConstructor
public class WmsTaskFinisher implements Job {
    /**ˉ
     * Wms任务服务
     */
    private final ITAppTaskService appTaskService;
    /**
     * 堆垛机任务业务服务
     */
    private final IStackerTaskService stackerTaskService;

    /**
     * 运行定时任务
     * 完成堆垛机任务
     *
     * @param jobExecutionContext 定时任务执行的环境（上下文）
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        // 获取到所有已完成的任务
        List<TAppTask> waitFinishWmsTaskList = appTaskService.list(
                new LambdaQueryWrapper<TAppTask>()
                        .eq(TAppTask::getTaskStatus, WmsStackerTaskStatusEnums.FINISH.getCode())
        );
        // 筛选入库任务
        List<TAppTask> stackerInTasks = waitFinishWmsTaskList.stream()
                .filter(task -> Objects.equals(WmsTaskTypeEnums.IN.getCode(), task.getTaskType()))
                .toList();
        if (!stackerInTasks.isEmpty()) {
            try {
                stackerTaskService.finishStackerInTasks(stackerInTasks);// 完成入库任务
            } catch (Exception e) {
                log.error("堆垛机任务完成类-入库执行异常：{}", StringUtils.objectToString(e));
            }
        }
        // 筛选入库任务
        List<TAppTask> stackerOutTasks = waitFinishWmsTaskList.stream()
                .filter(task -> Objects.equals(WmsTaskTypeEnums.OUT.getCode(), task.getTaskType()))
                .toList();
        if (!stackerOutTasks.isEmpty()) {
            try {
                stackerTaskService.finishStackerOutTasks(stackerOutTasks);// 完成出库任务
            } catch (Exception e) {
                log.error("堆垛机任务完成类-出库执行异常：{}", StringUtils.objectToString(e));
            }
        }
    }
}
