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

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.tuoheng.admin.constant.SystemConstant;
import com.tuoheng.admin.entity.domain.Inspection;
import com.tuoheng.admin.entity.domain.User;
import com.tuoheng.admin.entity.request.airport.ReversalFlightRequest;
import com.tuoheng.admin.enums.InspectionStatusEnum;
import com.tuoheng.admin.enums.code.inspection.EditInspectionCodeEnum;
import com.tuoheng.admin.mapper.InspectionMapper;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.common.core.config.common.CommonConfig;
import com.tuoheng.common.core.exception.ServiceException;
import com.tuoheng.common.core.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author ChengWang
 * @Date 2023/5/25
 */
@Service
@Slf4j
public class ReversalFlightService {

    @Autowired
    private InspectionMapper inspectionMapper;


    public JsonResult reversal(ReversalFlightRequest request) {
        User user = CurrentUserUtil.getUserInfo();
        String userId = user.getId();
        String tenantId = user.getTenantId();
        JsonResult result = this.check(userId,tenantId,request);
        if(0 != result.getCode()){
            log.info("进入无人机返航校验失败：{}",result.getMsg());
        }
        request.setZhilin("03");
        log.info("进入调用无人机平台,回仓指令值：{}",request.getZhilin());
        JsonResult jsonResult = this.queryInspection(request);
        if(0 != jsonResult.getCode()){
            return JsonResult.error(jsonResult.getCode(),jsonResult.getMsg());
        }
        Inspection inspection = (Inspection) jsonResult.getData();
        //回仓
        JsonResult resultData = this.getReversalFlight(inspection);
        if(0 != resultData.getCode()){
            return JsonResult.error(jsonResult.getCode(),jsonResult.getMsg());
        }

        return JsonResult.success("无人机返航成功");
    }

    private JsonResult getReversalFlight(Inspection inspection) {
        log.info("执行无人机回仓");
        inspection.setStatus(InspectionStatusEnum.FLIGHT_COMPLETED.getCode());
        inspection.setUpdateTime(DateUtils.now());
        inspection.setUpdateUser(CurrentUserUtil.getUserId());
        int count = inspectionMapper.updateById(inspection);
        if(count<=0){
            log.info("修改任务状态失败：{}",inspection);
            throw new SecurityException("修改任务状态失败");
        }
        //调用机场平台返航
        String url = CommonConfig.airportURL + SystemConstant.API_AIRPORT_DRONE_CONTROL;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("airportId", inspection.getAirportId());
        jsonObject.put("taskId", inspection.getId());
        jsonObject.put("zhilin", "03");
        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, jsonResult.getMsg());
        }
        log.info("调用无人机平台返航结束");
        return JsonResult.success();


    }

    private JsonResult queryInspection(ReversalFlightRequest request) {
        Inspection inspection = inspectionMapper.selectById(request.getInspectionId());
        if(ObjectUtil.isNull(inspection)){
            return JsonResult.error("巡检任务为空");
        }
        return JsonResult.success(inspection);
    }

    private JsonResult check(String userId, String tenantId, ReversalFlightRequest request) {
        if(StringUtils.isEmpty(request.getInspectionId())){
            return JsonResult.error(EditInspectionCodeEnum.ID_IS_NULL.getCode(),EditInspectionCodeEnum.ID_IS_NULL.getMsg());
        }
        return JsonResult.success();
    }
}
