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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tuoheng.admin.constant.SystemConstant;
import com.tuoheng.admin.dto.AirportDetailDto;
import com.tuoheng.admin.dto.AirportMsgDto;
import com.tuoheng.admin.entity.Tenant;
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.JsonResult;
import com.tuoheng.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.lang.reflect.Field;
import java.util.*;

/**
 * @Author xiaoying
 * @Date 2023/4/14 16:05
 */
@Service
@Slf4j
public class GetAirportDetailService {

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    @Qualifier("restTemplate")
    private RestTemplate restTemplate;

    public JsonResult getAirportDetail(Integer airportId, String airportCode) {
        JsonResult resultData = this.check(airportId, airportCode);
        if (resultData.getCode() != 0) {
            return JsonResult.error(resultData.getCode(), resultData.getMsg());
        }
        //获取当前租户code
        String tenantId = CurrentUserUtil.getTenantId();
        Tenant tenant = tenantMapper.selectOne(Wrappers.<Tenant>lambdaQuery()
                .eq(Tenant::getId, tenantId)
                .eq(Tenant::getMark, 1));
        if (StringUtils.isEmpty(tenant.getCode())) {
            throw new RuntimeException("租户code为空");
        }
        String tenantCode = tenant.getCode();

        String url = UriComponentsBuilder.fromHttpUrl(CommonConfig.airportURL + SystemConstant.API_AIRPORT_GET_WEATHER_STATUS)
                .queryParam("airportId", airportId)
                .toUriString();
        JsonResult jsonResult;
        try {
            jsonResult = restTemplate.getForObject(url, JsonResult.class);
        } catch (Exception e) {
            log.info("获取机场状态，机场平台返回异常, url:{}", url);
            return JsonResult.error("获取机场状态，机场平台返回异常");
        }
        if (0 != jsonResult.getCode()) {
            log.info("获取机场状态，机场平台返回失败，jsonResult={}", jsonResult);
            return JsonResult.error("获取机场状态，机场平台返回失败");
        }

        List<AirportMsgDto> msgList = this.getMsgList(tenantCode, airportCode);
        log.info("获取机场信息列表,msgList={}", JSON.toJSONString(msgList));
        AirportDetailDto vo = new AirportDetailDto();
        if (CollectionUtil.isNotEmpty(msgList) || msgList.size() != 0) {
            AirportMsgDto airportMsgDto = msgList.get(0);
            if (ObjectUtil.isNotNull(airportMsgDto)) {
                //电量数据%
                vo.setBattery(airportMsgDto.getBattery() + "%");
            }
        }

        JSONObject dataObject = (JSONObject) JSONObject.toJSON(jsonResult.getData());
        log.info("响应信息:{}", dataObject.toJSONString());
        JSONObject wthJson = dataObject.getJSONObject("WTH");
        if (Objects.nonNull(wthJson)) {
            log.info("参数信息:{}", wthJson.toJSONString());
            JSONObject parmJson = wthJson.getJSONObject("parmNew");
            log.info("参数信息parmJson:{}", parmJson.toJSONString());
            String wspd = "";
            String wdir = "";
            String hpa = "";
            String hum = "";
            String rainfull = "";
            String tmp = "";
            if (ObjectUtil.isNotEmpty(parmJson.getString("WSPD"))) {
                wspd = parmJson.getString("WSPD") + "m/s";
            }
            if (ObjectUtil.isNotEmpty(parmJson.getString("WDIRNAME"))) {
                wdir = parmJson.getString("WDIRNAME");
            }
            if (ObjectUtil.isNotEmpty(parmJson.getString("Hpa"))) {
                hpa = parmJson.getString("Hpa") + "Mpa";
            }
            if (ObjectUtil.isNotEmpty(parmJson.getString("Hum"))) {
                hum = parmJson.getString("Hum") + "%rh";
            }
            if (ObjectUtil.isNotEmpty(parmJson.getString("Rainfull"))) {
                rainfull = parmJson.getString("Rainfull");
            }
            if (ObjectUtil.isNotEmpty(parmJson.getString("Tmp"))) {
                tmp = parmJson.getString("Tmp") + "℃";
            }
            vo.setWspd(wspd)
                    .setWdir(wdir)
                    .setHpa(hpa)
                    .setHum(hum)
                    .setRainfull(rainfull)
                    .setTmp(tmp);
        }
        JSONObject tahJson = dataObject.getJSONObject("TAH");
        if (Objects.nonNull(tahJson)) {
            JSONObject parmJson = tahJson.getJSONObject("parmNew");
            String hum = "";
            String tmp = "";
            if (ObjectUtil.isNotEmpty(parmJson.getString("Hum"))) {
                hum = parmJson.getString("Hum") + "%rh";
            }
            if (ObjectUtil.isNotEmpty(parmJson.getString("Tmp"))) {
                tmp = parmJson.getString("Tmp") + "℃";
            }
            vo.setHum(hum).setTmp(tmp);
        }
        JSONObject mountJson = dataObject.getJSONObject("mount");
        if (Objects.nonNull(mountJson)) {
            String cameraName = "";
            String megaphoneName = "";
            String searchlightName = "";
            if (ObjectUtil.isNotEmpty(mountJson.getString("cameraName"))) {
                cameraName = mountJson.getString("cameraName") + "、";
            }
            if (ObjectUtil.isNotEmpty(mountJson.getString("megaphoneName"))) {
                megaphoneName = mountJson.getString("megaphoneName") + "、";
            }
            if (ObjectUtil.isNotEmpty(mountJson.getString("searchlightName"))) {
                searchlightName = mountJson.getString("searchlightName");
            }
            vo.setMountName(cameraName + megaphoneName + searchlightName);
        }
        String status = "";
        if (ObjectUtil.isNotEmpty(dataObject.getString("status"))) {
            status = dataObject.getString("status");
        }
        vo.setStatus(status);
        return JsonResult.success(vo);
    }

