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

import cn.hutool.core.util.ObjectUtil;
import com.tuoheng.admin.constant.SystemConstant;
import com.tuoheng.admin.entity.Tenant;
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.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

@Slf4j
@Service
public class GetAirportListService {

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    @Qualifier("restTemplate")
    private RestTemplate restTemplate;
    public JsonResult getAirportList() {
        //读取不同租户的机场平台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_LIST)
                .queryParam("page", 1)
                .queryParam("limit", 100)
                .queryParam("tenantCode", tenant.getCode())
                .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(jsonResult.getData()) && jsonResult.getCode() != 0)) {
            return JsonResult.error(AriportCodeEnum.BAD_REQUEST.getCode(), AriportCodeEnum.BAD_REQUEST.getMsg());
        }
        return jsonResult;
    }

}
