<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.day_weather_code)" width="100%" alt>
              <span>{{tempRange}}</span>
            </div>
            <div class="flex-item">
              <div v-if="weatherDetail">
                <span>今日 {{ weatherDetail.day_weather }} {{weatherDetail.index.gj.title}}外出</span>
                <ul>
                  <li>
                    <span>{{weatherDetail.wind_direction}}{{weatherDetail.wind_power}}</span>
                    <span>空气湿度: {{weatherDetail.sd}}</span>
                  </li>
                  <li>
                    <span>体感温度: {{weatherDetail.temperature}}</span>
                    <span>空气指数: {{weatherDetail.aqi}}</span>
                  </li>
                  <li>
                    <span>PM2.5: {{weatherDetail.aqiDetail.pm2_5}}</span>
                    <span>穿衣指数: {{weatherDetail.index.clothes.title}}</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="getLocalPath(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>
      <x-maquee class="marquee">
        <ul>
          <li v-for="item in sharesData" :key="item.WindCode">
            <span class="shares-name font24">{{item.Name}}</span>
            <span class="shares-price font24">{{item.Price}}</span>
            <span :class="{font24: true, ['shares-rate']: true, green: item.ChangeRate < 0, red: item.ChangeRate > 0 }">{{item.ChangeRate > 0 ? '+' : ''}}{{item.ChangeRate}}%</span>
          </li>
        </ul>
      </x-maquee>
  </div>
</template>

<script>
import md5 from 'md5'
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'
import getShares from '../util/shares'

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,
      assetdir: undefined,
      city: '',
      sharesData: []
    }
  },
  computed: {
    ...mapPageState({
      pageDetail: x => x.pageDetail
    }),
    mySwiper () {
      return this.$refs.mySwiper.swiper
    },
    weatherDetail () {
      let target = this.pageDetail.weather ? JSON.parse(this.pageDetail.weather) : undefined

      if (!target) return undefined

      const { f1, now } = target.showapi_res_body
      return { ...f1, ...now }
    },
    tempRange () {
      if (!this.weatherDetail) return ''
      let min, max
      const f = () => (this.weatherDetail.day_air_temperature) - 0 > (this.weatherDetail.night_air_temperature - 0)
        ? ((min = this.weatherDetail.night_air_temperature) | (max = this.weatherDetail.day_air_temperature))
        : ((max = this.weatherDetail.night_air_temperature) | (min = this.weatherDetail.day_air_temperature))
      f()
      return `${min}℃ ~ ${max}℃`
    }
  },
  components: {
    swiper,
    swiperSlide,
    XMaquee: () => import('../components/XMaquee')
  },
  created () {
    this.assetdir = this.$route.query.assets || this.assetdir
    this.city = this.$route.query.city || this.city

    getShares().then(dt => (this.sharesData = dt))
    window.setInterval(() => {
      getShares().then(dt => (this.sharesData = dt))
    }, 60000)

    // 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
    })

    window.console.log(this.$route.query.id, this.$route.query)

    const wsURI = `${window.location.origin.replace('http', 'ws')}/api/ws/${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'
    ]),
    getLocalPath (url = '') {
      if (!this.assetdir) return url

      const ext = url.split('.').pop()
      return `${this.assetdir}\\${md5(url)}.${ext}`
    },
    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({ id: this.$route.query.id, city: this.city })
    },
    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 '晴':
        case '00':
          return require('../assets/images/icon-6.png')
        case '少云':
        case '晴间多云':
        case '多云':
        case '01':
          return require('../assets/images/icon-4.png')
        case '阴':
        case '平静':
        case '02':
          return require('../assets/images/icon-9.png')
        case '有风':
        case '微风':
        case '和风':
        case '清风':
        case '强风/劲风':
        case '疾风':
        case '大风':
        case '烈风':
        case '风暴':
        case '狂爆风':
        case '飓风':
        case '热带风暴':
        case '浮尘':
        case '扬沙':
        case '29':
        case '30':
          return require('../assets/images/icon-1.png')
        case '阵雨':
        case '大雨':
        case '中雨-大雨':
        case '大雨-暴雨':
        case '暴雨-大暴雨':
        case '大暴雨-特大暴雨':
        case '暴雨':
        case '大暴雨':
        case '特大暴雨':
        case '强阵雨':
        case '极端降雨':
        case '雷阵雨':
        case '雷阵雨并伴有冰雹':
        case '03':
        case '04':
        case '05':
        case '06':
        case '09':
        case '10':
        case '11':
        case '12':
        case '22':
        case '23':
        case '24':
        case '25':
          return require('../assets/images/icon-5.png')
        case '毛毛雨/细雨':
        case '小雨':
        case '雨':
        case '中雨':
        case '小雨-中雨':
        case '07':
        case '08':
        case '21':
        case '301':
          return require('../assets/images/icon-3.png')
        case '雨夹雪':
        case '阵雨夹雪':
        case '雨雪天气':
        case '冻雨':
        case '19':
          return require('../assets/images/icon-10.png')
        case '阵雪':
        case '小雪':
        case '中雪':
        case '大雪':
        case '暴雪':
        case '小雪-中雪':
        case '中雪-大雪':
        case '大雪-暴雪':
        case '雪':
        case '13':
        case '14':
        case '15':
        case '16':
        case '17':
        case '26':
        case '27':
        case '28':
        case '302':
          return require('../assets/images/icon-2.png')
        case '沙尘暴':
        case '强沙尘暴':
        case '龙卷风':
        case '雾':
        case '浓雾':
        case '强浓雾':
        case '轻雾':
        case '大雾':
        case '特强浓雾':
        case '霾':
        case '中度霾':
        case '重度霾':
        case '严重霾':
        case '18':
        case '20':
        case '31':
        case '53':
        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 #eee;
                  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;
              }
            }
          }
        }
      }
    }
  }
}

.marquee {
  width: 100%;
  position: absolute !important;
  bottom: 2px;
  left: 0;
  height: 48px !important;
  z-index: 999 !important;
  color: #fff;
  letter-spacing: 0.05em;
  line-height: 48px;
  background-color: rgba(0, 0, 0, 0.7);
  font-weight: 700;
  border: none !important;

  .font24 {
    font-size: 24px;
  }

  ul {
    list-style: none;
    background: transparent;
  }

  li {
    display: inline;
    & + li {
      margin-left: 20px;
      padding-left: 20px;
      border-left: 1px solid #fff;
    }
  }

  .shares-name {
    color: #b49076;
  }

  .green {
    color: green;
  }

  .red {
    color: red;
  }
}
</style>
