package com.tuoheng.admin.service.airportline.query.inspection;

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.vo.airport.AirPortLineLocationVo;
import com.tuoheng.admin.entity.vo.airport.AirPortStatusVO;
import com.tuoheng.common.core.config.common.CommonConfig;
import com.tuoheng.common.core.exception.ServiceException;
import com.tuoheng.common.core.utils.HttpUtils;
import com.tuoheng.common.core.utils.JacksonUtil;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 根据任务ID获取航线，从机场平台获取
 *
 * @author wanjing
 * @team tuoheng
 * @date 2023-04-26
 */
@Slf4j
@Service
public class QueryAirportLineByAirportService {

    /**
     * 根据任务ID获取航线，从机场平台获取
     *
     * @return
     */
    public JsonResult getAirportLineList(Inspection inspection) {
        log.info("进入根据任务ID获取航线，从机场平台获取");
        Integer inspectionLine = inspection.getInspectionLine();
        JsonResult result = this.checkParam(inspectionLine);
        if (0 != result.getCode()) {
            log.info("根据任务ID获取航线：校验参数失败：{}", result.getMsg());
            return result;
        }
        JsonResult jsonResult = this.getAirPortLocation(inspectionLine);
        return JsonResult.success(jsonResult);
    }

    private JsonResult checkParam(Integer inspectionLine) {
        if (ObjectUtil.isEmpty(inspectionLine)) {
            log.info("进入根据任务ID获取航线，从机场平台获取业务，航线ID为空，inspectionLine={}", inspectionLine);
            throw new ServiceException("航线ID为空");
        }
        return JsonResult.success();
    }

    private JsonResult getAirPortLocation(Integer inspectionLine) {
        String url = CommonConfig.airportURL + SystemConstant.API_AIRPORT_LOCATION;
        String param = "id=" + inspectionLine;
        String airPortLineLocationStr = HttpUtils.sendGet(url, param);
        if (StringUtils.isEmpty(airPortLineLocationStr)) {
            log.info("调用机场平台，查询航线：机场接口返回数据为空：airPortLineLocationStr={}",airPortLineLocationStr);
            return JsonResult.error("调用机场平台,查询航线数据为空");
        }
        JsonResult jsonResult = JacksonUtil.json2pojo(airPortLineLocationStr, JsonResult.class);
        if (0 != jsonResult.getCode()) {
            log.info("调用机场平台，查询航线：机场接口返回状态失败");
            return JsonResult.error(jsonResult.getCode(),jsonResult.getMsg());
        }
        if (ObjectUtil.isEmpty(jsonResult.getData())) {
            log.info("调用机场平台，查询航线：机场接口返回数据为空");
            return JsonResult.error("机场平台返回数据data为空");
        }
        List<AirPortLineLocationVo> airPortLineLocationVoList = JSONObject.parseArray(JSONObject.toJSONString(jsonResult.getData()), AirPortLineLocationVo.class);
        return JsonResult.success(airPortLineLocationVoList);
    }

}
