package com.multictrl.modules.job.task;

import cn.hutool.json.JSONObject;
import com.multictrl.common.constant.BusinessConstant;
import com.multictrl.common.utils.CacheUtils;
import com.multictrl.common.utils.JsonUtils;
import com.multictrl.common.utils.Utils;
import com.multictrl.modules.business.dto.flight.FlightExecute;
import com.multictrl.modules.business.service.FlightTaskService;
import com.multictrl.modules.business.service.RouteFlightService;
import com.multictrl.modules.job.dto.ScheduleJobDTO;
import com.multictrl.modules.job.entity.ScheduleJobEntity;
import com.multictrl.modules.job.service.ScheduleJobService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 航线任务
 *
 * @author Sdy
 * @since 1.0.0 2026/5/28
 */
@Slf4j
@Component("routeTask")
@RequiredArgsConstructor
public class RouteTask implements ITask {
    private final ScheduleJobService scheduleJobService;
    private final RouteFlightService routeFlightService;
    private final FlightTaskService flightTaskService;

    @Override
    public void run(String params) {
        JSONObject jsonObject = JsonUtils.parseObject(params, JSONObject.class);
        if (jsonObject == null) {
            log.error("计划飞行任务无效，拒绝执行:{}", params);
            return;
        }
        Long jobId = jsonObject.getLong("jobId");
        Integer cronType = jsonObject.getInt("cronType");
        if (cronType == 1) {
            //一次性任务 执行完失效 不然初始化job会因为时间过期而报错
            ScheduleJobEntity scheduleJobEntity = new ScheduleJobEntity();
            scheduleJobEntity.setStatus(-1);
            scheduleJobEntity.setId(jobId);
            scheduleJobService.updateById(scheduleJobEntity);
        }
        ScheduleJobDTO dto = scheduleJobService.get(jobId);
        String dockSn = dto.getDockSn();
        //执行任务
        FlightExecute flightExecute = new FlightExecute();
        flightExecute.setRouteId(Long.parseLong(dto.getParams()));
        routeFlightService.flightExecute(dockSn, flightExecute, false);
        //添加日志
        Utils.sleep(1000);
        String taskId = (String) CacheUtils.get(BusinessConstant.WORKING_TASK_ID + dockSn);
        flightTaskService.addJobRouteTask(taskId, jobId);
    }
}
