<!--
 * @Description: 天气组件，中国天气网数据
 * @Author: 王晓颖
 * @Date: 2021-04-06 09:24:09
 -->
<template>
  <div class="topWeather">
    <ul v-if="weatherInfo.length>0" class="weather-ul">
      <li v-for="(day,i) in weatherInfo" :key="i" class="weather-li">
        <!--只展示今天昨天数据-->
        <div v-if="i < days">
          <img :src="day.type | weatherFilter">
          {{ i | daysFilter }}&nbsp;
          <!--夜间温度，日间温度-->
          <a class="gradient-text">{{ day.low | formatWeather }}~{{ day.high | formatWeather }}</a>
        </div>
      </li>
    </ul>
  </div>
</template>

<script>
import { getWeather } from '@/api/common'
export default {
  name: 'Weather',
  filters: {
    daysFilter(day) {
      switch (day) {
        case 0: return '今天'
        case 1: return '明天'
        case 2: return '后天'
        case 3: return '大后天'
      }
    },
    weatherFilter(weather) {
      switch (weather) {
        case '晴': return require(`@/assets/weather_images/weather-qing.png`)
        case '多云': return require(`@/assets/weather_images/weather-duoyun.png`)
        case '阴': return require(`@/assets/weather_images/weather-yin.png`)
        case '雨': return require(`@/assets/weather_images/weather-yu.png`)
        case '小雨': return require(`@/assets/weather_images/weather-xiaoyu.png`)
        default: return require(`@/assets/weather_images/weather-yin.png`)
      }
    },
    formatWeather(weather) {
      const str = weather.split(' ')
      return str[1]
    }
  },
  props: {
    city: {
      type: String,
      default: '太原'
    }, // 城市
    days: {
      type: Number,
      default: 2
    } // 显示几天数据
  },
  data() {
    return {
      weatherInfo: [] // 天气情况
    }
  },
  created() {
    this.fetchWeather() // 获取天气
  },
  methods: {
    fetchWeather() {
      getWeather(this.city).then(res => {
        if (res.data) {
          this.weatherInfo = res.data.forecast
        }
      }, e => {
        console.log('获取天气失败', e)
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .topWeather{
    position: fixed;
    z-index:100;
    top:0.1rem;
    right:0.5rem;
    .weather-ul{
      /*display:inline-block;*/
      display: flex;
    }
    .weather-li{
      display: flex;
      align-items: center;
      font-size: 1rem;
      color:#FFF;
      margin-right: 1rem;
    }
    .weather-li img{
      width:1.2rem;
      height:1.2rem;
      margin-right: .3rem;
    }
    .weather-li a{
      font-size: 1rem;
      font-weight: bolder;
    }
    .weather-li:last-child{
      margin-right: 0;
    }
  }
</style>
