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

import cn.hutool.core.util.ObjectUtil;
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.service.third.dsp.IDspService;
import com.tuoheng.admin.tzhl.response.TZHLFlyLogResponse;
import com.tuoheng.admin.tzhl.service.fly.data.FlyDataService;
import com.tuoheng.common.core.utils.DateUtils;
import com.tuoheng.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class FlyLogByNormalService {

    private final static String SUCCESS = "成功";
    private final static String FAILED = "失败";

    private final static String PREPARE_TASK = "下发航线任务";   // 1、下发航线任务+成功/失败（任务失败会给出错误码，需自行跟据大疆的上云api进行转译。下同）
    private final static String EXECUTE_TASK = "执行航线任务";   // 2、执行航线任务+成功/失败
    private final static String CANCEL_TASK = "取消航线任务";    // 3、取消航线任务+成功/失败
    private final static String PAUSE_TASK = "暂停航线任务";     // 4、暂停航线任务+成功/失败
    private final static String RECOVERY_TASK = "恢复航线任务";  // 5、恢复航线任务+成功/失败
    private final static String FLY_COMPLETED = "超5分钟未收到飞行数据，平台主动汇总";   // 6、超5分钟未收到飞行数据，平台主动汇总（此时飞机已完成飞行并关机）
    private final static String CLOUD_STORAGE_INSUFFICIENT = "云存储不足，飞行视频未保存"; // 7、云存储不足，飞行视频未保存
    private final static String ONE_CLICK_TAKEOFF = "一键起飞";      // 8、一键起飞
    private final static String POINT_FLY = "指点飞行";              // 9、指点飞行
    private final static String POINT_FLY_CANCEL = "取消指点飞行";    // 10、取消指点飞行
    private final static String RETURN_HOME = "一键返航";            // 11、一键返航
    private final static String RETURN_HOME_CANCEL = "取消返航";     // 12、取消返航

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private InspectionHistoryMapper inspectionHistoryMapper;

    @Autowired
    private IDspService dspService;

    @Autowired
    private FlyDataService flyDataService;

    public void getFlyLog(Inspection inspection, TZHLFlyLogResponse flyLogResponse) {
        log.info("获取飞行日志，status=normal，title={}", flyLogResponse.getTitle());

        if (ObjectUtil.isEmpty(flyLogResponse)) {
            log.info("flyLogResponse：{}", flyLogResponse);
        }
        String title = flyLogResponse.getTitle();
        if (StringUtils.isEmpty(title)) {
            log.info("title为空");
        }

        if (title.contains(PREPARE_TASK)) {
            // 下发任务
            this.prepareTask(inspection, flyLogResponse);
        } else if (title.contains(EXECUTE_TASK)) {
            // 执行任务
            this.executeTask(inspection, flyLogResponse);
        } else if (title.contains(FLY_COMPLETED)) {
            // 飞行完成
           this.completedTask(inspection, flyLogResponse);
        } else if (title.contains(CLOUD_STORAGE_INSUFFICIENT)) {
            //  TODO，产品确认该场景不做处理
        }
    }

    /**
     * 下发任务
      * @param inspection
     * @param flyLogResponse
     */
    private void prepareTask(Inspection inspection, TZHLFlyLogResponse flyLogResponse) {
        String title = flyLogResponse.getTitle().replace(PREPARE_TASK, "");
        if (ObjectUtil.isEmpty(title) && title.length() < 2) {
            return;
        }
        String status = title.substring(0, 2);
        if (FAILED.equals(status)) {
            inspection.setStatus(InspectionStatusEnum.FLIGHT_FAILED.getCode());

            this.updateInspection(inspection);

            String error = title.replace(status, "");
            this.insertInspectionHistory(inspection, error);

            dspService.stopAI(inspection.getId());
        }
    }

    /**
     * 执行任务
     * @param inspection
     * @param flyLogResponse
     */
    private void executeTask(Inspection inspection, TZHLFlyLogResponse flyLogResponse) {
        String title = flyLogResponse.getTitle().replace(PREPARE_TASK, "");
        if (ObjectUtil.isEmpty(title) && title.length() < 2) {
            return;
        }
        String status = title.substring(0, 2);
        if (FAILED.equals(status)) {
            inspection.setStatus(InspectionStatusEnum.FLIGHT_FAILED.getCode());

            this.updateInspection(inspection);

            String error = title.replace(status, "");
            this.insertInspectionHistory(inspection, error);

            dspService.stopAI(inspection.getId());
        }
    }

    /**
     * 完成任务
     * @param inspection
     * @param flyLogResponse
     */
    private void completedTask(Inspection inspection, TZHLFlyLogResponse flyLogResponse) {
        // 任务完成
        inspection.setStatus(InspectionStatusEnum.FLIGHT_COMPLETED.getCode());

        this.updateInspection(inspection);

        // 拉取飞行数据
        flyDataService.getFlyData(inspection);

        dspService.stopAI(inspection.getId());
    }

    /**
     * 修改任务执行时数据
     *
     * @param inspection
     */
    private void updateInspection(Inspection inspection) {
        inspection.setStatus(inspection.getStatus());
        inspection.setUpdateUser("");
        inspection.setUpdateTime(DateUtils.now());
        inspectionMapper.updateStatus(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);
    }

}
