<template>
  <div class="baseWeather" @click="clickHandler">
    <div v-if="props.mode === 'text'" class="mode-text">
      <i :class="`qi-${weatherIcon}`"> </i>
      <span>{{ weatherText }}</span>
      <span>{{ weatherTemp }}℃</span>
    </div>
    <div v-if="props.mode === 'card'" class="mode-card">
      <i :class="`qi-${weatherIcon}`" class="icon"> </i>
      <div class="desc">
        <span>{{ weatherText }}</span>
        <span>{{ weatherTemp }}℃</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

defineOptions({
  name: 'BaseWeather',
})

type Props = {
  mode: 'text' | 'card'
}
const props = withDefaults(defineProps<Props>(), {
  mode: 'text',
})

const weatherIcon = ref('') // 天气图标
const weatherTemp = ref('') // 天气温度
const weatherFeelsLike = ref('') // 体感温度
const weatherText = ref('') // 天气描述
const weatherwindDir = ref('') // 天气风向
const weatherWindSpeed = ref('') // 风速
const fxLink = ref('') // 天气链接

const getWeather = async () => {
  try {
    const response = await fetch(
      'https://kp36x7gr79.re.qweatherapi.com/v7/weather/now?location=101220101',
      {
        headers: {
          'X-QW-Api-Key': '72afe228cd7f436ebea7caa1345956f2',
        },
      }
    )

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const data = await response.json()
    console.log('天气数据:', data.now)
    fxLink.value = data.fxLink
    weatherIcon.value = data.now.icon
    weatherTemp.value = data.now.temp
    weatherFeelsLike.value = data.now.feelsLike
    weatherText.value = data.now.text
    weatherwindDir.value = data.now.windDir
    weatherWindSpeed.value = data.now.windSpeed
  } catch (error) {
    console.error('获取天气失败:', error)
  }
}
getWeather()

const clickHandler = () => {
  window.open(fxLink.value, '_blank')
}
</script>

<style scoped lang="less">
.baseWeather {
  padding: 0 10px;
  .mode-text {
    display: flex;
    align-items: center;
    gap: 5px;
    cursor: pointer;
  }

  .mode-card {
    display: flex;
    flex-direction: column;
    align-items: center;
    cursor: pointer;

    .icon {
      font-size: 32px;
      line-height: 50px;
      margin-right: 8px;
    }
    .desc {
      font-size: 18px;
      margin-bottom: 8px;
    }
  }
}
</style>
