package com.tuoheng.admin.service.inspection.update.status;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tuoheng.admin.entity.Business;
import com.tuoheng.admin.entity.Inspection;
import com.tuoheng.admin.entity.LiveChannel;
import com.tuoheng.admin.entity.Report;
import com.tuoheng.admin.enums.AiAnalyseStatusEnum;
import com.tuoheng.admin.enums.InspectionStatusEnum;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.mapper.*;
import com.tuoheng.admin.request.inspection.MissionStatusRequest;
import com.tuoheng.admin.service.third.dsp.IDspService;
import com.tuoheng.admin.vo.DspCallbackVo;
import com.tuoheng.admin.websocket.WebSocketService;
import com.tuoheng.common.core.utils.DateUtils;
import com.tuoheng.common.core.utils.JacksonUtil;
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 UpdateFlightStatusService {

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private IDspService dspService;

    public JsonResult updateFlightStatus(Inspection inspection, MissionStatusRequest missionStatusRequest) {
        Inspection inspectionUpdate = new Inspection();
        inspectionUpdate.setId(inspection.getId());
        inspectionUpdate.setExecutionStartTime(DateUtils.now());

        JsonResult result = dspService.startAI(inspection, missionStatusRequest.getPushUrl(), missionStatusRequest.getPullUrl());

        if (0 != result.getCode()) {
            //如果调用DSP失败就直接失败！
            log.info("修改任务状态业务接口：调用DSP数据失败：{}", result.getMsg());
            inspectionUpdate.setStatus(InspectionStatusEnum.FLIGHT_FAILED.getCode());
            inspectionUpdate.setAnalyseStatus(AiAnalyseStatusEnum.WAITING.getCode());
            inspectionMapper.updateById(inspectionUpdate);

            // 修改报告状态和开始时间
            this.updateReport(inspection);

            return result;
        }

        // 修改任务的状态
        this.updateInspection(inspectionUpdate);

        // 修改报告状态和开始时间
        this.updateReport(inspection);

        return JsonResult.success();
    }

    /**
     * 修改任务的状态
     *
     * @param inspectionUpdate
     */
    private void updateInspection(Inspection inspectionUpdate) {
        inspectionUpdate.setStatus(InspectionStatusEnum.IN_FLIGHT.getCode());
        inspectionUpdate.setUpdateTime(DateUtils.now());
        Integer count = inspectionMapper.updateStatus(inspectionUpdate);
        if (count <= 0) {
            log.info("修改inspection status 失败");
        } else {
            log.info("修改inspection status 成功");
        }
    }

    private void updateReport(Inspection inspection) {
        Report report = reportMapper.selectOne(Wrappers.<Report>lambdaQuery()
                .eq(Report::getInspectionId, inspection.getId())
                .eq(Report::getMark, MarkEnum.VALID.getCode()));
        if (ObjectUtil.isNull(report)) {
            log.info("该任务还没有生成报告，不需要修改报告的完成时间和状态");
            return;
        }
        report.setStatus(inspection.getStatus());
        report.setExecutionStartTime(inspection.getExecutionStartTime());
        reportMapper.updateById(report);
    }
}
