<template>
  <div class="weather-card">
    <div class="cloud-bg">
      <div class="basic-info">
        <div>
          <div class="location">上海市</div>
          <div class="date-time">
            <span>{{ currentDate }}</span>
            <span>{{ currentWeek }}</span>
            <span>{{ currentTime }}</span>
          </div>
        </div>
        <div class="weather-info">
          <div class="temperature">{{ curTemperature || '--' }}℃</div>
          <div class="wind">
            <div>
              风速:
              <span class="wind-value">{{ curWindVelocity || '--' }} km/h</span>
            </div>
            <div>
              风力:
              <span class="wind-value">{{ windSpeedLevel || '--' }}级</span>
            </div>
          </div>
        </div>
      </div>
      <div class="disaster-emergency-tips">
        <WeatherTips :title="measureTitle" :measure="measureInfo" :disasterWarningList="todayWarningInfo" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, onUnmounted, ref, watch } from 'vue';
  import dayjs from 'dayjs';
  import WeatherTips from './weather-info/WeatherTips.vue';
  import { SysDictDataDetail, queryDictTypeDetail } from '@/api/dict';
  import { getTodayDisasterWarnInfoList, getRealTimeWeatherData } from '@/api/disaster-overview';

  export interface DisasterWarningListType {
    disasterType: string;
    disasterName: string;
  }

  const currentDate = ref('');
  const currentWeek = ref('');
  const currentTime = ref('');
  let timer: NodeJS.Timeout;
  const weatherDisasterDic = ref<SysDictDataDetail[]>([]); // 气象灾害预警字典
  const disasterMeasureDic = ref<SysDictDataDetail[]>([]); // 灾害应急措施字典
  const todayWarningInfo = ref<DisasterWarningListType[]>([]); // 今日灾害预警信息
  const measureTitle = ref<string | undefined>('');
  const measureInfo = ref<string | undefined>('');

  const curTemperature = ref('0');
  const curWindVelocity = ref(0);
  const windSpeedLevel = ref(0);
  // 风速km/h等级换算表
  const windLevels = [
    { max: 1, level: 0 },
    { max: 5, level: 1 },
    { max: 11, level: 2 },
    { max: 19, level: 3 },
    { max: 28, level: 4 },
    { max: 38, level: 5 },
    { max: 49, level: 6 },
    { max: 61, level: 7 },
    { max: 74, level: 8 },
    { max: 88, level: 9 },
    { max: 102, level: 10 },
    { max: 117, level: 11 },
    { max: 133, level: 12 },
    { max: 149, level: 13 },
    { max: 166, level: 14 },
    { max: 183, level: 15 },
    { max: 201, level: 16 },
    { max: 220, level: 17 },
    { max: Infinity, level: 18 },
  ];

  const getWindLevel = (windSpeedKmh: number): number => {
    const matched = windLevels.find(({ max }) => windSpeedKmh <= max);
    return matched ? matched.level : 18;
  };

  watch(
    () => curWindVelocity.value,
    (newVal) => {
      windSpeedLevel.value = getWindLevel(newVal);
    },
  );

  // 更新时间函数
  const updateDateTime = () => {
    const now = dayjs();
    currentDate.value = now.format('MM月DD日');
    currentWeek.value = `星期${now.format('dd').slice(-1)}`;
    currentTime.value = now.format('HH:mm:ss');
  };

  // 获取实时天气数据
  const getRealTimeWeatherDataInfo = async () => {
    const res = await getRealTimeWeatherData();
    curTemperature.value = res?.temperature || '0';
    curWindVelocity.value = (res?.windVelocity || 0) * 3.6;
  };

  function getWeatherWarningType(val: string) {
    const match = val.match(/^[a-zA-Z0-9]+/);
    if (!match) return;
    return match[0];
  }

  // 获取今日灾害预警信息
  const getTodayWarningInfo = async () => {
    todayWarningInfo.value = (await getTodayDisasterWarnInfoList())?.map((item) => ({
      disasterType: item.disasterType,
      disasterName:
        weatherDisasterDic.value.find((dic) => dic.itemCode === item.disasterType)?.itemValue || '未知预警信息',
    }));

    const normalMeasure = disasterMeasureDic.value.find((item) => item.itemCode === 'normal_measure');

    if (todayWarningInfo.value.length === 0) {
      measureTitle.value = '安全提示';
      measureInfo.value = normalMeasure?.itemValue || '暂无提示';
    } else {
      const todayWarningValue = todayWarningInfo.value.find(
        (item) => item.disasterType === todayWarningInfo.value[0].disasterType,
      )?.disasterType;
      if (todayWarningValue) {
        const weatherWarningType = getWeatherWarningType(todayWarningValue);
        if (weatherWarningType) {
          const targetMeasure = disasterMeasureDic.value.find((item) => item.itemCode.includes(weatherWarningType));
          measureTitle.value = targetMeasure?.itemValue ? '应急提示' : '安全提示';
          measureInfo.value = targetMeasure?.itemValue || normalMeasure?.itemValue;
        }
      }
    }
  };

  onMounted(async () => {
    await queryDictTypeDetail('weather_warning').then((res) => {
      weatherDisasterDic.value = res.sysDictDataList;
    });
    await queryDictTypeDetail('disaster_emergency_measure').then((res) => {
      disasterMeasureDic.value = res.sysDictDataList;
    });
    updateDateTime();
    timer = setInterval(updateDateTime, 1000);
    getRealTimeWeatherDataInfo();
    getTodayWarningInfo();
  });

  onUnmounted(() => {
    clearInterval(timer);
  });
</script>

<style lang="scss" scoped>
  .weather-card {
    width: 100%;
    height: 267px;
    background: linear-gradient(90deg, #b4ccff 0%, #e4fbf9 100%);
    border-radius: 4px;
  }

  .cloud-bg {
    width: 100%;
    height: 100%;
    display: flex;
    padding: 16px;
    background-image: url('@/assets/images/disaster-overview/cloud-bg.png');
    background-repeat: no-repeat;
    background-position: left top;
    background-size: auto 100%;
  }

  .basic-info {
    width: 305px;
    margin: 4px 35px 32px 12px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .location {
      font-weight: 500;
      font-size: 20px;
      color: #0f3d7d;
      margin-bottom: 8px;
    }

    .date-time {
      font-weight: 400;
      font-size: 16px;
      color: #0f3d7d;
      display: flex;
      gap: 6px;
    }

    .weather-info {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .temperature {
        font-weight: bold;
        font-size: 63px;
        color: #0f3d7d;
      }

      .wind {
        display: flex;
        flex-direction: column;
        gap: 7px;
        font-weight: 400;
        font-size: 16px;
        color: #0f3d7d;
      }

      .wind-value {
        font-weight: 500;
      }
    }
  }

  .disaster-emergency-tips {
    flex: 1;
  }
</style>
