<template>
  <div class="projectIndex">
    <img src="../assets/images/bg.jpg" class="centerLabel cover bg" alt>
    <div class="content flex-h">
      <div class="left flex-v">
        <div class="weather">
          <div class="date flex-h">
            <span>{{currentDate}}</span>
            <span class="flex-item">{{currentWeek}}</span>
            <span>农历{{currentChineseDate}}</span>
          </div>
          <div class="weatherDetail flex-h">
            <div class="imgData" v-if="weatherDetail">
              <img :src="weatherIcon(weatherDetail.dayweather)" width="100%" alt>
              <span>{{tempRange}}</span>
            </div>
            <div class="flex-item">
              <div v-if="weatherDetail">
                <span>今日 {{ weatherDetail.dayweather }}</span>
                <ul>
                  <li>
                    <span>白天</span>
                    <span>{{weatherDetail.daywind}} 风 {{weatherDetail.daypower}}</span>
                  </li>
                  <li>
                    <span>晚上</span>
                    <span>{{weatherDetail.nightwind}} 风 {{weatherDetail.nightpower}}</span>
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </div>
        <div class="flex-item">
          <div>
            <div class="centerLabel notice">
              <span v-html="(showNew.content || '').replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>').replace(/\s/g, ' ')">
              </span>
              <div>
                <span>{{showNew.publisher}}</span>
                <span>{{FormatDate(showNew.publishDate, 'yyyy年MM月dd日')}}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="flex-item">
        <div :hidden="!showSlide">
          <swiper :options="swiperOption" ref="mySwiper">
            <swiper-slide class="swiper-slide" v-for="(item, index) in showPage" :key="index">
              <img
                v-if="item.showType === 'image'"
                class="centerLabel"
                width="100%"
                height="100%"
                :src="'/api' + item.showContent"
                alt
              >
              <video v-if="item.showType === 'video'" width="100%" height="100%" id="hj-vdo" autoplay muted loop>
                <source :src="'/api' + item.showContent" type="video/mp4" />
              </video>
            </swiper-slide>
          </swiper>
        </div>
        <div :hidden="showSlide">
          <ul class="centerLabel userList">
            <li v-for="(item, index) in userList" :key="index" :class="{'active': item.show}">
              <span>{{item.firstName}}</span>
              <span>{{item.words}}</span>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <audio :src="audioSrc" autoplay :style="{ width: '1px', height: '1px' }" ></audio>
  </div>
</template>

<script>
import { createNamespacedHelpers } from 'vuex'
import 'swiper/dist/css/swiper.css'
import { swiper, swiperSlide } from 'vue-awesome-swiper'
import solarLunar from 'solarLunar'
// import videojs from 'video.js'
const { mapState: mapUserState, mapActions: mapUserActions } = createNamespacedHelpers('user')

const { mapState: mapPageState, mapActions: mapPageActions } = createNamespacedHelpers('page')

