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

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tuoheng.admin.constant.SystemConstant;
import com.tuoheng.admin.entity.domain.Inspection;
import com.tuoheng.admin.entity.domain.User;
import com.tuoheng.admin.entity.vo.airport.AirPortStatusVO;
import com.tuoheng.admin.entity.vo.inspection.InspectionScrollbarVo;
import com.tuoheng.admin.enums.InspectionStatusEnum;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.mapper.InspectionMapper;
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 com.tuoheng.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author ChengWang
 * @Date 2023/5/22
 */
@Slf4j
@Service
public class QueryInspectionAndAirportStatusService {

    @Autowired
    private InspectionMapper inspectionMapper;


    public JsonResult getList() {
        User user = CurrentUserUtil.getUserInfo();
        String userId = user.getId();
        String tenantId = user.getTenantId();
        JsonResult jsonResult = check(userId,tenantId);
        if(0 != jsonResult.getCode()){
            log.info("进入查询任务列表及机场状态业务：校验失败：{}",jsonResult.getMsg());
        }
        //查询当前租户下的任务列表
        List<Inspection> inspectionList = inspectionMapper.selectList(Wrappers.<Inspection>lambdaQuery()
                .eq(Inspection::getTenantId, tenantId)
                .eq(Inspection::getMark, MarkEnum.VALID.getCode())
                .in(Inspection::getStatus, InspectionStatusEnum.IN_FLIGHT.getCode(), InspectionStatusEnum.PREPARING.getCode()));
        if(CollectionUtils.isEmpty(inspectionList) || inspectionList.size() == 0){
            log.info("任务列表为空");
            return JsonResult.success();
        }
        List<InspectionScrollbarVo> inspectionVoList = new ArrayList<>();
        for (Inspection inspection : inspectionList) {
            InspectionScrollbarVo vo = new InspectionScrollbarVo();
            BeanUtils.copyProperties(inspection,vo);
            inspectionVoList.add(vo);
        }
        //机场状态
        Map<Integer, AirPortStatusVO> airPortStatusVOMap = this.getAirPortStatusMap(inspectionList);
        AirPortStatusVO airPortStatusVO;
        for (InspectionScrollbarVo inspectionScrollbarVo : inspectionVoList) {
            if(ObjectUtil.isNotNull(airPortStatusVOMap)){
                airPortStatusVO = airPortStatusVOMap.get(inspectionScrollbarVo.getAirportId());
                if(ObjectUtil.isNotNull(airPortStatusVO)){
                    //机场状态
                    inspectionScrollbarVo.setAirportStatus(airPortStatusVO.getMsg());
                }
            }
        }

        return JsonResult.success(inspectionVoList);
    }

    private Map<Integer, AirPortStatusVO> getAirPortStatusMap(List<Inspection> inspectionList) {
        StringBuffer ids = new StringBuffer();
        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;
        }
        //String---> JsonResult
        JsonResult jsonResult = JacksonUtil.json2pojo(airPortStatusStr, JsonResult.class);
        List<AirPortStatusVO> airPortStatusVOList = (List<AirPortStatusVO>) jsonResult.getData();
//        List<AirPortStatusVO> airPortStatusVOList = com.alibaba.fastjson.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;
    }

    private JsonResult check(String userId, String tenantId) {
        return JsonResult.success();
    }
}
