package com.wms_main.service.quartz_job.job_executor;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wms_main.constant.enums.wcs.WcsStackerTaskStatusEnums;
import com.wms_main.constant.enums.wcs.WcsStackerTaskTypeEnums;
import com.wms_main.constant.enums.wms.WmsStackerTaskStatusEnums;
import com.wms_main.constant.enums.wms.WmsTaskTypeEnums;
import com.wms_main.dao.ITAppOrderInService;
import com.wms_main.dao.ITAppTaskService;
import com.wms_main.dao.ITAppWcsTaskService;
import com.wms_main.model.po.TAppOrderIn;
import com.wms_main.model.po.TAppTask;
import com.wms_main.model.po.TAppWcsTask;
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;

    private final ITAppOrderInService appOrderInService;

    private final ITAppWcsTaskService appWcsTaskService;

    /**
     * 运行定时任务
     * 完成堆垛机任务
     *
     * @param jobExecutionContext 定时任务执行的环境（上下文）
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        // 获取到所有待下发的任务

       // 入库单
        try {
            List<TAppOrderIn> orderIns = appOrderInService.list();
            if(orderIns != null && !orderIns.isEmpty()) {
                stackerTaskService.finishStackerInTasks(orderIns);// 完成入库任务
            }
        } catch (Exception e) {
            log.error("堆垛机任务完成类-入库执行异常：{}", StringUtils.objectToString(e));
        }
        // 出库
        List<TAppWcsTask> waitFinishWcsTaskList = appWcsTaskService.list(
                new LambdaQueryWrapper<TAppWcsTask>()
                        .eq(TAppWcsTask::getWcsTaskStatus, WcsStackerTaskStatusEnums.FINISH.getCode())
        );
        List<TAppWcsTask> stackerOutTasks = waitFinishWcsTaskList.stream()
                .filter(task -> Objects.equals(WcsStackerTaskTypeEnums.OUT.getCode(), task.getWcsTaskType()))
                .toList();
        if (!stackerOutTasks.isEmpty()) {
            try {
                stackerTaskService.finishStackerOutTasks(stackerOutTasks);// 完成出库任务
            } catch (Exception e) {
                log.error("堆垛机任务完成类-出库执行异常：{}", StringUtils.objectToString(e));
            }
        }
    }
}
