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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.constant.SystemConstant;
import com.tuoheng.admin.entity.Business;
import com.tuoheng.admin.entity.FlightData;
import com.tuoheng.admin.entity.Inspection;
import com.tuoheng.admin.entity.Tenant;
import com.tuoheng.admin.enums.AiAnalyseStatusEnum;
import com.tuoheng.admin.enums.MarkTypeEnum;
import com.tuoheng.admin.enums.TaskStatusEnum;
import com.tuoheng.admin.enums.code.inspection.EditInspectionStatusCodeEnum;
import com.tuoheng.admin.mapper.BusinessMapper;
import com.tuoheng.admin.mapper.FlightDataMapper;
import com.tuoheng.admin.mapper.InspectionMapper;
import com.tuoheng.admin.mapper.TenantMapper;
import com.tuoheng.admin.service.third.dsp.IDspService;
import com.tuoheng.admin.utils.AirWeatherUtil;
import com.tuoheng.admin.vo.AirWeatherVO;
import com.tuoheng.common.core.utils.HttpUtils;
import com.tuoheng.common.core.utils.JacksonUtil;
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.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class UpdateWaittStatusService {

    @Autowired
    private BusinessMapper businessMapper;

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private FlightDataMapper flightDataMapper;

    @Autowired
    private IDspService dspService;

    public void updateWaittStatus(Inspection inspection) {
        Inspection inspectionUpdate = new Inspection();
        inspectionUpdate.setId(inspection.getId());
        inspectionUpdate.setStatus(TaskStatusEnum.COMPLETE.getCode());

        List<Business> businessList = businessMapper.selectList(new LambdaQueryWrapper<Business>()
                                        .eq(Business::getTypeId, inspection.getId())
                                        .eq(Business::getMark, MarkTypeEnum.VALID.getCode())
                                        .orderByDesc(Business::getCreateTime));

        if (CollectionUtil.isNotEmpty(businessList)) {
            inspectionMapper.updateById(inspectionUpdate);
            return;
        }

        //硬件停止后，停止AI分析
        stopAI(businessList.get(0).getMsgId(), inspection.getId());

        //获取天气信息
        //查询业务对应的租户信息
        Tenant tenant = tenantMapper.selectById(inspection.getTenantId());

        JsonResult result =  this.getWeather(tenant.getAirportUrl(), inspection.getAirportId());
        if (0 != result.getCode()) {
            log.info("修改任务状态业务接口：获取天气信息失败：{}", result.getMsg());
            inspectionUpdate.setWeather("");
            inspectionMapper.updateById(inspectionUpdate);
            return;
        }

        AirWeatherVO weather = (AirWeatherVO) result.getData();
        String weatherStr = AirWeatherUtil.getWeather(weather);
        inspectionUpdate.setWeather(weatherStr);

        Integer flightDataCount = flightDataMapper.selectCount(new LambdaQueryWrapper<FlightData>()
                .eq(FlightData::getInspectionId, inspection.getId())
                .eq(FlightData::getTenantId, inspection.getTenantId())
                .eq(FlightData::getMark, MarkTypeEnum.VALID.getCode()));
        if (flightDataCount > 0) {
            int index = (int) Math.ceil((double) flightDataCount / 2);
            FlightData flightData = flightDataMapper.selectOne(new LambdaQueryWrapper<FlightData>()
                    .eq(FlightData::getInspectionId, inspection.getId())
                    .eq(FlightData::getTenantId, inspection.getTenantId())
                    .eq(FlightData::getMark, MarkTypeEnum.VALID.getCode())
                    .orderByDesc(FlightData::getTimestamp)
                    .last("limit " + index + ",1"));
            if (ObjectUtil.isNotNull(flightData)) {
                inspectionUpdate.setFlyHeight(flightData.getUltrasonic());
            }
        }
        inspectionMapper.updateById(inspectionUpdate);
    }

    private JsonResult stopAI(String msgId, String inspectionId) {
        //任务调用完成之后，调用发送通道，请求DSP关闭请求
        //调用DSP接口
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("requestId", msgId);
        JSONObject responseJson = new JSONObject();
        Inspection inspectionUpdate = new Inspection();
        inspectionUpdate.setId(inspectionId);
        try {
            responseJson = dspService.serviceStopApplication(jsonObject);
            if (responseJson.getIntValue("code") == 0) {
                if (responseJson.containsKey("data") && ObjectUtil.isNotEmpty(responseJson.get("data"))) {
                    String requestId = responseJson.getJSONObject("data").getString("requestId");
                    log.info("dsp实时调用响应requestId：{}", requestId);
                } else {
                    log.info("dsp实时调用响应:{}", responseJson);
                }
                return JsonResult.success();
            } else {
                log.error("dsp实时调用失败：{}", responseJson);
                inspectionUpdate.setAnalyseStatus(AiAnalyseStatusEnum.FAILED.getCode());
            }
            inspectionMapper.updateById(inspectionUpdate);
        } catch (Exception e) {
            log.error("dsp实时调用失败：{}", responseJson);
            inspectionUpdate.setAnalyseStatus(AiAnalyseStatusEnum.FAILED.getCode());
            inspectionMapper.updateById(inspectionUpdate);
        }
        return JsonResult.success();
    }

    public JsonResult getWeather(String airportUrl, Integer airportId) {
        String url = airportUrl + SystemConstant.API_AIRPORT_GET_WEATHER;
        String param = "airportId=" + airportId;
        String weatherStr = HttpUtils.sendGet(url, param);
        JsonResult jsonResult;
        try {
            jsonResult = JacksonUtil.json2pojo(weatherStr, JsonResult.class);
            if (ObjectUtil.isEmpty(jsonResult) || Objects.requireNonNull(jsonResult).getCode() != 0) {
                return JsonResult.error(EditInspectionStatusCodeEnum.GET_WEATHER_FAILED.getCode(), EditInspectionStatusCodeEnum.GET_WEATHER_FAILED.getMsg());
            }
            if (ObjectUtil.isEmpty(jsonResult.getData())) {
                return JsonResult.success(new AirWeatherVO());
            }
            AirWeatherVO airWeatherVO = JSONObject.parseObject(JSONObject.toJSONString(jsonResult.getData()), AirWeatherVO.class);
            return JsonResult.success(airWeatherVO);
        } catch (Exception e) {
            return JsonResult.error(EditInspectionStatusCodeEnum.GET_WEATHER_FAILED.getCode(), EditInspectionStatusCodeEnum.GET_WEATHER_FAILED.getMsg());
        }
    }
}
