<template>
  <section class="videos-container">
    <div class="videos-wrap">
      <div class="bread-crumbs">
        <a
          :href="`${wwwURL}/${$store.state.locale}`"
          class="ele link"
          target="_blank">{{ $t("home") }}</a>
        <span class="ele arrow">></span>
        <a
          :href="`/${$store.state.locale}`"
          class="ele link">{{ $t("community") }}</a>
        <span class="ele arrow">></span>
        <a
          class="ele link disable"
          href="javascript:void(0);">{{ $t("tabVideos") }}</a>
      </div>
      <ul
        v-if="videoArr.length>0"
        class="video-grid">
        <li
          v-for="(item,index) in videoArr"
          :key="index"
          class="video-box">
          <video-item
            :video-obj="item"
            @handlePlayVideo="handlePlayVideo"/>
        </li>
      </ul>
      <template v-else>
        <empty :empty-obj="{'tips': $t('noVideoData')}"/>
      </template>
      <div
        v-if="isMounted&&totalCount>pageSize"
        class="pagination-container">
        <paginate
          v-model="page"
          :page-count="Math.ceil(totalCount/pageSize)"
          :page-range="3"
          :margin-pages="2"
          :prev-text="$t('paginationPrev')"
          :next-text="$t('paginationNext')"
          :click-handler="paginationClickCallback"
          :container-class="'pagination'"
          :page-class="'page-item'"
          :page-link-class="'page-item-link'"
          :prev-class="'page-prev-item'"
          :prev-link-class="'page-prev-item-link'"
          :next-class="'page-next-item'"
          :next-link-class="'page-next-item-link'"
          :hide-prev-next="true"/>
      </div>
    </div>
    <div
      v-if="currentVideoItem&&currentVideoItem.videoUrl"
      class="video-mask"
      @click="handleCloseVideo"
    >
      <div
        class="video-inner animated zoomIn faster"
        @click.stop="handleStopBubble">
        <video
          id="myVideo"
          :poster="currentVideoItem.coverImg"
          class="video-js vjs-big-play-centered video-player"
          controls
          preload="auto"
          autoplay
        />
        <span
          class="iconfont icon-guanbi1"
          @click="handleCloseVideo"/>
      </div>
    </div>
  </section>
</template>

<script>
import Vue from 'vue'
import { php_api_video_list, php_api_video_hit } from '~/common/apis.js'
import { loadSrc } from '~/common/utils.js'
import VideoItem from '~/components/videos/VideoItem'
import Empty from '~/components/common/Empty.vue'
import { wwwURL } from '~/common/config.js'

const PAGE_SIZE = 20

