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

import cn.hutool.core.util.ObjectUtil;
import com.tuoheng.admin.constant.SystemConstant;
import com.tuoheng.admin.entity.domain.Tenant;
import com.tuoheng.admin.entity.vo.AirPortVo;
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.utils.HttpUtils;
import com.tuoheng.common.core.utils.JacksonUtil;
import com.tuoheng.common.core.utils.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class GetAirportListService {

    @Autowired
    private TenantMapper tenantMapper;

    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 = CommonConfig.airportURL + SystemConstant.API_AIRPORT_LIST;
        log.info("调用机场平台获取机场列表接口：url={}",url);
        String param = "page=1&limit=100&tenantCode=" + tenant.getCode();
        log.info("调用机场平台传参：param={}",param);
        String airPortStr = HttpUtils.sendGet(url, param);

        JsonResult jsonResult = JacksonUtil.json2pojo(airPortStr, JsonResult.class);

        if (ObjectUtil.isEmpty(jsonResult) || (!ObjectUtil.isEmpty(jsonResult.getData()) && jsonResult.getCode() != 0)) {
            return JsonResult.error(AriportCodeEnum.BAD_REQUEST.getCode(), AriportCodeEnum.BAD_REQUEST.getMsg());
        }
        return jsonResult;
    }

    public List<AirPortVo> getAirportListByTenantId(String tenantId) {
        List<AirPortVo> airPortVoList = new ArrayList<>();
        //读取不同租户的机场平台url
        Tenant tenant = tenantMapper.selectById(tenantId);
        if (ObjectUtil.isEmpty(tenant)) {
            log.info("获取机场信息, 租户为空，tenantId={}", tenantId);
            return null;
        }
        String url = CommonConfig.airportURL + SystemConstant.API_AIRPORT_LIST;
        String param = "page=1&limit=100&tenantCode=" + tenant.getCode();
        String airPortStr = HttpUtils.sendGet(url, param);
        JsonResult jsonResult = JacksonUtil.json2pojo(airPortStr, JsonResult.class);
        if (ObjectUtil.isEmpty(jsonResult) || (!ObjectUtil.isEmpty(jsonResult.getData()) && jsonResult.getCode() != 0)) {
            log.info("获取机场信息失败, jsonResult={}", jsonResult);
            return null;
        }
        Map<String, Object> map = (Map<String, Object>) jsonResult.getData();
        List<Object> list = (List<Object>) map.get("records");
        AirPortVo airPortVo;
        Map<String, Object> airPortVoMap;
        for (Object obj : list) {
            airPortVoMap = new HashMap<>();
            for (Object entry : ((Map) obj).entrySet()) {
                String key = ((Map.Entry) entry).getKey().toString();
                String value = "";
                if (ObjectUtil.isNotEmpty(((Map.Entry) entry).getValue())) {
                    value = ((Map.Entry) entry).getValue().toString();
                }
                airPortVoMap.put(key, value);
            }
            airPortVo = (AirPortVo) this.copyObject(airPortVoMap);
            if (ObjectUtil.isNotEmpty(airPortVo)) {
                airPortVoList.add(airPortVo);
            }
        }
        return airPortVoList;
    }

    public static <T> Object copyObject(Map<String, Object> field_Val) {
        Object o;
        try {
            Class clz = AirPortVo.class;
            o = clz.newInstance();
            for (Field tf : clz.getDeclaredFields()) {
                String fieldName = tf.getName();
                Object targetV = field_Val.get(fieldName);
                if (targetV == null) {
                    continue;
                }
                tf.setAccessible(true);
                tf.set(o, targetV);
            }
        } catch (InstantiationException e) {
            log.info("获取机场信息，InstantiationException：{}", e);
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            log.info("获取机场信息，IllegalAccessException：{}", e);
            throw new RuntimeException(e);
        }
        return o;
    }
}
