<template >
  <div class="weatherComponent">
    <div class="left">
      <div class="address">{{location}}</div>
      <div class="temp">{{currentTemp}}°</div>
    </div>
    <div class="center">
      <div>{{desc}}</div>
      <div class="weather-temp"><img :src="require(`@/assets/images/weather-icon/${weatherImage}.png`)" />  {{tempRange}}</div>
      <div class="date-time">
        <span>{{currentDate}}</span>
        <span>{{currentTime}}</span>
      </div>
    </div>
    <div class="right">
      <img :src="require(`@/assets/images/icon/${disasterImage}.png`)" />
      <span>{{disasterData[disasterImage]}}</span>
    </div>
  </div>
</template>

<script>

const disasterData = {
  'yl': '雨涝',
  'nw': '浓雾',
  'xz': '雪灾',
  'gw': '高温',
  'gh': '干旱',
  'gby': '大暴雨'
}

export default {
  name: 'WeatherComponent',
  data() {
    return {
      timer: null,
      // 当前时间
      currentDateTime: new Date(),
      // 天气图片
      weatherImage: '1',
      // 描述
      desc: '晴转多云 降雨量 6mm',
      // 当前温度
      currentTemp: '24',
      // 位置
      location: '北碚区',
      // 温度范围
      tempRange: '18~26°C',
      // 灾害图片
      disasterImage: 'yl',
      disasterData
    }
  },
  computed: {
    currentDate() {
      const month = this.checkNumber(this.currentDateTime.getMonth() + 1)
      const day = this.checkNumber(this.currentDateTime.getDate())
      return `${this.currentDateTime.getFullYear()}${month}${day}`
    },
    currentTime() {
      const hour = this.checkNumber(this.currentDateTime.getHours())
      const minute = this.checkNumber(this.currentDateTime.getMinutes())
      const second = this.checkNumber(this.currentDateTime.getSeconds())  
      return `${hour}:${minute}:${second}`
    }
  },
  methods: {
    checkNumber(ch) {
      if (ch < 10) {
        return '0' + ch;
      }
      return ch
    },
    loadData() {
      this.currentDateTime = new Date();
    }
  },
  mounted() {
    const {loadData} = this
    this.timer = setInterval(() => {
      loadData();
    }, 1000);
  },
  destroyed() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  }
}
</script>

<style scoped lang='less'>
.weatherComponent {
  font-size: 15px;
  width: 362px;
  height: 72px;
  display: flex;
  align-items: center;
  & > div {
    margin: 0px 10px;
  }
  .left {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .temp {
      font-size: 39px;
    }
  }
  .center {
    .date-time {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .weather-temp {
      display: flex;
      gap: 8px;
      align-items: center;
      img {
        width: 40px;
        height: 40px;
      }
    }
  }

  .right {
    display: flex;
    gap: 10px;
    justify-content: flex-start;
    align-items: center;
    img {
      width: 35px;
      height: 35px;
    }
  }
}
</style>
