<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" v-if="pageDetail !== null && (pageDetail.detail.noticeShow || pageDetail.detail.weatherShow)">
        <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="pageDetail.detail.weatherShow">
              <img :src="weatherIcon(weatherDetail.weather)" 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.indexOf('级') > 0 ? weatherDetail.daypower : `${weatherDetail.daypower} 级`}}</span>
                  </li>
                  <li>
                    <span>晚上</span>
                    <span>{{weatherDetail.nightwind}} 风 {{weatherDetail.nightpower.indexOf('级') > 0 ? weatherDetail.nightpower : `${weatherDetail.nightpower} 级`}}</span>
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </div>
        <div class="flex-item" v-if="pageDetail !== null && pageDetail.notice && pageDetail.notice.length">
          <div>
            <div class="centerLabel notice">
              <span v-html="(pageDetail.notice[0].content || '').replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>').replace(/\s/g, ' ')"></span>
              <div>
                <span>{{pageDetail.notice[0].publisher}}</span>
                <span>{{pageDetail.notice[0].publishDate}}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="flex-item">
        <div :hidden="!!users.length" v-if="pageDetail !== null">
          <swiper :options="swiperOption" ref="mySwiper">
            <swiper-slide class="swiper-slide" v-for="(item, index) in pageDetail.content" :key="index">
              <img v-if="pageDetail.detail.contentType === 'image'" class="centerLabel" width="100%" height="100%" :src="item.content" alt>
              <video v-if="pageDetail.detail.contentType === 'video'" width="100%" height="100%" id="hj-vdo" autoplay muted loop>
                <source :src="item.content" type="video/mp4">
              </video>
            </swiper-slide>
          </swiper>
        </div>
        <div :hidden="!users.length">
          <transition-group class="centerLabel userList" tag="ul" name="fade">
            <li v-for="(user, k) in users" :key="k" class="fade-item">
              <span>{{user.name}}</span>
              <span>{{user.words}}</span>
            </li>
          </transition-group>
          <div v-if="audios.length > 0" :hidden="true">
            <div v-for="(audio, k) in audios" :key="k">
              <audio v-if="audio.isShow" @ended="audioEnd(k)" autoplay>
                <source :src="audio.url">
              </audio>
            </div>
          </div>
        </div>
      </div>
    </div>
  </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 XWebSocket from '../util/websocket'
const { mapState: mapPageState, mapActions: mapPageActions, mapMutations: mapPageMutations } = createNamespacedHelpers('newIndex')
export default {
  name: 'projectIndex',
  data () {
    return {
      ws: null,
      users: [],
      audios: [],
      diffM: 5000,
      currentDate: '',
      currentWeek: '',
      currentChineseDate: '',
      showSlide: false,
      currentTimeTamp: Date.now(),
      activeIndex: 0,
      timer: null,
      timeNum: 0,
      swiperOption: {
        speed: 1000,
        autoplay: {
          delay: 6000,
          disableOnInteraction: false
        }
      },
      num: 1,
      personDelay: null,
      pageTimer: null
    }
  },
  computed: {
    ...mapPageState({
      pageDetail: x => x.pageDetail
    }),
    mySwiper () {
      return this.$refs.mySwiper.swiper
    },
    weatherDetail () {
      let target = this.pageDetail.weather ? JSON.parse(this.pageDetail.weather) : undefined
      return !target ? undefined : target.forecasts[0].casts[0]
    },
    tempRange () {
      if (!this.weatherDetail) return ''
      let min, max
      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 () {
    // const _that = this
    window.setInterval(() => {
      let dels = this.users.filter(x => Date.parse(new Date()) - x.createdata > this.diffM)
      dels.forEach(x => {
        const inx = this.users.findIndex(i => i.createdata === x.createdata)
        this.users.splice(inx, 1)
      })
      let delaudios = this.audios.filter(x => Date.parse(new Date()) - x.createdata > this.diffM)
      delaudios.forEach(x => {
        const inx = this.audios.findIndex(i => i.createdata === x.createdata)
        this.audios.splice(inx, 1)
      })
    }, 100)
    this.ws = new XWebSocket({
      message: this.receviedMsg.bind(this),
      delay: 10,
      autoConnect: true
    })

    const wsURI = `${window.location.origin.replace('http', 'ws')}/api/websocket/${this.$route.query.id}`
    this.ws.connect(wsURI)
    this.init()
    this.pageTimer = window.setInterval(() => {
      let curMin = new Date().getMinutes() - 0
      let curHour = new Date().getHours() - 0
      let curSec = new Date().getSeconds() - 0
      if (!curMin && !curSec) { // 整点刷新请求
        if (curHour === 1 && !curSec) { // 1点刷新页面
          window.clearInterval(this.pageTimer)
          window.location.reload()
        }
        // this.init()
      }
    }, 1000)
  },
  mounted () {
  },
  updated () {
    this.$nextTick(() => {
      // const ados = window.document.getElementsByTagName('audio')
      // if (ados && ados.length) {
      //   Array.prototype.forEach.call(ados, (ado) => {
      //     ado.muted = false
      //     ado.play()
      //   })
      // }
    })
  },
  methods: {
    ...mapPageActions([
      'getNewIndex'
    ]),
    ...mapPageMutations([
      'emptyPageDetail'
    ]),
    newData (info) {
      if (info.classId - 0 === 1 && this.users.filter(x => x.classId - 0 === 1).length > 0) {
        this.users = this.users.map((x) => {
          if (x.classId - 0 === 1) {
            return { ...x, createdata: Date.parse(new Date()) }
          } else {
            return x
          }
        })
      } else {
        if (this.users.length >= 3) {
          this.users.splice(0, 1)
        }
        this.users = [...this.users, { ...info, createdata: Date.parse(new Date()) }]
        this.audios = [...this.audios, { ...info, isShow: true, createdata: Date.parse(new Date()) }]
      }
    },
    audioEnd (index) {
      this.audios = this.audios.slice().map((x, i) => {
        if (i === index) {
          x.isShow = false
        }
        return x
      })
    },
    receviedMsg (e) {
      const msg = e.data
      if (!msg) {
        return
      }

      const res = JSON.parse(e.data)
      if (res.type && res.type === 'cmd') {
        // 如果这种类型的消息, 说明是行为控制
        switch (res.data) {
          // 刷新数据
          case 'refresh':
            window.location.reload()
            break
          default:
            break
        }
      } else {
        this.newData({
          name: !res.person.name ? '' : res.person.name,
          classId: res.person.typeId,
          words: res.taVisitingWords.words,
          url: res.audio
        })
      }
    },
    init () { // 初始化
      this.emptyPageDetail()
      this.getDate()
      this.getNewIndex(this.$route.query.id)
    },
    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 {
  $mainfontcolor: #000;

  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
  .fade-item {
    transition: all 1s;
    display: inline-block;
  }
  .fade-enter,
  .fade-leave-to {
    opacity: 0;
  }
  .fade-leave-active {
    position: absolute;
  }
  .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: $mainfontcolor;
            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: $mainfontcolor;
              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: $mainfontcolor;
                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: $mainfontcolor;
                    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: $mainfontcolor;
              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: $mainfontcolor;
              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: $mainfontcolor;
                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;
            &:first-child {
              margin-top: 0;
            }
            span {
              width: 100%;
              display: block;
              color: $mainfontcolor;
              text-align: center;
              line-height: 1.45;
              font-size: 2.6vw;
              &:first-child {
                font-size: 3.2vw;
                line-height: 1.3;
              }
            }
          }
        }
      }
    }
  }
}
</style>
