package com.wms_main.service.quartz_job.job_executor;

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.wcs.WcsStackerTaskTypeEnums;
import com.wms_main.constant.enums.wms.WmsStackerTaskStatusEnums;
import com.wms_main.constant.enums.wms.WmsStockStatusEnums;
import com.wms_main.constant.enums.wms.WmsTaskTypeEnums;
import com.wms_main.constant.enums.wms.WmsVehicleStatusEnums;
import com.wms_main.dao.ITAppLocationService;
import com.wms_main.dao.ITAppTaskService;
import com.wms_main.dao.ITAppWcsTaskService;
import com.wms_main.model.bo.wcs.WcsStackerTask;
import com.wms_main.model.dto.response.wcs.WcsApiResponse;
import com.wms_main.model.po.*;
import com.wms_main.repository.utils.StringUtils;
import com.wms_main.repository.utils.UUIDUtils;
import com.wms_main.service.business.IStackerTaskService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


/**
 * 定时任务定义类
 */
@Slf4j
@PersistJobDataAfterExecution
// 以下注解用于实现fixed_delay
@DisallowConcurrentExecution
@RequiredArgsConstructor
public class WmsBackTaskAnalysis implements Job {
    private final IStackerTaskService stackerTaskService;// 堆垛机任务服务
    private final ITAppTaskService appWmsTaskService;// wms任务服务
    private final ITAppLocationService appLocationService;// 库位服务

    /**
     * Wcs任务服务
     */
    private final ITAppWcsTaskService appWcsTaskService;

    /**
     * 运行定时任务
     * 将WMS中TEMP的任务进行解析
     *
     * @param jobExecutionContext 定时任务执行的环境（上下文）
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        // 查询所有状态为TEMP的wms任务
        List<TAppTask> wmsTasks = appWmsTaskService.list(
                new LambdaQueryWrapper<TAppTask>()
                        .eq(TAppTask::getTaskType, WmsTaskTypeEnums.IN.getCode())
                        .eq(TAppTask::getTaskStatus, WmsStackerTaskStatusEnums.JOB.getCode())
        );
        if(!wmsTasks.isEmpty()){
            executeStackerInTask(wmsTasks);// 解析入库任务
        }
    }

    public void executeStackerInTask(List<TAppTask> wmsTasks) {
        for (TAppTask task : wmsTasks) {
            // 查询是否已经有对应wcs任务
            List<TAppWcsTask> wcsTasks = appWcsTaskService.list(
                    new LambdaQueryWrapper<TAppWcsTask>()
                            .eq(TAppWcsTask::getVehicleId, task.getVehicleId())
                            .eq(TAppWcsTask::getWcsTaskType, WcsStackerTaskTypeEnums.IN.getCode())
                            .ne(TAppWcsTask::getWcsTaskStatus, WcsStackerTaskStatusEnums.FINISH.getCode()));

            if (wcsTasks != null && !wcsTasks.isEmpty()) {
                WcsStackerTask wcsStackerTask = new WcsStackerTask(
                        wcsTasks.getFirst().getWcsTaskId(),
                        wcsTasks.getFirst().getWcsTaskType(),
                        wcsTasks.getFirst().getVehicleId(),
                        wcsTasks.getFirst().getOrigin(),
                        wcsTasks.getFirst().getDestination(),
                        "WMS"
                );
                log.info("载具请求入库成功。{}", wcsStackerTask);
                continue;
            }
            // 判断是否已经分配库位
            String locationId = "";

            if (StringUtils.isNotEmpty(task.getDestination())) {
                locationId = task.getDestination();
            }
            String stackerNumber = "";
            if (StringUtils.isEmpty(locationId)) {
                // 需要申请库位
                TAppLocation targetLocation = stackerTaskService.requestOneLocation(null, task.getVehicleId());
                locationId = targetLocation.getLocationId();
                stackerNumber = String.valueOf(targetLocation.getEquipmentId());
            }else{
                if (locationId.startsWith("A") && locationId.contains("-")) {
                    try {
                        // 提取排号(紧跟在A后面的数字)
                        String rowNumberStr = locationId.substring(1, locationId.indexOf('-'));
                        int rowNumber = Integer.parseInt(rowNumberStr);
                        // 计算堆垛机编号: 1,2→1; 3,4→2; 5,6→3...
                        stackerNumber = String.valueOf((rowNumber + 1) / 2);
                    } catch (Exception e) {
                        log.warn("解析库位编码失败: {}", locationId);
                    }
                }

            }
            // 起点规则：SC+堆垛机编号+库前/库后
            String callStand = task.getOrigin();
            String locationByUse = "";
            if (callStand != null && callStand.length() >= 3) {
                String location = callStand.substring(1, 2); // 提取中间一位库前/库后编号
                // 如果location是1则改为2，如果是2则改为1
                if ("1".equals(location)) {
                    location = "2";
                } else if ("2".equals(location)) {
                    location = "1";
                }
                //wcsOutTask.setDestination("SC" + stackerNumber + location);
                locationByUse = "SC" + stackerNumber + location;
            }
            // 解析wms任务以获得wcs任务
            TAppWcsTask wcsInTask = new TAppWcsTask();
            wcsInTask.setWcsTaskId(UUIDUtils.getNewUUID());
            wcsInTask.setWcsTaskType(WcsStackerTaskTypeEnums.IN.getCode());
            wcsInTask.setWcsTaskStatus(WcsStackerTaskStatusEnums.INIT.getCode());
            wcsInTask.setTaskPriority(task.getTaskPriority());
            wcsInTask.setOrigin(locationByUse);
            wcsInTask.setDestination(locationId);
            wcsInTask.setVehicleId(task.getVehicleId());
            wcsInTask.setCreateTime(LocalDateTime.now());
            wcsInTask.setSendTime(LocalDateTime.now());
            // 实时返回的任务
            WcsStackerTask wcsStackerTask = new WcsStackerTask(
                    wcsInTask.getWcsTaskId(),
                    wcsInTask.getWcsTaskType(),
                    wcsInTask.getVehicleId(),
                    wcsInTask.getOrigin(),
                    wcsInTask.getDestination(),
                    "WMS"
            );
            try {
                // 更新wmsTask
                appWmsTaskService.update(
                        new LambdaUpdateWrapper<TAppTask>()
                                .set(TAppTask::getTaskStatus, WmsStackerTaskStatusEnums.SEND.getCode())
                                .set(TAppTask::getWcsTaskId, wcsInTask.getWcsTaskId())
                                .set(TAppTask::getDestination, locationId)
                                .eq(TAppTask::getVehicleId, task.getVehicleId())
                                .eq(TAppTask::getTaskType, WmsTaskTypeEnums.IN.getCode())
                                .eq(TAppTask::getTaskStatus, WmsStackerTaskStatusEnums.JOB.getCode())
                );
                // 存储wcsTask
                appWcsTaskService.save(wcsInTask);
                log.info("载具请求入库成功。{}", wcsStackerTask);
            } catch (Exception e) {
                // 回滚事务
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                // 恢复库位空闲
                appLocationService.update(new LambdaUpdateWrapper<TAppLocation>()
                        .set(TAppLocation::getIsOccupy, 0)
                        .set(TAppLocation::getVehicleId, "")
                        .eq(TAppLocation::getLocationId, locationId));
                log.error("载具请求入库发生异常。{}", wcsStackerTask);
            }
        }
    }
}
