package com.tuoheng.admin.service.accident.query;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.constant.SystemConstant;
import com.tuoheng.admin.conver.AccidentConverMapper;
import com.tuoheng.admin.entity.Inspection;
import com.tuoheng.admin.entity.User;
import com.tuoheng.admin.enums.InspectionStatusEnum;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.mapper.InspectionMapper;
import com.tuoheng.admin.request.accident.QueryEmergencyListRequest;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.admin.vo.airport.AirPortStatusVO;
import com.tuoheng.admin.vo.accident.EmergencyMissionVO;
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 com.tuoheng.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 查询应急任务列表业务层处理
 *
 * @author wanjing
 * @team tuoheng
 * @date 2023-02-13
 */
@Slf4j
@Service
public class QueryEmergencyListService {

    @Autowired
    private InspectionMapper inspectionMapper;

    public JsonResult getList(QueryEmergencyListRequest request) {
//        log.info("进入查询应急任务列表业务");
        User user = CurrentUserUtil.getUserInfo();
        String tenantId = user.getTenantId();
        request.setTenantId(tenantId);
        JsonResult result = this.check(tenantId, request);
        if (0 != result.getCode()) {
            log.info("进入查询应急任务列表业务：校验失败：{}", result.getMsg());
            return result;
        }
        List<Inspection> inspectionList = inspectionMapper.selectList(new LambdaQueryWrapper<Inspection>()
                .eq(Inspection::getMark, MarkEnum.VALID.getCode())
                .eq(Inspection::getTenantId, tenantId)
                .eq(Inspection::getType, 2)
                .eq(Inspection::getStatus, InspectionStatusEnum.IN_FLIGHT.getCode()));
        //.in(CollectionUtil.isNotEmpty(request.getStatusList()), Inspection::getStatus, request.getStatusList()));
        if (CollectionUtil.isEmpty(inspectionList)) {
//            log.info("应急任务列表数据为空");
            return JsonResult.success(inspectionList);
        }
        List<EmergencyMissionVO> emergencyMissionVOList = AccidentConverMapper.INSTANCE.fromMissionListToEmergencyMissionVOList(inspectionList);
        Map<Integer, AirPortStatusVO> airPortStatusVoMap = getAirPortStatusVoMap(inspectionList);
        AirPortStatusVO airPortStatusVO;
        for (EmergencyMissionVO emergencyMissionVO : emergencyMissionVOList) {
            if (ObjectUtil.isNotNull(airPortStatusVoMap)) {
                airPortStatusVO = airPortStatusVoMap.get(emergencyMissionVO.getAirportId());
                if (ObjectUtil.isNotNull(airPortStatusVO)) {
                    emergencyMissionVO.setAirportStatus(airPortStatusVO.getMsg());
                }
            }
        }
        return JsonResult.success(emergencyMissionVOList);
    }

    /**
     * 检查参数
     *
     * @param tenantId
     * @param request
     * @return
     */
    private JsonResult check(String tenantId, QueryEmergencyListRequest request) {
        return JsonResult.success();
    }

    private Map<Integer, AirPortStatusVO> getAirPortStatusVoMap(List<Inspection> inspectionList) {

        StringBuilder ids = new StringBuilder();
        String airportIds;
        Set<Integer> set = new HashSet<>();
        for (Inspection inspection : inspectionList) {
            if (set.add(inspection.getAirportId())) {
                ids.append(inspection.getAirportId()).append(",");
            }
        }
        airportIds = ids.substring(0, ids.length() - 1);
        String url = CommonConfig.airportURL + SystemConstant.API_AIRPORT_STATUS_BY_AIRPORT_ID;
        String param = "airportIds=" + airportIds;
        String airPortStatusStr = HttpUtils.sendGet(url, param);
        if (StringUtils.isEmpty(airPortStatusStr)) {
            log.info("调用机场平台，查询飞行状态：机场接口返回数据为空，查询飞行状态失败");
            return null;
        }
        JsonResult jsonResult = JacksonUtil.json2pojo(airPortStatusStr, JsonResult.class);

        List<AirPortStatusVO> airPortStatusVOList = JSONObject.parseArray(JSONObject.toJSONString(jsonResult.getData()), AirPortStatusVO.class);
        Map<Integer, AirPortStatusVO> map = new HashMap<>();
        for (AirPortStatusVO airPortStatusVO : airPortStatusVOList) {
            map.put(airPortStatusVO.getAirportId(), airPortStatusVO);
        }
        return map;
    }

}
