package com.tuoheng.admin.tzhl.service.fly.log;

import cn.hutool.core.util.ObjectUtil;
import com.tuoheng.admin.dto.AirportDto;
import com.tuoheng.admin.entity.Inspection;
import com.tuoheng.admin.enums.InspectionStatusEnum;
import com.tuoheng.admin.mapper.InspectionMapper;
import com.tuoheng.admin.service.third.dsp.IDspService;
import com.tuoheng.admin.tzhl.response.TZHLFlyLogResponse;
import com.tuoheng.admin.tzhl.service.airport.TZHLGetAirportListService;
import com.tuoheng.admin.tzhl.service.fly.data.FlyDataService;
import com.tuoheng.common.core.utils.DateUtils;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Service
public class FlyLogBySuccessService {

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private TZHLGetAirportListService tzhlGetAirportListService;

    @Autowired
    private IDspService dspService;

    @Autowired
    private FlyDataService flyDataService;

    public void getFlyLog(Inspection inspection, TZHLFlyLogResponse flyLogResponse) {
        log.info("获取飞行日志，status=success，inspectionId={}, title={}", inspection.getId(), flyLogResponse.getTitle());
        if (InspectionStatusEnum.IN_FLIGHT.getCode() == inspection.getStatus()) {
            log.info("获取飞行日志，该任务状态已经改是飞行中，inspectionid={}", inspection.getId());
            return;
        }
        inspection.setExecutionStartTime(DateUtils.now());
        inspection.setStatus(InspectionStatusEnum.IN_FLIGHT.getCode());
        inspection.setUpdateUser("");
        inspection.setUpdateTime(DateUtils.now());
        inspectionMapper.updateStatus(inspection);

        log.info("获取飞行日志，status=success，修改任务状态，inspectionId={}, status={}", inspection.getId(), inspection.getStatus());

        AirportDto airportDto = tzhlGetAirportListService.getAirport(inspection.getAirportId());
        if (ObjectUtil.isEmpty(airportDto)) {
            log.info("获取飞行日志，获取推流地址失败，inspectionId={}", inspection.getId());
            return;
        }

        if (StringUtils.isEmpty(airportDto.getUavPushUrl())) {
            log.info("获取飞行日志，获取推流地址为空，inspectionId={}", inspection.getId());
            return;
        }

        // 通知DSP
        log.info("获取飞行日志，status=success，通知DSP，推流地址：pushUrl={}", airportDto.getUavPushUrl());
        JsonResult result = dspService.startAI(inspection, airportDto.getUavPushUrl(), airportDto.getUavPushUrl());
        if (0 != result.getCode()) {
            log.info("获取飞行日志，获取推流地址，通知DSP失败");
            inspection.setStatus(InspectionStatusEnum.FLIGHT_FAILED.getCode());
        }

        log.info("获取飞行日志，轮询飞行数据开始，inspectionId:{}", inspection.getId());
        // 此处另起线程
        ExecutorService executor = Executors.newFixedThreadPool(1);
        CompletableFuture.runAsync(() -> {
            this.exec(inspection.getId());
        }, executor);
        log.info("获取飞行日志，轮询飞行数据结束，inspectionId:{}", inspection.getId());
    }

    public void exec(String inspectionId) {
        try {
            Long beginTime = System.currentTimeMillis();
            while (true) {
                log.info("轮训飞行数据，inspectionId:{}", inspectionId);
                Thread.sleep(2000);
                if (System.currentTimeMillis() - beginTime > 7200000) {
                    // 超过120分钟，停止轮询
                    log.info("轮询飞行数据，超时60分钟，停止轮询，inspectionId:{}", inspectionId);
                    break;
                }
                Inspection inspection = inspectionMapper.selectById(inspectionId);
                if (ObjectUtil.isEmpty(inspection)) {
                    log.info("轮询飞行数据，任务不存在，停止轮询，inspectionId:{}", inspectionId);
                    break;
                }
                if (InspectionStatusEnum.IN_FLIGHT.getCode() != inspection.getStatus()) {
                    log.info("轮询飞行数据，任务状态，不在飞行中，停止轮询，inspectionId:{}", inspectionId);
                    break;
                }

                // 拉取飞行数据
                flyDataService.getFlyData(inspection);
            }
        } catch (Exception e) {
        }
    }

}
