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

import com.alibaba.fastjson.JSONObject;
import com.tuoheng.admin.constant.SystemConstant;
import com.tuoheng.admin.mapper.TenantMapper;
import com.tuoheng.common.core.config.common.CommonConfig;
import com.tuoheng.common.core.exception.ServiceException;
import com.tuoheng.common.core.utils.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class DroneControlService {

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    @Qualifier("restTemplate")
    private RestTemplate restTemplate;

    public JsonResult execute(JSONObject jsonObject) {
        log.info("进入调用机场平台，操作无人机, jsonObject={}", jsonObject);
        String url = CommonConfig.airportURL + SystemConstant.API_AIRPORT_DRONE_CONTROL;

        log.info("调用机场平台，操作无人机: url:{}", url);
        log.info("调用机场平台，操作无人机: jsonObject:{}", jsonObject);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity httpEntity = new HttpEntity(jsonObject, headers);
        ResponseEntity<JsonResult> response;
        try {
            response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, JsonResult.class);
        } catch (Exception e) {
            log.error("调用机场平台，操作无人机异常, url:{}", url);
            log.error("调用机场平台，操作无人机异常, httpEntity:{}", httpEntity);
            throw new ServiceException("调用机场平台，操作无人机异常");
        }
        JsonResult jsonResult = response.getBody();
        if (0 != jsonResult.getCode()) {
            log.info("调用机场平台，操作无人机：返回失败，jsonResult：{}", jsonResult.getMsg());
            return JsonResult.error(-1, "机场平台返回失败");
        }
        log.info("调用机场平台方法: 操作无人机结束");
        return JsonResult.success();
    }

}