const { mapState: mapNewsState, mapActions: mapNewsActions } = createNamespacedHelpers('news')
export default {
  name: 'projectIndex',
  data () {
    return {
      userList: [],
      currentWeek: '周',
      currentTime: '00:00:00',
      currentDate: 'xx年xx月xx日',
      currentChineseDate: 'xx月xx日',
      showSlide: true,
      currentTimeTamp: Date.now(),
      ChineseDate: null,
      activeIndex: 0,
      timer: null,
      timeNum: 0,
      swiperOption: {
        loop: true,
        speed: 1000,
        autoplay: {
          delay: 6000,
          disableOnInteraction: false
        }
      },
      num: 1,
      audioSrc: '',
      personDelay: null
    }
  },
  computed: {
    ...mapUserState({
      weatherInfo: x => x.weatherInfo // 天气信息
    }),
    ...mapPageState({
      pages: x => x.pages
    }),
    ...mapNewsState({
      news: x => x.news
    }),
    showNew () {
      return ((this.news.data || {}).records || []).filter(x => x.status === 1)[0] || {}
    },
    showPage () {
      return ((this.pages.data || {}).records || []).filter(x => x.status === 1) || []
    },
    mySwiper () {
      return this.$refs.mySwiper.swiper
    },
    isDay () {
      return new Date(this.currentTimeTamp).getHours() <= 17 && new Date(this.currentTimeTamp).getHours() >= 6
    },
    weatherDetail () {
      return this.weatherInfo.forecasts[0].casts[0]
    },
    tempRange () {
      if (!this.weatherDetail) return ''
      let min, max

      // 这么复杂是为了避免 eslint 错误
      const f = () => (this.weatherDetail.daytemp) - 0 > (this.weatherDetail.nighttemp - 0)
        ? ((min = this.weatherDetail.nighttemp) | (max = this.weatherDetail.daytemp))
        : ((max = this.weatherDetail.nighttemp) | (min = this.weatherDetail.daytemp))
      f()

      return `${min}℃ ~ ${max}℃`
    }
  },
  components: {
    swiper,
    swiperSlide
  },
  created () {
    window.console.log('---------created---------')

    this.init()
    window.setInterval(() => {
      this.init()
    }, 1000)
    this.getInitData()
    window.setInterval(() => {
      this.getInitData()
    }, 1000 * 60 * 60)
    this.getPersonList()
  },
  updated () {
    this.$nextTick(() => {
      // window.__vcl__111.showTab('log')
      // window.__vcl__111.show()

      const vdo = window.document.getElementById('hj-vdo')
      console.log(vdo)
      if (vdo) {
        vdo.play()
      }
      // videojs('hj-vdo', {
      //   controls: false,
      //   autoplay: true,
      //   loop: true,
      //   muted: true,
      //   preload: 'auto'
      // })
      // const t = window.setInterval(() => {
      //   if (this.$refs.vdo) {
      //     this.$refs.vdo.play()
      //     window.clearInterval(t)
      //   }
      // }, 2000)

      // setTimeout(() => {
      //   window.clearInterval(t)
      // }, 60000)
    })
  },
  methods: {
    ...mapUserActions([
      'getWeatherInfo',
      'getPerson'
    ]),
    ...mapPageActions([
      'getPagesList'
    ]),
    ...mapNewsActions([
      'getNewsList'
    ]),
    returnUserList (item) { // 返回用户信息
      this.showSlide = false
      window.clearInterval(this.timer)
      this.timeNum = 0
      window.setTimeout(() => {
        item.show = true
        this.audioSrc = item.audio
      }, 100)
      if (this.userList.length > 2) {
        this.userList = this.userList.concat(item).slice(1)
      } else {
        this.userList = this.userList.concat(item)
      }
      this.timer = window.setInterval(() => {
        if (this.timeNum - 0 >= 5000) {
          this.timeNum = 0
          window.clearInterval(this.timer)
          this.showSlide = true
          this.userList = []
        } else {
          this.timeNum += 100
        }
      }, 100)
    },
    init () { // 初始化
      this.getDate()
      if (!new Date().getMinutes()) { // 整点更新时间
        this.currentTimeTamp = Date.now()
      }
    },
    getInitData () {
      window.console.log('---------getInitData---------')
      this.getPagesList({
        pageNum: 1,
        pageSize: 100
      })
      this.getNewsList({
        pageNum: 1,
        pageSize: 100
      })
      this.getWeatherInfo()
    },
    getPersonList () {
      this.getPerson().then(res => {
        window.console.log('---------success---------')
        // this.$toast(`${(new Date().valueOf())}---------success---------`)

        if (res && res.isShow) {
          const sex = res.sex === '1' ? '先生' : '女士'
          const voice = res.sex === '2' ? 'm' : 'f'
          const wds = (res.words2 || '').replace('{{name}}', res.personName).replace('{{sex}}', sex)

          this.returnUserList({
            firstName: (res.classId || res.classId === 1) ? '' : res.personName,
            words: wds,
            show: false,
            audio: `http://ycapi.jcjyhn.com/welcome-api/?t=${window.encodeURIComponent(wds)}&u=${voice}&rand=${(new Date()).valueOf()}`
          })
        }

        if (this.personDelay) {
          window.clearTimeout(this.personDelay)
        }

        this.personDelay = setTimeout(() => {
          this.getPersonList()
        }, 500)
      }).catch(r => {
        window.console.log('---------error---------')
        // this.$toast(`${(new Date().valueOf())}---------error---------`)

        if (this.personDelay) {
          window.clearTimeout(this.personDelay)
        }

        this.personDelay = setTimeout(() => {
          this.getPersonList()
        }, 30000)
      })
    },
    FormatDate (timestamp, fmt) {
      if (timestamp === '0001-01-01T00:00:00Z') {
        return ''
      }
      if (!fmt) {
        fmt = 'yyyy-MM-dd hh:mm'
      }

      let date = new Date(timestamp)
      var o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds(),
        'q+': Math.floor((date.getMonth() + 3) / 3),
        'S': date.getMilliseconds()
      }
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
      }
      for (var k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
        }
      }
      return fmt
    },
    getDate () { // 获取当前时间
      let currentTime = Date.now()
      let weekday = ['日', '一', '二', '三', '四', '五', '六']
      let ChineseDate = solarLunar.lunar2solar(new Date(currentTime).getFullYear(), new Date(currentTime).getMonth(), new Date(currentTime).getDate())
      this.currentWeek = `星期${weekday[new Date(currentTime).getDay()]}`
      this.currentTime = `${new Date(currentTime).getHours().toString().padStart(2, '0')} : ${new Date(currentTime).getMinutes().toString().padStart(2, '0')} : ${new Date(currentTime).getSeconds().toString().padStart(2, '0')}`
      this.currentDate = `${new Date(currentTime).getFullYear()}年${(new Date(currentTime).getMonth() + 1).toString().padStart(2, '0')}月${new Date(currentTime).getDate().toString().padStart(2, '0')}日`
      this.currentChineseDate = `${ChineseDate.monthCn}${ChineseDate.dayCn}`
    },
    weatherIcon (target) { // 返回天气图标
      switch (target) {
        case '晴':
          return require('../assets/images/icon-6.png')
        case '少云':
        case '晴间多云':
        case '多云':
          return require('../assets/images/icon-4.png')
        case '阴':
        case '平静':
          return require('../assets/images/icon-9.png')
        case '有风':
        case '微风':
        case '和风':
        case '清风':
        case '强风/劲风':
        case '疾风':
        case '大风':
        case '烈风':
        case '风暴':
        case '狂爆风':
        case '飓风':
        case '热带风暴':
        case '浮尘':
        case '扬沙':
          return require('../assets/images/icon-1.png')
        case '阵雨':
        case '大雨':
        case '中雨-大雨':
        case '大雨-暴雨':
        case '暴雨-大暴雨':
        case '大暴雨-特大暴雨':
        case '暴雨':
        case '大暴雨':
        case '特大暴雨':
        case '强阵雨':
        case '极端降雨':
        case '雷阵雨':
        case '雷阵雨并伴有冰雹':
          return require('../assets/images/icon-5.png')
        case '毛毛雨/细雨':
        case '小雨':
        case '雨':
        case '中雨':
        case '小雨-中雨':
          return require('../assets/images/icon-3.png')
        case '雨夹雪':
        case '阵雨夹雪':
        case '雨雪天气':
        case '冻雨':
          return require('../assets/images/icon-10.png')
        case '阵雪':
        case '小雪':
        case '中雪':
        case '大雪':
        case '暴雪':
        case '小雪-中雪':
        case '中雪-大雪':
        case '大雪-暴雪':
        case '雪':
          return require('../assets/images/icon-2.png')
        case '沙尘暴':
        case '强沙尘暴':
        case '龙卷风':
        case '雾':
        case '浓雾':
        case '强浓雾':
        case '轻雾':
        case '大雾':
        case '特强浓雾':
        case '霾':
        case '中度霾':
        case '重度霾':
        case '严重霾':
        default:
          return require('../assets/images/icon-1.png')
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
.projectIndex {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  .bg {
    z-index: 1;
  }
  > div {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    border: 20px solid transparent;
    z-index: 2;
    position: relative;
    overflow: hidden;
    .left {
      width: 35.5%;
      position: relative;
      overflow: hidden;
      > div {
        background: rgba(255, 255, 255, 0.15);
        border-radius: 6px;
      }
      .weather {
        width: 100%;
        position: relative;
        overflow: hidden;
        margin-bottom: 20px;
        padding: 60px 0;
        .date {
          align-items: center;
          span {
            line-height: 1.6;
            font-size: 1.7vw;
            color: #fff;
            text-align: center;
            &:first-child {
              margin-left: 2.4vw;
            }
            &:last-child {
              margin-right: 2.4vw;
            }
          }
        }
        .weatherDetail {
          padding: 0 20px;
          position: relative;
          overflow: hidden;
          margin-top: 18px;
          .imgData {
            width: 12.6vw;
            position: relative;
            overflow: hidden;
            span {
              width: 100%;
              color: #fff;
              font-size: 2vw;
              line-height: 1.5;
              margin-top: 20px;
              display: block;
            }
          }
          > .flex-item {
            > div {
              width: 100%;
              position: relative;
              overflow: hidden;
              > span {
                width: 100%;
                color: #fff;
                font-size: 1.2vw;
                line-height: 1.8;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
              }
              ul {
                li {
                  border-bottom: 1px solid #b3bcc3;
                  font-size: 0;
                  white-space: nowrap;
                  padding: 6px 0;
                  span {
                    display: inline-block;
                    width: 50%;
                    color: #fff;
                    font-size: 1.3vw;
                    white-space: nowrap;
                    line-height: 1.7;
                  }
                }
              }
            }
          }
        }
      }
      > .flex-item {
        > div {
          width: 100%;
          height: 100%;
          position: relative;
          > .notice {
            width: 100%;
            box-sizing: border-box;
            border-left: 2.4vw solid transparent;
            border-right: 2.4vw solid transparent;
            overflow: hidden;
            h1 {
              text-align: center;
              color: #fff;
              font-size: 1.9vw;
              line-height: 1.6;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              font-weight: normal;
            }
            > span {
              width: 100%;
              display: block;
              color: #fff;
              font-size: 1.2vw;
              line-height: 1.6;
              text-align: justify;
              margin-top: 30px;
            }
            div {
              margin-top: 30px;
              span {
                width: 100%;
                display: block;
                text-align: right;
                color: #fff;
                font-size: 1.2vw;
                line-height: 1.6;
              }
            }
          }
        }
      }
    }
    > .flex-item {
      margin-left: 20px;
      position: relative;
      > div {
        width: 100%;
        height: 100%;
        position: relative;
        overflow: hidden;
        border-radius: 6px;
        .swiper-container {
          width: 100%;
          height: 100%;
          position: relative;
        }
        .userList {
          width: 35vw;
          overflow: hidden;
          transition: all 0.3s linear;
          -webkit-transition: all 0.3s linear;
          > li {
            width: 100%;
            position: relative;
            overflow: hidden;
            background: rgba(255, 255, 255, 0.15);
            margin: 1.8vh auto 0;
            padding: 9vh 0;
            transform: translateY(100vh);
            -webkit-transform: translateY(100vh);
            transition: all 0.3s linear;
            -webkit-transition: all 0.3s linear;
            &:first-child {
              margin-top: 0;
            }
            &.active {
              transform: translateY(0);
              -webkit-transform: translateY(0);
            }
            span {
              width: 100%;
              display: block;
              color: #fff;
              text-align: center;
              line-height: 1.45;
              font-size: 2.3vw;
              &:first-child {
                font-size: 2.8vw;
                line-height: 1.3;
              }
            }
          }
        }
      }
    }
  }
}
</style>
