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

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.common.core.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class FlyLogByErrorService {

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private InspectionHistoryMapper inspectionHistoryMapper;

    @Autowired
    private IDspService dspService;

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

        this.updateInspection(inspection);

        this.insertInspectionHistory(inspection, flyLogResponse.getTitle());

        // 停止dsp分支
        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);
    }
}
