package com.tuoheng.admin.service.third.airport.execute;

import cn.hutool.core.util.ObjectUtil;
import com.tuoheng.admin.dto.AirportDto;
import com.tuoheng.admin.entity.Inspection;
import com.tuoheng.admin.entity.InspectionHistory;
import com.tuoheng.admin.enums.InspectionStatusEnum;
import com.tuoheng.admin.mapper.InspectionHistoryMapper;
import com.tuoheng.admin.mapper.InspectionMapper;
import com.tuoheng.admin.mapper.TenantMapper;
import com.tuoheng.admin.tzhl.response.TZHLAirportLineResponse;
import com.tuoheng.admin.tzhl.service.airport.TZHLGetAirportListService;
import com.tuoheng.admin.tzhl.service.airportline.TZHLGetAirportLineListService;
import com.tuoheng.admin.tzhl.service.task.FlightTaskService;
import com.tuoheng.common.core.utils.DateUtils;
import com.tuoheng.common.core.utils.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ExecuteTaskService {

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private InspectionHistoryMapper inspectionHistoryMapper;

    @Autowired
    private TZHLGetAirportListService tzhlGetAirportListService;

    @Autowired
    private TZHLGetAirportLineListService tzhlGetAirportLineListService;

    @Autowired
    private FlightTaskService flightTaskService;

    public JsonResult executeTask(String userId, Inspection inspection) {
        log.info("进入泰州海陵区城管，执行任务，inspectionId={}", inspection.getId());
        JsonResult result = this.check(inspection);
        if (0 != result.getCode()) {
            this.insertInspectionHistory(inspection, result.getMsg());
            return JsonResult.error(result.getMsg());
        }

        result = flightTaskService.flightTask(inspection);
        if (0 != result.getCode()) {
            inspection.setStatus(InspectionStatusEnum.FLIGHT_FAILED.getCode());
            this.updateInspection(userId, inspection);

            log.info("执行任务失败，修改任务状态，status={}", inspection.getStatus());

            this.insertInspectionHistory(inspection, "执行任务失败");

            return JsonResult.success("执行任务失败");
        }

        inspection.setStatus(InspectionStatusEnum.PREPARING.getCode());
        this.updateInspection(userId, inspection);

        log.info("执行任务成功，修改任务状态，status={}", inspection.getStatus());

        return JsonResult.success();
    }

    private JsonResult check(Inspection inspection) {
        AirportDto airportDto = tzhlGetAirportListService.getAirport(inspection.getAirportId());
        if (ObjectUtil.isEmpty(airportDto)) {
            log.info("泰州海陵区城管，执行任务，机场不存在，inspectionId:{}, airportId", inspection.getId(), inspection.getAirportId());
            return JsonResult.error("泰州海陵区城管，执行任务，机场不存在");
        }

        if (1 == airportDto.getShelterStatus()) {
            log.info("泰州海陵区城管，执行任务，机场被禁用，inspectionId:{}, airportId", inspection.getId(), inspection.getAirportId());
            return JsonResult.error("泰州海陵区城管，执行任务，机场被禁用");
        }

        TZHLAirportLineResponse tzhlAirportLineResponse = tzhlGetAirportLineListService.getAirportLineById(inspection.getInspectionLine());
        if (ObjectUtil.isEmpty(tzhlAirportLineResponse)) {
            log.info("泰州海陵区城管，执行任务，航线不存在，inspectionId:{}, airportLineId", inspection.getId(), tzhlAirportLineResponse.getId());
            return JsonResult.error("泰州海陵区城管，执行任务，航线不存在");
        }
        return JsonResult.success();
    }

    /**
     * 修改任务执行
     *
     * @param userId
     * @param inspection
     */
    private void updateInspection(String userId, Inspection inspection) {
        inspection.setExecutionStatus(2);   // 修改任务执行状态，防止手动执行和定时重复
        inspection.setStatus(inspection.getStatus());
        inspection.setUpdateUser(userId);
        inspection.setUpdateTime(DateUtils.now());
        inspectionMapper.update(inspection);
    }

    /**
     * 更新任务失败记录
     *
     * @param inspection
     */
    private void insertInspectionHistory(Inspection inspection, String msg) {
        InspectionHistory inspectionHistory = new InspectionHistory();
        inspectionHistory.setTenantId(inspection.getTenantId());
        inspectionHistory.setInspectionId(inspection.getId());
        inspectionHistory.setHistoryName(msg);
        inspectionHistory.setCreateUser("");
        inspectionHistory.setCreateTime(DateUtils.now());
        inspectionHistoryMapper.insert(inspectionHistory);
    }
}