<template>
  <div :class="inPage ? 'page active' : 'page'">
    <div id="top"></div>
    <HeadTop />
    <div class="content">
      <!-- 视频 -->
      <div class="videoBox" v-if="videoSrc">
        <div id="player-container" />

        <!-- 下载按钮 -->
        <!-- <a :href="videoSrc" download class="videoBox-download">
          <img src="../../assets/icon/icon-download.png" alt="" />
        </a> -->
        <!-- <a class="videoBox-download" :href="videoSrc" download
          ><img src="../../assets/icon/icon-download.png" alt=""
        /></a> -->
        <div class="videoBox-download" @click="downloadVideo">
          <img src="../../assets/icon/icon-download.png" alt="" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { Toast, Dialog } from 'vant'
import { mapState, mapActions } from 'vuex'
import HeadTop from './../../components/common/head.vue'
// 工具
import { scrollToID, getDeviceType } from '../../utils'
import { saveAs } from 'file-saver'

// 接口
import { getModelDetailById } from '../../api/getPaper'
import { doGetVideoDetialById } from '../../api/downloadVideo'
Vue.use(Toast)

export default {
  components: {
    HeadTop
  },
  data() {
    return {
      inPage: false,
      // videoSrc:
      //   'https://wenlian.wenzhou.gov.cn:8001//upload/video/%E3%80%8A%E7%93%AF%E8%B6%8A%E4%B9%8B%E5%8D%8E%E3%80%8B%E7%89%87%E8%8A%B11.mp4',
      videoSrc: null, //播放地址路径
      title: null, // 视频名称
      coverUrl: null //封面图
    }
  },
  computed: {
    ...mapState({
      characters: (state) => state.publicObj.characters
    })
  },
  created() {},
  async mounted() {
    this.inPage = true
    scrollToID('top')
    //初始化数据
    await this.getVideoInfo()
    this.open()
  },
  destroyed() {},
  methods: {
    // 创建阿里云播放器
    open() {
      // 检测设备类型
      const deviceType = getDeviceType()
      let isAndroid = false
      if (!deviceType) {
        // 设备类型为pc
        isAndroid = false
      } else {
        if (deviceType[0] == 'Android') {
          // 设备类型为安卓
          isAndroid = true
        } else {
          // 其他设备
          isAndroid = false
        }
      }

      new Aliplayer(
        {
          id: 'player-container',
          cover: this.coverUrl,
          source: this.videoSrc,
          // 安卓设备尺寸比其他设备小一半，需适配
          // width: isAndroid ? '260px' : '480px',
          // height: isAndroid ? '427px' : '854px',
          width: '100%',
          height: '100%',
          // 以下可选设置
          playsinline: true, // 禁止内置播放
          isLive: false, // 直播
          rePlay: false, // 循环播放
          useH5Prism: true, // 开启H5播放器
          preload: true, //播放器自动加载
          autoplay: false, // 自动播放
          diagnosisButtonVisible: false, //是否显示检测按钮
          keyShortCuts: true, //是否启用快捷键
          keyFastForwardStep: 3, //快进快退的时间长度
          controlBarVisibility: 'always' // 控制条的显示方式
        },
        function (player) {
          player.play()
        }
      )
    },
    //  下载视频
    async downloadVideo() {
      // 视频地址
      let that = this
      const videoUrl = this.videoSrc
      const title = this.sanitizeFilename(this.title)
      // ios
      const deviceType = getDeviceType()
      let isAndroid = false
      if (!deviceType) {
        // 设备类型为pc
        isAndroid = false
      } else {
        if (deviceType[0] == 'Android') {
          // 设备类型为安卓
          isAndroid = true
        } else {
          // 其他设备
          isAndroid = false
        }
      }
      if (!isAndroid) {
        console.log('ios')
        // await this.downloadFun(
        //   this.videoSrc + '?response-content-type=application/octet-stream',
        //   this.title + '.mp4'
        // )
        // await this.downloadFile1(this.videoSrc)
        window.open(this.videoSrc, '_self')
      } else {
        // 下载视频
        saveAs(videoUrl, this.title + '.mp4')
      }
    },
    // 视频名转化
    sanitizeFilename(filename) {
      return filename.replace(/[/\\:?*"<>|]/g, '').trim()
    },
    // ios下载处理
    downloadFile1(url) {
      return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest()
        xhr.open('GET', url, true)
        xhr.responseType = 'arraybuffer'
        xhr.onload = () => {
          if (xhr.status === 200) {
            const contentType = xhr.getResponseHeader('Content-Type')
            const blob = new Blob([xhr.response], { type: contentType })
            const reader = new FileReader()
            reader.readAsDataURL(blob)
            reader.onloadend = function () {
              const base64Data = reader.result
              const link = document.createElement('a')
              link.href = base64Data
              link.download = fileName
              document.body.appendChild(link)
              link.click()
              document.body.removeChild(link)
            }
            resolve(blob)
          } else {
            reject(
              new Error(`Failed to download file, status code: ${xhr.status}`)
            )
          }
        }

        xhr.onerror = () => {
          reject(new Error(`Failed to download file, network error`))
        }

        xhr.send()
      })
    },
    async downloadFun(blobFile, fileName) {
      let blob = new Blob([blobFile], {
        type: 'application/pdf;charset=UTF-8'
      })
      console.log(blob)
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, fileName)
      } else {
        const reader = new FileReader()
        reader.readAsDataURL(blob)
        reader.onloadend = function () {
          const base64Data = reader.result
          const link = document.createElement('a')
          link.href = base64Data
          link.download = fileName
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        }
        // const dataUrl = 'data:application/octet-stream;base64,' + blobFile
        // const a = document.createElement('a')
        // a.style.display = 'none'
        // a.href = dataUrl
        // a.download = fileName
        // document.body.appendChild(a)
        // a.click()
        // window.URL.revokeObjectURL(dataUrl)
        // document.body.removeChild(a)
        // let link = document.createElement('a')
        // // link.href = blobFile
        // link.href = window.URL.createObjectURL(blob)
        // link.download = fileName
        // link.click()
        // window.URL.revokeObjectURL(link.href) //释放内存
      }
    },
    // 获取视频信息
    async getVideoInfo() {
      const { data: res } = await getModelDetailById(this.$route.query.id)
      if (res.videoId) {
        const { data: res2 } = await doGetVideoDetialById(res.videoId)
        this.videoSrc = res2.videoUrl
        this.title = res2.title
        this.coverUrl = res2.coverURL
        return
      }
      this.videoSrc = res.videoPathUri + res.videoPath
      this.title = res.title
      this.coverUrl = res.coverURL
    },

    // 处理时间
    formatTime(time) {
      const minutes = Math.floor(time / 60)
      const seconds = Math.round(time % 60)
      return `${minutes}:${seconds.toString().padStart(2, '0')}`
    },
    ...mapActions(['setCharacters']),

    go(url) {
      this.$router.push(url)
    }
  }
}
</script>

<style lang="scss" scoped>
#player-container {
  width: 100%;
  height: calc(100vh - 40px);
  overflow: hidden;
}

.page {
  // width: 375px;
  // height: 100vh;
  overflow: hidden;
}
.content {
  width: 100%;
  height: calc(100vh - 40px);
  overflow: hidden;
}
.videoBox {
  position: relative;
  width: 100%;
  height: calc(100vh - 40px);
  background-color: #f8f9f9;

  &-download {
    position: absolute;
    right: 15px;
    top: 15px;
    display: inline-block;
    width: 24px;
    height: 24px;
    z-index: 99;
    img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
