package com.tuoheng.admin.service.third.airport;

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.Inspection;
import com.tuoheng.admin.enums.InspectionStatusEnum;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.mapper.InspectionMapper;
import com.tuoheng.admin.request.accident.ReversalFlightRequest;
import com.tuoheng.common.core.config.common.CommonConfig;
import com.tuoheng.common.core.exception.ServiceException;
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.stereotype.Service;

/**
 * @Author ChengWang
 * @Date 2023/3/14
 */
@Slf4j
@Service
public class ReversalFlightService {

    @Autowired
    private InspectionMapper inspectionMapper;

    /**
     * 应急飞行（回仓）
     *
     * @param request
     * @return
     */
    public JsonResult reversalFlight(ReversalFlightRequest request) {
        log.info("进入调用机场平台，执行定点飞行, airportId={}", request.getAirportId());
        //校验传参
        if (null == request.getAirportId()) {
            throw new ServiceException("机场id为空");
        }
        // 根据机场查询对应应急任务
        // 正常由机场平台会回调改状态，为防止机场平台回调出问题，此时将应急任务状态改为已完成
        Inspection inspection = inspectionMapper.selectOne(new LambdaQueryWrapper<Inspection>()
                .eq(Inspection::getAirportId, request.getAirportId())
                .eq(Inspection::getType, 2)
                .eq(Inspection::getMark, MarkEnum.VALID.getCode())
                .eq(Inspection::getStatus, InspectionStatusEnum.IN_FLIGHT.getCode()));
        if (ObjectUtil.isNotNull(inspection)) {
            // 修改原巡检任务状态为已完成
            inspection.setStatus(InspectionStatusEnum.FLIGHT_COMPLETED.getCode());
            inspectionMapper.updateById(inspection);
        }

        request.setZhilin("03");
        //调用机场平台让飞机返航
        String url = CommonConfig.airportURL + SystemConstant.API_AIRPORT_DRONE_CONTROL;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("airportId", request.getAirportId());
        jsonObject.put("zhilin", request.getZhilin());
        jsonObject.put("msg", "回仓");
        log.info("调用机场平台，无人机执行定点飞行返航：url:{}", url);
        log.info("调用机场平台，原无人机执行定点飞行返航，jsonObject:{}", jsonObject);

        String airPortStr = HttpUtils.doSend(url, jsonObject, null, "POST");
        log.info("调用无人机平台，操作无人机：airPortStr:{}", airPortStr);
        if (StringUtils.isEmpty(airPortStr)) {
            log.info("原无人机执行定点飞行返航：机场接口返回数据为空，返航失败，jsonObject：{}", jsonObject);
            throw new ServiceException("机场接口返回数据为空，返航失败");
        }
        JsonResult jsonResult = JacksonUtil.json2pojo(airPortStr, JsonResult.class);
        if (0 != jsonResult.getCode()) {
            log.info("调用机场平台，无人机执行定点飞行：返航失败，jsonResult：{}", jsonResult.getMsg());
            return JsonResult.error(-1, "机场平台返回失败");
        }
        log.info("调用无人机平台返航结束");
        return JsonResult.success();
    }
}