    private JsonResult check(Integer airportId, String airportCode) {
        if (ObjectUtil.isEmpty(airportId) || 0 == airportId) {
            return JsonResult.error("机场id为空");
        }
        if (ObjectUtil.isEmpty(airportCode)) {
            return JsonResult.error("机场code为空");
        }
        return JsonResult.success();
    }

    public List<AirportMsgDto> getMsgList(String tenantCode, String airportCode) {
        String url = UriComponentsBuilder.fromHttpUrl(CommonConfig.airportURL + SystemConstant.API_AIRPORT_GET_AIRPORT_MSG)
                .queryParam("tenantCode", tenantCode)
                .queryParam("airportCode", airportCode)
                .toUriString();
        JsonResult jsonResult;
        try {
            jsonResult = restTemplate.getForObject(url, JsonResult.class);
        } catch (Exception e) {
            log.info("获取机场状态，机场平台返回异常, url:{}", url);
            return null;
        }
        if (0 != jsonResult.getCode()) {
            log.info("获取机场状态，机场平台返回失败，jsonResult={}", jsonResult);
            return null;
        }
        if (ObjectUtil.isEmpty(jsonResult) || (!ObjectUtil.isEmpty(Objects.requireNonNull(jsonResult).getData()) && jsonResult.getCode() != 0)) {
            log.info("获取机场列表失败");
            return null;
        }

        List<Object> list = (List<Object>) jsonResult.getData();
        List<AirportMsgDto> airportMsgDtoList = new ArrayList<>();
        AirportMsgDto airportMsgDto;
        Map<String, String> map;
        for (Object obj : list) {
            map = 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();
                }
                map.put(key, value);
            }
            airportMsgDto = (AirportMsgDto) this.copyObject(map);

            if (ObjectUtil.isNotEmpty(airportMsgDto)) {
                airportMsgDtoList.add(airportMsgDto);
            }
        }
        return airportMsgDtoList;
    }

    public static <T> Object copyObject(Map<String, String> field_Val) {
        Object o;
        try {
            Class clz = AirportMsgDto.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.error("获取机场信息，InstantiationException：{}", e);
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            log.error("获取机场信息，IllegalAccessException：{}", e);
            throw new RuntimeException(e);
        }
        return o;
    }
}
