package org.wcs.serve.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.wcs.business.pub.ReportStandard;
import org.wcs.business.stock.LocationManage;
import org.wcs.constant.ConstantData;
import org.wcs.constant.enums.business.LocationTypeEnum;
import org.wcs.constant.enums.common.TrueOrFalseEnum;
import org.wcs.constant.enums.database.StockComposeTaskStatusEnum;
import org.wcs.constant.enums.database.StockComposeTaskStepStatusEnum;
import org.wcs.constant.enums.database.StockComposeTaskTypeEnum;
import org.wcs.constant.enums.database.StockSingleTaskStatusEnum;
import org.wcs.constant.enums.http.StockCallBackStatusEnum;
import org.wcs.factory.AppServeResponseFactory;
import org.wcs.mapper.intf.AppStockComposeTaskBakService;
import org.wcs.mapper.intf.AppStockComposeTaskService;
import org.wcs.mapper.intf.AppStockSingleTaskService;
import org.wcs.model.bo.tuple.Tuple2;
import org.wcs.model.dto.serve.stcokComposeTask.AddStockComposeTaskReq;
import org.wcs.model.dto.serve.stcokComposeTask.QueryStockComposeTaskReq;
import org.wcs.model.dto.serve.stcokComposeTask.ReporterTaskStatusReq;
import org.wcs.model.po.app.AppStockComposeTask;
import org.wcs.model.po.app.AppStockComposeTaskBak;
import org.wcs.model.vo.serve.AppServeDataResponse;
import org.wcs.model.vo.serve.AppServeResponse;
import org.wcs.model.vo.serve.common.PageDataResponse;
import org.wcs.model.vo.serve.stockComposeTask.AppStockComposeTaskVo;
import org.wcs.model.vo.serve.stockComposeTask.CourseResultVo;
import org.wcs.model.vo.serve.stockComposeTask.ExportAppStockComposeTaskVo;
import org.wcs.plugin.excel.ExcelPoi;
import org.wcs.serve.service.intf.IStockComposeTaskService;
import org.wcs.utils.AppBeanUtils;
import org.wcs.utils.AppDataBaseTransUtils;
import org.wcs.utils.AppStringUtils;
import org.wcs.utils.AppUUIDUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class StockComposeTaskService implements IStockComposeTaskService {

    private final AppStockComposeTaskService stockComposeTaskService;
    private final AppStockComposeTaskBakService stockComposeTaskBakService;
    private final AppStockSingleTaskService stockSingleTaskService;
    private final ExcelPoi excelPoi;
    private final AppDataBaseTransUtils transUtils;
    private final LocationManage locationManage; // 位置管理

    /**
     * 条件查询组合式任务
     * @param queryTaskReq 查询条件
     * @param pageSize 每页大小
     * @param pageIndex 页码
     * @return 查询结果
     */
    @Override
    public AppServeDataResponse<PageDataResponse<AppStockComposeTaskVo>> query(QueryStockComposeTaskReq queryTaskReq, Integer pageSize, Integer pageIndex) {
        Tuple2<Long, List<AppStockComposeTask>> queryResult = stockComposeTaskService.query(queryTaskReq, pageSize, pageIndex);
        if(queryResult == null) {
            return AppServeResponseFactory.internalServerError("数据服务异常", null);
        }
        List<AppStockComposeTaskVo> queryResultVo = AppBeanUtils.copyListProperties(queryResult.getItem2(), AppStockComposeTaskVo::new);
        PageDataResponse<AppStockComposeTaskVo> pageDataResponse = new PageDataResponse<>();
        pageDataResponse.setPageIndex(pageIndex);
        pageDataResponse.setPageSize(pageSize);
        pageDataResponse.setTotalCount(queryResult.getItem1());
        pageDataResponse.setData(queryResultVo);
        return AppServeResponseFactory.success("查询成功", pageDataResponse);
    }

    /**
     * 条件查询组合式任务历史数据
     * @param queryTaskReq 查询条件
     * @param pageSize 每页大小
     * @param pageIndex 页码
     * @return 查询结果
     */
    @Override
    public AppServeDataResponse<PageDataResponse<AppStockComposeTaskVo>> queryBak(QueryStockComposeTaskReq queryTaskReq, Integer pageSize, Integer pageIndex) {
        Tuple2<Long, List<AppStockComposeTaskBak>> queryResult = stockComposeTaskBakService.query(queryTaskReq, pageSize, pageIndex);
        if(queryResult == null) {
            return AppServeResponseFactory.internalServerError("数据服务异常", null);
        }
        List<AppStockComposeTaskVo> queryResultVo = AppBeanUtils.copyListProperties(queryResult.getItem2(), AppStockComposeTaskVo::new);
        PageDataResponse<AppStockComposeTaskVo> pageDataResponse = new PageDataResponse<>();
        pageDataResponse.setPageIndex(pageIndex);
        pageDataResponse.setPageSize(pageSize);
        pageDataResponse.setTotalCount(queryResult.getItem1());
        pageDataResponse.setData(queryResultVo);
        return AppServeResponseFactory.success("查询成功", pageDataResponse);
    }

    /**
     * 下载组合式任务
     * @param response 响应
     * @param queryTaskReq 请求参数
     */
    @Override
    public void downLoadTask(HttpServletResponse response, QueryStockComposeTaskReq queryTaskReq) {
        List<AppStockComposeTask> queryResult = stockComposeTaskService.query(queryTaskReq);
        if(queryResult == null) {
            log.error("下载组合式任务失败，数据服务异常");
            return;
        }
        List<ExportAppStockComposeTaskVo> queryResultVo = new ArrayList<>();
        for (AppStockComposeTask appStockComposeTask : queryResult) {
            ExportAppStockComposeTaskVo exportAppStockComposeTaskVo = new ExportAppStockComposeTaskVo();
            exportAppStockComposeTaskVo.setTaskId(appStockComposeTask.getTaskId());
            exportAppStockComposeTaskVo.setTaskGroup(appStockComposeTask.getTaskGroup());
            exportAppStockComposeTaskVo.setUpperTaskId(AppStringUtils.isEmptyOr(appStockComposeTask.getUpperTaskId(), ""));
            exportAppStockComposeTaskVo.setTaskType(StockComposeTaskTypeEnum.getByCode(appStockComposeTask.getTaskType()).getMsg());
            exportAppStockComposeTaskVo.setOrigin(appStockComposeTask.getOrigin());
            exportAppStockComposeTaskVo.setDestination(appStockComposeTask.getDestination());
            exportAppStockComposeTaskVo.setTaskStatus(StockComposeTaskStatusEnum.getByCode(appStockComposeTask.getTaskStatus()).getMsg());
            exportAppStockComposeTaskVo.setStepStatus(StockComposeTaskStepStatusEnum.getByCode(appStockComposeTask.getStepStatus()).getMsg());
            exportAppStockComposeTaskVo.setCanCancel(TrueOrFalseEnum.getByCode(appStockComposeTask.getCanCancel()).getMsg());
            exportAppStockComposeTaskVo.setPriority(appStockComposeTask.getPriority());
            exportAppStockComposeTaskVo.setVehicleNo(appStockComposeTask.getVehicleNo());
            exportAppStockComposeTaskVo.setVehicleSize(appStockComposeTask.getVehicleSize());
            exportAppStockComposeTaskVo.setWeight(appStockComposeTask.getWeight());
            exportAppStockComposeTaskVo.setCreateTime(appStockComposeTask.getCreateTime());
            exportAppStockComposeTaskVo.setUpdateTime(appStockComposeTask.getUpdateTime());
            exportAppStockComposeTaskVo.setStartTime(appStockComposeTask.getStartTime());
            exportAppStockComposeTaskVo.setCompleteTime(appStockComposeTask.getCompleteTime());
            exportAppStockComposeTaskVo.setEndTime(appStockComposeTask.getEndTime());
            exportAppStockComposeTaskVo.setTaskSource(appStockComposeTask.getTaskSource());
            exportAppStockComposeTaskVo.setCreatePerson(appStockComposeTask.getCreatePerson());
            exportAppStockComposeTaskVo.setTaskMsg(appStockComposeTask.getTaskMsg());
            queryResultVo.add(exportAppStockComposeTaskVo);
        }
        if(queryResultVo.isEmpty()) {
            log.info("下载组合式任务失败，没有数据");
            return;
        }
        try {
            excelPoi.doWriteExcel("组合式任务下载", response, queryResultVo, ExportAppStockComposeTaskVo.class);
        } catch (Exception e) {
            log.error("下载组合式任务失败", e);
        }
    }

    /**
     * 下载组合式任务历史数据
     * @param response 响应
     * @param queryTaskReq 请求参数
     */
    @Override
    public void downLoadTaskBak(HttpServletResponse response, QueryStockComposeTaskReq queryTaskReq) {
        List<AppStockComposeTaskBak> queryResult = stockComposeTaskBakService.query(queryTaskReq);
        if(queryResult == null) {
            log.error("下载组合式任务失败，数据服务异常");
            return;
        }
        List<ExportAppStockComposeTaskVo> queryResultVo = new ArrayList<>();
        for (AppStockComposeTaskBak appStockComposeTask : queryResult) {
            ExportAppStockComposeTaskVo exportAppStockComposeTaskVo = new ExportAppStockComposeTaskVo();
            exportAppStockComposeTaskVo.setTaskId(appStockComposeTask.getTaskId());
            exportAppStockComposeTaskVo.setTaskGroup(appStockComposeTask.getTaskGroup());
            exportAppStockComposeTaskVo.setUpperTaskId(AppStringUtils.isEmptyOr(appStockComposeTask.getUpperTaskId(), ""));
            exportAppStockComposeTaskVo.setTaskType(StockComposeTaskTypeEnum.getByCode(appStockComposeTask.getTaskType()).getMsg());
            exportAppStockComposeTaskVo.setOrigin(appStockComposeTask.getOrigin());
            exportAppStockComposeTaskVo.setDestination(appStockComposeTask.getDestination());
            exportAppStockComposeTaskVo.setTaskStatus(StockComposeTaskStatusEnum.getByCode(appStockComposeTask.getTaskStatus()).getMsg());
            exportAppStockComposeTaskVo.setStepStatus(StockComposeTaskStepStatusEnum.getByCode(appStockComposeTask.getStepStatus()).getMsg());
            exportAppStockComposeTaskVo.setCanCancel(TrueOrFalseEnum.getByCode(appStockComposeTask.getCanCancel()).getMsg());
            exportAppStockComposeTaskVo.setPriority(appStockComposeTask.getPriority());
            exportAppStockComposeTaskVo.setVehicleNo(appStockComposeTask.getVehicleNo());
            exportAppStockComposeTaskVo.setVehicleSize(appStockComposeTask.getVehicleSize());
            exportAppStockComposeTaskVo.setWeight(appStockComposeTask.getWeight());
            exportAppStockComposeTaskVo.setCreateTime(appStockComposeTask.getCreateTime());
            exportAppStockComposeTaskVo.setUpdateTime(appStockComposeTask.getUpdateTime());
            exportAppStockComposeTaskVo.setStartTime(appStockComposeTask.getStartTime());
            exportAppStockComposeTaskVo.setCompleteTime(appStockComposeTask.getCompleteTime());
            exportAppStockComposeTaskVo.setEndTime(appStockComposeTask.getEndTime());
            exportAppStockComposeTaskVo.setTaskSource(appStockComposeTask.getTaskSource());
            exportAppStockComposeTaskVo.setCreatePerson(appStockComposeTask.getCreatePerson());
            exportAppStockComposeTaskVo.setTaskMsg(appStockComposeTask.getTaskMsg());
            queryResultVo.add(exportAppStockComposeTaskVo);
        }
        if(queryResultVo.isEmpty()) {
            log.info("下载组合式任务历史数据失败，没有数据");
            return;
        }
        try {
            excelPoi.doWriteExcel("组合式任务历史数据下载", response, queryResultVo, ExportAppStockComposeTaskVo.class);
        } catch (Exception e) {
            log.error("下载组合式任务历史数据失败", e);
        }
    }

    /**
     * 添加组合式任务
     * @param addTaskReq 添加任务数据
     * @return 结果
     */
    @Override
    public AppServeResponse addTask(AddStockComposeTaskReq addTaskReq) {
        Object userIdObj = StpUtil.getLoginId();
        if(userIdObj == null) {
            return AppServeResponseFactory.unauthorized("用户未登录");
        }
        String operationUserId = userIdObj.toString();
        log.info("用户：{} 想要添加组合式任务：{}", operationUserId, AppStringUtils.objectToString(addTaskReq));
        List<AppStockComposeTask> notCompleteTaskList = stockComposeTaskService.queryNotCompleteTask(addTaskReq.getVehicleNo());
        if(notCompleteTaskList == null) {
            return AppServeResponseFactory.internalServerError("数据服务异常");
        }
        if(!notCompleteTaskList.isEmpty()) {
            return AppServeResponseFactory.fail("当前载具有未完成的任务，请先完成未完成的任务");
        }
        AppStockComposeTask appStockComposeTask = new AppStockComposeTask();
        appStockComposeTask.setTaskId(AppUUIDUtils.getNewUUID());
        appStockComposeTask.setTaskGroup(AppUUIDUtils.getNewUUID());
        appStockComposeTask.setTaskType(addTaskReq.getTaskType());
        appStockComposeTask.setOrigin(addTaskReq.getOrigin());
        appStockComposeTask.setDestination(addTaskReq.getDestination());
        appStockComposeTask.setTaskStatus(StockComposeTaskStatusEnum.CREATE.getCode());
        appStockComposeTask.setStepStatus(StockComposeTaskStepStatusEnum.CREATE.getCode());
        appStockComposeTask.setCanCancel(TrueOrFalseEnum.TRUE.getCode());
        appStockComposeTask.setPriority(addTaskReq.getPriority());
        appStockComposeTask.setVehicleNo(addTaskReq.getVehicleNo());
        appStockComposeTask.setVehicleSize(addTaskReq.getVehicleSize());
        appStockComposeTask.setWeight(addTaskReq.getWeight());
        appStockComposeTask.setCreatePerson(operationUserId);
        appStockComposeTask.setTaskSource(ConstantData.SYSTEM_NAME);
        int insertResult = stockComposeTaskService.insert(appStockComposeTask);
        if(insertResult == 0) {
            return AppServeResponseFactory.internalServerError("数据服务异常");
        }
        return AppServeResponseFactory.success(String.format("添加成功，添加了 %d 条记录", insertResult));
    }

    /**
     * 取消组合式任务
     * @param taskId 任务ID
     * @return 结果
     */
    @Override
    public AppServeResponse cancelTask(String taskId) {
        if(AppStringUtils.isEmpty(taskId)) {
            return AppServeResponseFactory.fail("参数错误");
        }
        Object userIdObj = StpUtil.getLoginId();
        if(userIdObj == null) {
            return AppServeResponseFactory.unauthorized("用户未登录");
        }
        String operationUserId = userIdObj.toString();
        AppStockComposeTask appStockComposeTask = stockComposeTaskService.queryByTaskId(taskId);
        if(appStockComposeTask == null) {
            return AppServeResponseFactory.fail("任务不存在");
        }
        if(appStockComposeTask.getCanCancel() != TrueOrFalseEnum.TRUE.getCode()) {
            return AppServeResponseFactory.fail("任务不允许取消");
        }
        boolean updateResult = transUtils.useTran(() -> {
            // 更新组合任务表
            AppStockComposeTask appStockComposeTaskUpdater = new AppStockComposeTask();
            appStockComposeTaskUpdater.setTaskId(taskId);
            appStockComposeTaskUpdater.setTaskStatus(StockComposeTaskStatusEnum.CANCEL.getCode());
            appStockComposeTaskUpdater.setEndTime(LocalDateTime.now());
            appStockComposeTaskUpdater.setTaskMsg(String.format("用户：%s 取消任务", operationUserId));
            stockComposeTaskService.updateThrowEx(appStockComposeTaskUpdater);
            // 更新独立任务表
            stockSingleTaskService.updateWithUpperTaskIdAndStatusThrowEx(appStockComposeTask.getUpperTaskId(), StockSingleTaskStatusEnum.notFinishedCodes(), StockSingleTaskStatusEnum.CANCEL.getCode(), String.format("用户：%s 取消任务", operationUserId));
        });
        if(!updateResult) {
            return AppServeResponseFactory.fail("更新失败");
        }
        log.info("用户：{} 取消组合式任务：{}", operationUserId, taskId);
        return AppServeResponseFactory.success("取消成功");
    }

    /**
     * 完成组合式任务
     * @param taskId 载具ID
     * @return 结果
     */
    @Override
    public AppServeResponse completeTask(String taskId) {
        if(AppStringUtils.isEmpty(taskId)) {
            return AppServeResponseFactory.fail("参数错误");
        }
        Object userIdObj = StpUtil.getLoginId();
        if(userIdObj == null) {
            return AppServeResponseFactory.unauthorized("用户未登录");
        }
        String operationUserId = userIdObj.toString();
        AppStockComposeTask appStockComposeTask = stockComposeTaskService.queryByTaskId(taskId);
        if(appStockComposeTask == null) {
            return AppServeResponseFactory.fail("任务不存在");
        }

        boolean updateResult = transUtils.useTran(() -> {
            // 更新组合任务表
            AppStockComposeTask appStockComposeTaskUpdater = new AppStockComposeTask();
            appStockComposeTaskUpdater.setTaskId(taskId);
            appStockComposeTaskUpdater.setTaskStatus(StockComposeTaskStatusEnum.COMPLETE.getCode());
            appStockComposeTaskUpdater.setCompleteTime(LocalDateTime.now());
            appStockComposeTaskUpdater.setEndTime(LocalDateTime.now());
            appStockComposeTaskUpdater.setTaskMsg(String.format("用户：%s 完成任务", operationUserId));
            stockComposeTaskService.updateThrowEx(appStockComposeTaskUpdater);
            // 更新独立任务表
            stockSingleTaskService.updateWithUpperTaskIdAndStatusThrowEx(appStockComposeTask.getUpperTaskId(), StockSingleTaskStatusEnum.notFinishedCodes(), StockSingleTaskStatusEnum.COMPLETE.getCode(), String.format("用户：%s 完成任务", operationUserId));
        });
        if(!updateResult) {
            return AppServeResponseFactory.fail("更新失败");
        }
        log.info("用户：{} 完成组合式任务：{}", operationUserId, taskId);
        return AppServeResponseFactory.success("完成成功");
    }

    /**
     * 重置组合式任务
     * @param taskId 载具ID
     * @return 结果
     */
    @Override
    public AppServeResponse resetTask(String taskId) {
        if(AppStringUtils.isEmpty(taskId)) {
            return AppServeResponseFactory.fail("参数错误");
        }
        Object userIdObj = StpUtil.getLoginId();
        if(userIdObj == null) {
            return AppServeResponseFactory.unauthorized("用户未登录");
        }
        String operationUserId = userIdObj.toString();
        AppStockComposeTask appStockComposeTask = stockComposeTaskService.queryByTaskId(taskId);
        if(appStockComposeTask == null) {
            return AppServeResponseFactory.fail("任务不存在");
        }

        boolean updateResult = transUtils.useTran(() -> {
            // 更新组合任务表
            AppStockComposeTask appStockComposeTaskUpdater = new AppStockComposeTask();
            appStockComposeTaskUpdater.setTaskId(taskId);
            appStockComposeTaskUpdater.setTaskStatus(StockComposeTaskStatusEnum.CREATE.getCode());
            appStockComposeTaskUpdater.setTaskMsg(String.format("用户：%s 要求重做任务", operationUserId));
            stockComposeTaskService.updateThrowEx(appStockComposeTaskUpdater);
            // 更新独立任务表
            stockSingleTaskService.updateWithUpperTaskIdAndStatusThrowEx(appStockComposeTask.getUpperTaskId(), StockSingleTaskStatusEnum.notFinishedCodes(), StockSingleTaskStatusEnum.ERROR.getCode(), String.format("用户：%s 要求重做任务", operationUserId));
        });
        if(!updateResult) {
            return AppServeResponseFactory.fail("更新失败");
        }
        log.info("用户：{} 重做组合式任务：{}", operationUserId, taskId);
        return AppServeResponseFactory.success("重做成功");
    }

    /**
     * 组合式任务状态完成上报
     * @param reporterTaskStatusReq 上报信息
     * @return 结果
     */
    @Override
    public AppServeResponse reporterTaskCompleted(ReporterTaskStatusReq reporterTaskStatusReq) {
        Object userIdObj = StpUtil.getLoginId();
        if(userIdObj == null) {
            return AppServeResponseFactory.unauthorized("用户未登录");
        }
        String operationUserId = userIdObj.toString();
        AppStockComposeTask appStockComposeTask = stockComposeTaskService.queryByTaskId(reporterTaskStatusReq.getTaskId());
        if(appStockComposeTask == null) {
            return AppServeResponseFactory.fail("任务不存在");
        }
        if(AppStringUtils.isNotEmpty(reporterTaskStatusReq.getDestination().trim())) {
            appStockComposeTask.setDestination(reporterTaskStatusReq.getDestination());
        }
        Tuple2<String, String> taskFinish = ReportStandard.stockTaskReport(StockCallBackStatusEnum.FINISH, appStockComposeTask, operationUserId + "#" + reporterTaskStatusReq.getMessage());
        if(taskFinish.getItem1() != null) {
            log.info("任务完成上报失败，组合任务ID：{}，错误信息：{}", appStockComposeTask.getTaskId(), taskFinish.getItem1());
            return AppServeResponseFactory.fail(taskFinish.getItem1());
        }
        log.info("任务完成上报成功，组合任务ID：{}，返回信息：{}", appStockComposeTask.getTaskId(), taskFinish.getItem2());
        return AppServeResponseFactory.success("上报成功");
    }

    /**
     * 组合式任务状态取消上报
     * @param reporterTaskStatusReq 上报信息
     * @return 结果
     */
    @Override
    public AppServeResponse reporterTaskCancel(ReporterTaskStatusReq reporterTaskStatusReq) {
        Object userIdObj = StpUtil.getLoginId();
        if(userIdObj == null) {
            return AppServeResponseFactory.unauthorized("用户未登录");
        }
        String operationUserId = userIdObj.toString();
        AppStockComposeTask appStockComposeTask = stockComposeTaskService.queryByTaskId(reporterTaskStatusReq.getTaskId());
        if(appStockComposeTask == null) {
            return AppServeResponseFactory.fail("任务不存在");
        }
        Tuple2<String, String> taskFinish = ReportStandard.stockTaskReport(StockCallBackStatusEnum.CANCEL, appStockComposeTask, operationUserId + "#" + reporterTaskStatusReq.getMessage());
        if(taskFinish.getItem1() != null) {
            log.info("任务取消上报失败，组合任务ID：{}，错误信息：{}", appStockComposeTask.getTaskId(), taskFinish.getItem1());
            return AppServeResponseFactory.fail(taskFinish.getItem1());
        }
        log.info("任务取消上报成功，组合任务ID：{}，返回信息：{}", appStockComposeTask.getTaskId(), taskFinish.getItem2());
        return AppServeResponseFactory.success("上报成功");
    }

    /**
     * 组合式任务状态完成上报 ---- 历史数据
     * @param reporterTaskStatusReq 上报信息
     * @return 结果
     */
    @Override
    public AppServeResponse reporterTaskBakCompleted(ReporterTaskStatusReq reporterTaskStatusReq) {
        Object userIdObj = StpUtil.getLoginId();
        if(userIdObj == null) {
            return AppServeResponseFactory.unauthorized("用户未登录");
        }
        String operationUserId = userIdObj.toString();
        AppStockComposeTaskBak appStockComposeTask = stockComposeTaskBakService.queryByTaskId(reporterTaskStatusReq.getTaskId());
        if(appStockComposeTask == null) {
            return AppServeResponseFactory.fail("任务不存在");
        }
        if(AppStringUtils.isNotEmpty(reporterTaskStatusReq.getDestination().trim())) {
            appStockComposeTask.setDestination(reporterTaskStatusReq.getDestination());
        }
        AppStockComposeTask appStockComposeTaskUpper = new AppStockComposeTask();
        AppBeanUtils.copyProperties(appStockComposeTask, appStockComposeTaskUpper);
        Tuple2<String, String> taskFinish = ReportStandard.stockTaskReport(StockCallBackStatusEnum.FINISH, appStockComposeTaskUpper, operationUserId + "#" + reporterTaskStatusReq.getMessage());
        if(taskFinish.getItem1() != null) {
            log.info("历史数据任务完成上报失败，组合任务ID：{}，错误信息：{}", appStockComposeTask.getTaskId(), taskFinish.getItem1());
            return AppServeResponseFactory.fail(taskFinish.getItem1());
        }
        log.info("历史数据任务完成上报成功，组合任务ID：{}，返回信息：{}", appStockComposeTask.getTaskId(), taskFinish.getItem2());
        return AppServeResponseFactory.success("上报成功");
    }

    /**
     * 组合式任务状态取消上报 ---- 历史数据
     * @param reporterTaskStatusReq 上报信息
     * @return 结果
     */
    @Override
    public AppServeResponse reporterTaskBakCancel(ReporterTaskStatusReq reporterTaskStatusReq) {
        Object userIdObj = StpUtil.getLoginId();
        if(userIdObj == null) {
            return AppServeResponseFactory.unauthorized("用户未登录");
        }
        String operationUserId = userIdObj.toString();
        AppStockComposeTaskBak appStockComposeTask = stockComposeTaskBakService.queryByTaskId(reporterTaskStatusReq.getTaskId());
        if(appStockComposeTask == null) {
            return AppServeResponseFactory.fail("任务不存在");
        }
        if(AppStringUtils.isNotEmpty(reporterTaskStatusReq.getDestination().trim())) {
            appStockComposeTask.setDestination(reporterTaskStatusReq.getDestination());
        }
        AppStockComposeTask appStockComposeTaskUpper = new AppStockComposeTask();
        AppBeanUtils.copyProperties(appStockComposeTask, appStockComposeTaskUpper);
        Tuple2<String, String> taskFinish = ReportStandard.stockTaskReport(StockCallBackStatusEnum.CANCEL, appStockComposeTaskUpper, operationUserId + "#" + reporterTaskStatusReq.getMessage());
        if(taskFinish.getItem1() != null) {
            log.info("历史数据任务取消上报失败，组合任务ID：{}，错误信息：{}", appStockComposeTask.getTaskId(), taskFinish.getItem1());
            return AppServeResponseFactory.fail(taskFinish.getItem1());
        }
        log.info("历史数据任务取消上报成功，组合任务ID：{}，返回信息：{}", appStockComposeTask.getTaskId(), taskFinish.getItem2());
        return AppServeResponseFactory.success("上报成功");
    }

    /**
     * 查询任务路径结果
     * @param taskId 任务ID
     * @return 结果
     */
    @Override
    public AppServeDataResponse<List<CourseResultVo>> queryCourseResult(String taskId) {
        AppStockComposeTask stockComposeTask = stockComposeTaskService.queryByTaskId(taskId);
        if(stockComposeTask == null) {
            return AppServeResponseFactory.fail("任务不存在", null);
        }
        List<Tuple2<LocationTypeEnum, String>> courseCalculateResult = locationManage.courseCalculate(stockComposeTask.getOrigin(), stockComposeTask.getDestination());
        if(courseCalculateResult == null) {
            return AppServeResponseFactory.fail("无法计算路径", null);
        }
        List<CourseResultVo> courseResultVos = courseCalculateResult.stream().map(item -> {
            CourseResultVo courseResultVo = new CourseResultVo();
            courseResultVo.setLocation(item.getItem2());
            courseResultVo.setLocationType(item.getItem1().getDesc());
            return courseResultVo;
        }).toList();
        return AppServeResponseFactory.success("查询成功", courseResultVos);
    }


}