export default {
  async asyncData({ app, query, store }) {
    let { page } = query
    if (page) {
      page = parseInt(page)
    } else {
      page = 1
    }
    let pageSize = PAGE_SIZE
    let totalCount = 0
    let videoArr = await app.$axios
      .$post(php_api_video_list, { page, pageSize })
      .then(res => {
        if (res) {
          let { code, data } = res
          code = parseInt(code)
          if (code === 0 && data) {
            totalCount = data.totalCount
            if (Array.isArray(data.list)) {
              return data.list
            }
          }
        }
        return []
      })
      .catch(e => {
        return []
      })
    return { page, pageSize, videoArr, totalCount }
  },
  validate({ query, store, route, redirect }) {
    if (!query.hasOwnProperty('page')) {
      return true
    }
    let { page } = query
    if (/^[0-9]+$/.test(page) && parseInt(page) !== 0 && parseInt(page) !== 1) {
      return true
    } else {
      let { fullPath } = route
      let { locales, locale } = store.state
      let flag = false
      locales.some(val => {
        if (fullPath.indexOf(`/${val}`) === 0) {
          flag = true
          return true
        }
      })
      if (flag) {
        return redirect(`/${locale}/videos`)
      } else {
        return redirect(`/videos`)
      }
    }
  },
  head() {
    return {
      script: [
        {
          type: 'text/javascript',
          src: '//static.hoolihome.com/common/vuejs-paginate/index.js'
        }
      ]
    }
  },
  components: { VideoItem, Empty },
  data() {
    return {
      wwwURL,
      page: 1,
      pageSize: PAGE_SIZE,
      videoArr: [],
      currentVideoItem: null,
      myVideoPlayer: null,
      totalCount: 0,
      isMounted: false
    }
  },
  scrollToTop: true,
  beforeCreate() {
    if (process.client && window.VuejsPaginate) {
      Vue.component('paginate', window.VuejsPaginate)
    }
  },
  mounted() {
    this.isMounted = true
    this.loadVideoSrc()
    this.$hooliAnalysis.upload({
      et: this.$C.EVENT_TYPE.show
    })
  },
  methods: {
    handlePlayVideo(videoItem) {
      if (!window.videojs) {
        return false
      }
      this.currentVideoItem = videoItem
      this.$nextTick(() => {
        if (!this.myVideoPlayer) {
          this.myVideoPlayer = window.videojs('myVideo', {
            autoplay: true,
            controls: true
          })
        }
        let mimeType = ''
        if (videoItem.videoUrl.toLowerCase().indexOf('.m3u8') !== -1) {
          mimeType = 'application/x-mpegURL'
        } else if (videoItem.videoUrl.toLowerCase().indexOf('.mp4') !== -1) {
          mimeType = 'video/mp4'
        }
        // videoItem.videoUrl =
        //   'https://files.hoolihome.com/m3u8/index/1116/20181116170224_544.m3u8'
        this.myVideoPlayer.src({
          src: videoItem.videoUrl,
          type: mimeType
        })
        this.myVideoPlayer.play()
      })
      this.updateVideoBrowseVolume(videoItem.id)
    },
    handleCloseVideo() {
      if (this.myVideoPlayer) {
        this.myVideoPlayer.pause()
        this.myVideoPlayer.dispose()
        this.myVideoPlayer = null
      }
      this.currentVideoItem = null
    },
    handleStopBubble() {},
    loadVideoSrc() {
      loadSrc(
        '//static.hoolihome.com/common/video.js/video-js.min.css',
        'VIDEO_LINK_ID',
        'css'
      ).then(() => {
        loadSrc(
          '//static.hoolihome.com/common/video.js/video.min.js',
          'VIDEO_SCRIPT_ID',
          'js'
        )
      })
    },
    loadData() {
      this.$axios
        .$post(php_api_video_list, {
          page: this.page,
          pageSize: this.pageSize
        })
        .then(res => {
          if (res) {
            let { code, data } = res
            code = parseInt(code)
            if (code === 0 && data && Array.isArray(data.list) && data) {
              let { list } = data
              if (Array.isArray(list) && list.length > 0) {
                this.videoArr = data.list
                return false
              }
            }
          }
          this.videoArr = []
        })
        .catch(e => {
          this.videoArr = []
        })
    },
    paginationClickCallback(pageNum) {
      let { path, query } = this.$route
      let queryArr = []
      query.page = pageNum
      for (let key in query) {
        queryArr.push(`${key}=${query[key]}`)
      }
      window.location.href = `${path}?${queryArr.join('&')}`
    },
    updateVideoBrowseVolume(id) {
      this.$axios
        .$post(php_api_video_hit, { id })
        .then(res => {})
        .catch(e => {})
    }
  }
}
</script>

<style lang="less">
.video-inner {
  .vjs-paused .vjs-big-play-button,
  .vjs-paused.vjs-has-started .vjs-big-play-button {
    display: block;
  }
  .video-js .vjs-big-play-button {
    font-size: 2.5em;
    line-height: 2.3em;
    height: 2.5em;
    width: 2.5em;
    -webkit-border-radius: 2.5em;
    -moz-border-radius: 2.5em;
    border-radius: 2.5em;
    background-color: #73859f;
    background-color: rgba(115, 133, 159, 0.5);
    border-width: 0.15em;
    margin-top: -1.25em;
    // margin-left: -1.75em;
  }
  /* 中间的播放箭头 */
  .vjs-big-play-button .vjs-icon-placeholder {
    font-size: 1.63em;
  }
  /* 加载圆圈 */
  .vjs-loading-spinner {
    font-size: 2.5em;
    width: 2em;
    height: 2em;
    border-radius: 1em;
    margin-top: -1em;
    margin-left: -1.5em;
  }
  .video-js.vjs-playing .vjs-tech {
    pointer-events: auto;
  }
  .video-js .vjs-big-play-button .vjs-icon-placeholder:before,
  .video-js .vjs-modal-dialog,
  .vjs-button > .vjs-icon-placeholder:before,
  .vjs-modal-dialog .vjs-modal-dialog-content {
    position: relative;
  }
}
.videos-container {
  .pagination {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .page-prev-item,
    .page-next-item {
      height: 24px;
      line-height: 24px;
      margin-right: 2px;
      padding: 0 7px;
      font-size: 12px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      color: rgba(255, 255, 255, 1);
      background-color: #ed5f48;
      border-radius: 2px;
      outline: none;
      &.disabled {
        pointer-events: none;
        background-color: #d6d6d6;
      }
      .page-prev-item-link,
      .page-next-item-link {
        display: inline-block;
        outline: none;
      }
    }
    .page-item {
      height: 24px;
      line-height: 24px;
      margin-right: 2px;
      outline: none;
      border-radius: 2px;
      &.active {
        pointer-events: none;
        background-color: #ed5f48;
        .page-item-link {
          color: #ffffff;
        }
      }
      &:not(.active) {
        &:hover {
          background-color: #eeeeee;
        }
      }
      .page-item-link {
        display: inline-block;
        padding: 3px 7px;
        font-size: 12px;
        font-family: PingFangSC-Regular;
        font-weight: 400;
        color: rgba(102, 102, 102, 1);
        outline: none;
      }
    }
  }
}
</style>

