package com.tuoheng.admin.service.mission.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.config.SystemConstant;
import com.tuoheng.admin.conver.MissionConverMapper;
import com.tuoheng.admin.entity.domain.ThMission;
import com.tuoheng.admin.entity.request.emergency.QueryEmergencyListRequest;
import com.tuoheng.admin.entity.vo.AirPortStatusVO;
import com.tuoheng.admin.entity.vo.EmergencyMissionVO;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.mapper.ThMissionMapper;
import com.tuoheng.common.config.CommonConfig;
import com.tuoheng.common.exception.ServiceException;
import com.tuoheng.common.utils.HttpUtils;
import com.tuoheng.common.utils.JacksonUtil;
import com.tuoheng.common.utils.JsonResult;
import com.tuoheng.common.utils.StringUtils;
import com.tuoheng.system.entity.City;
import com.tuoheng.system.entity.User;
import com.tuoheng.system.utils.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

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

    @Autowired
    private ThMissionMapper thMissionMapper;

    public JsonResult getList(QueryEmergencyListRequest request) {
//        log.info("进入查询应急任务列表业务");
        User user = ShiroUtils.getUserInfo();
        Integer tenantId = user.getTenantId();
        request.setTenantId(tenantId);
        JsonResult result = this.check(tenantId, request);
        if (0 != result.getCode()) {
            log.info("进入查询应急任务列表业务：校验失败：{}", result.getMsg());
            return result;
        }
        List<ThMission> missionList = thMissionMapper.selectList(new LambdaQueryWrapper<ThMission>()
                        .eq(ThMission::getMark, MarkEnum.VALID.getCode())
                        .eq(ThMission::getTenantId, tenantId)
                        .eq(ThMission::getType, 2)
                        .in(CollectionUtil.isNotEmpty(request.getStatusList()), ThMission::getStatus, request.getStatusList()));
        if (CollectionUtil.isEmpty(missionList)) {
            log.info("应急任务列表数据为空");
            return JsonResult.success();
        }
        List<EmergencyMissionVO> emergencyMissionVOList = MissionConverMapper.INSTANCE.fromMissionListToEmergencyMissionVOList(missionList);
        Map<Integer, AirPortStatusVO> airPortStatusVOMap = getAirPortStatusVOMap(missionList);
        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(Integer tenantId, QueryEmergencyListRequest request) {
        return JsonResult.success();
    }

    private Map<Integer, AirPortStatusVO> getAirPortStatusVOMap(List<ThMission> missionList) {
        String airportIds = "";
        for (ThMission mission : missionList) {
            airportIds += mission.getAirportId() + ",";
        }
        airportIds = airportIds.substring(0, airportIds.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;
    }

}
