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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.tuoheng.admin.constant.SystemConstant;
import com.tuoheng.admin.entity.domain.Tenant;
import com.tuoheng.admin.entity.vo.airport.AirportLineVo;
import com.tuoheng.admin.enums.code.AriportCodeEnum;
import com.tuoheng.admin.mapper.TenantMapper;
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.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;
import org.springframework.web.util.UriComponentsBuilder;

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

@Slf4j
@Service
public class GetAirLineListService {

    @Autowired
    private TenantMapper tenantMapper;

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

    public JsonResult getAirLineList(Integer droneId) {
        //读取不同租户的机场平台url
        Tenant tenant = tenantMapper.selectById(CurrentUserUtil.getTenantId());
        if (ObjectUtil.isEmpty(tenant)) {
            return JsonResult.error(AriportCodeEnum.GET_NO_TENANT.getCode(), AriportCodeEnum.GET_NO_TENANT.getMsg());
        }
        String url = UriComponentsBuilder.fromHttpUrl(CommonConfig.airportURL + SystemConstant.API_AIRPORT_LINE_LIST)
                .queryParam("page", 1)
                .queryParam("limit", 100)
                .queryParam("droneId", droneId)
                .toUriString();

        JsonResult jsonResult;
        try {
            jsonResult = restTemplate.getForObject(url, JsonResult.class);
        } catch (Exception e) {
            log.info("获机航线列表接口异常, url:{}", url);
            throw new ServiceException("获机航线列表接口异常");
        }
        if (ObjectUtil.isEmpty(jsonResult) || (!ObjectUtil.isEmpty(Objects.requireNonNull(jsonResult).getData()) && jsonResult.getCode() != 0)) {
            return JsonResult.error(AriportCodeEnum.BAD_REQUEST.getCode(), AriportCodeEnum.BAD_REQUEST.getMsg());
        }
        return jsonResult;
    }

    public List<AirportLineVo> getList(String airportId, List<Integer> airportLineIdList) {
        //读取不同租户的机场平台url
        Tenant tenant = tenantMapper.selectById(CurrentUserUtil.getTenantId());
        if (ObjectUtil.isEmpty(tenant)) {
            return null;
        }
        String url = CommonConfig.airportURL + SystemConstant.API_AIRPORT_LINE_FILE_LIST;

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", SystemConstant.PLATFORM_CODE);
        jsonObject.put("sourceCode", SystemConstant.PLATFORM_CODE);
        jsonObject.put("tenantCode", tenant.getCode());
        jsonObject.put("airportId", airportId);
        jsonObject.put("airlineFileIds", airportLineIdList);

        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.info("调用机场平台，获取航线列表接口异常，url:{}", url);
            log.info("调用机场平台，获取航线列表接口异常，jsonObject：{}", jsonObject);
            return null;
        }
        if (ObjectUtil.isEmpty(response)) {
            log.info("调用机场平台，获取航线列表接口返回为空，url:{}", url);
            log.info("调用机场平台，获取航线列表接口返回为空，jsonObject：{}", jsonObject);
            return null;
        }
        JsonResult jsonResult = response.getBody();
        if (0 != jsonResult.getCode()) {
            log.info("调用机场平台，获取航线列表，失败，url:{}", url);
            log.info("调用机场平台，获取航线列表，失败，jsonObject：{}", jsonObject);
            log.info("调用机场平台，获取航线列表，失败，jsonResult：{}", jsonResult.getMsg());
            return null;
        }
        List<AirportLineVo> airportLineVoList = JSONObject.parseArray(JSONObject.toJSONString(jsonResult.getData()), AirportLineVo.class);
        if (CollectionUtil.isEmpty(airportLineVoList)) {
            log.info("调用机场平台，获取航线列表，数据为空");
        }
        return airportLineVoList;
    }
}