<style lang="less" scoped>
.videos-container {
  .videos-wrap {
    margin: 0 auto;
    .bread-crumbs {
      display: flex;
      align-items: center;
      width: 1200px;
      height: 50px;
      margin: 0 auto;
      padding: 0 5px;
      .ele {
        display: inline-block;
        height: 17px;
        line-height: 17px;
        margin-right: 10px;
        font-size: 12px;
        font-family: PingFangSC-Regular;
        font-weight: 400;
        color: rgba(153, 153, 153, 1);
        &.link {
          &:hover {
            color: #ed5f48;
          }
          &.disable {
            pointer-events: none;
          }
        }
      }
    }
    .video-grid {
      display: flex;
      flex-flow: row wrap;
      width: 1200px;
      margin: 0 auto;
      padding-left: 5px;
      .video-box {
        width: 272px;
        height: 265px;
        margin: 0 34px 30px 0;
        &:nth-child(4n + 4) {
          margin-right: 0px;
        }
      }
    }
    .pagination-container {
      width: 1200px;
      margin: 10px auto 90px;
      padding: 0 5px;
    }
  }
  .video-mask {
    position: fixed;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    z-index: 10;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: rgba(0, 0, 0, 0.7);
    cursor: pointer;
    -webkit-transition: opacity 350ms cubic-bezier(0.165, 0.84, 0.44, 1);
    transition: opacity 350ms cubic-bezier(0.165, 0.84, 0.44, 1);
    .video-inner {
      position: relative;
      width: 711px;
      height: 401px;
      box-shadow: 0px 3px 8px 0px rgba(0, 0, 0, 0.17);
      border-radius: 8px;
      background-color: #000000;
      animation-duration: 0.3s;
      .video-player {
        position: relative;
        width: 100%;
        height: 100%;
        border-radius: 8px;
      }
      .icon-guanbi1 {
        position: absolute;
        top: -27px;
        right: 0px;
        color: #ffffff;
        font-size: 12px;
        cursor: pointer;
      }
    }
  }
}
@-webkit-keyframes zoomIn {
  0% {
    -webkit-transform: scale3d(0.3, 0.3, 0.3);
    opacity: 0;
    transform: scale3d(0.3, 0.3, 0.3);
  }
  50% {
    opacity: 1;
  }
}
@keyframes zoomIn {
  0% {
    -webkit-transform: scale3d(0.3, 0.3, 0.3);
    opacity: 0;
    transform: scale3d(0.3, 0.3, 0.3);
  }
  50% {
    opacity: 1;
  }
}
.zoomIn {
  -webkit-animation-name: zoomIn;
  animation-name: zoomIn;
}
.animated {
  -webkit-animation-duration: 1s;
  -webkit-animation-fill-mode: both;
  animation-duration: 1s;
  animation-fill-mode: both;
}
.animated.faster {
  -webkit-animation-duration: 0.5s;
  animation-duration: 0.5s;
}
@media (prefers-reduced-motion) {
  .animated {
    -webkit-animation: unset !important;
    -webkit-transition: none !important;
    animation: unset !important;
    transition: none !important;
  }
}
</style>
