<template>
  <el-row v-if="video !== null" class="movie-list">
    <el-col :md="15">
      <el-row style="padding-right: 5px; padding-left: 5px; padding-bottom: 5px">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <el-row>
              <h3 v-html="video.title" />
            </el-row>
            <el-row style="color: #999;font-size: 16px;padding-top: 0px;">
              <span><i class="el-icon-video-play">{{ video.view }}</i></span>
              <span v-html="'&nbsp;&nbsp;&nbsp;&nbsp;'" />
              <span><i class="el-icon-s-comment">{{ video.comment }}</i></span>
              <span v-html="'&nbsp;&nbsp;&nbsp;&nbsp;'" />
              <span><i class="el-icon-watch">{{ video.pubDate }}</i></span>
            </el-row>
          </div>
          <div class="text item">
            <video-player :video-prop="video" />
          </div>
        </el-card>
      </el-row>
      <el-row style="padding-right: 5px; padding-left: 5px; padding-bottom: 5px">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <div class="video-data-row">
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-collection"
                :disabled="isCollected"
                @click="collection(video.videoId)"
              >
                <span>收藏 {{ video.favorite }}</span>
              </el-button>
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-thumb"
                :disabled="isCollected"
                @click="collection(video.videoId)"
              >
                <span>喜欢 {{ video.thumbUp }}</span>
              </el-button>
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-share"
                :disabled="isCollected"
                @click="collection(video.videoId)"
              >
                <span>分享 {{ video.share }}</span>
              </el-button>
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-download"
                @click="getDownloadUrl(video.videoId)"
              >
                <span>下载</span>
              </el-button>
              <el-button
                v-if="video.cache != null"
                type="danger"
                size="mini"
                icon="el-icon-download"
                @click="cacheBiliVideo(video.videoId)"
              >
                <span>{{ video.cache.msg }}</span>
              </el-button>
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-help"
                @click="displayErrorReportDialog"
              >
                <span>报错</span>
              </el-button>
            </div>
          </div>
          <div class="text item">
            <!--视频描述行-->
            <span class="description" v-html="video.description" />
            <el-divider />
            <!--视频标签行-->
            <div class="v-tag">
              <el-tag
                v-for="(tag,index) in video.tags"
                :key="index"
                class="tag"
                size="medium"
                effect="plain"
              >
                <router-link target="_blank" :to="`/video/tag/` + tag">
                  {{ tag }}
                </router-link>
              </el-tag>
            </div>
          </div>
        </el-card>
      </el-row>
      <el-row style="padding-right: 5px; padding-left: 5px; padding-bottom: 5px">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <el-row>
              <h3>视频评论</h3>
            </el-row>
          </div>
          <div class="text item">
            <comment :video-id="video.videoId" />
          </div>
        </el-card>
      </el-row>
    </el-col>
    <el-col :md="9">
      <el-row>
        <el-row style="padding-right: 5px; padding-left: 5px; padding-bottom: 5px">
          <user-avatar-card v-if="user !== null" :user-avatar="user" />
        </el-row>
        <el-row v-if="showPlaylist" style="padding-right: 5px; padding-left: 5px; padding-bottom: 5px">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <el-row>
                <h3>播放列表</h3>
              </el-row>
              <el-row>
                <span>自动播放 <el-switch v-model="autoPlay" /></span>
              </el-row>
            </div>
            <div class="text item">
              <el-table
                :data="similarVideos"
                style="width: 100%"
              >
                <el-table-column
                  prop="title"
                >
                  <template slot-scope="scope">
                    <router-link target="_blank" :to="`/video/${scope.row.videoId}`">
                      <span>{{ scope.row.videoId }}</span>
                    </router-link>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="coverUrl"
                >
                  <template slot-scope="scope">
                    <span>10:00</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>
        </el-row>
        <el-row style="padding-right: 5px; padding-left: 5px; padding-bottom: 5px">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <el-row>
                <h3>推荐视频</h3>
              </el-row>
              <el-row>
                <span>自动播放 <el-switch v-model="autoPlay" /></span>
              </el-row>
            </div>
            <div class="text item">
              <el-row v-for="(item,index) in similarVideos" :key="index" class="item">
                <video-card :video="item" />
              </el-row>
            </div>
          </el-card>
        </el-row>
      </el-row>
    </el-col>

    <!-- 视频报错对话框 -->
    <el-dialog
      append-to-body
      :visible.sync="showErrorReportDialog"
      width="30%"
      center
    >
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>视频报错</span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="submitErrorReport">提交错误</el-button>
        </div>
        <div class="text item">
          <el-form ref="form" :model="errorReportForm" label-width="80px">
            <el-form-item label="错误类型">
              <el-select v-model="errorReportForm.errorCode" placeholder="选择视频错误类型">
                <el-option label="视频无封面" value="1" />
                <el-option label="视频无声音" value="2" />
                <el-option label="视频无画面" value="3" />
                <el-option label="视频无资源" value="4" />
                <el-option label="视频待删除" value="5" />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </el-dialog>
  </el-row>
</template>

<script>
import VideoPlayer from 'components/VideoPlayer'
import Comment from 'components/comment/Comment'
import VideoCard from 'components/card/VideoCard'
import UserAvatarCard from '@/components/card/UserAvatarCard'

import { similarVideo, videoInfo, videoErrorReport, downloadVideo, cacheBiliVideo } from '@/api/video'
import { collectItem } from '@/api/collect'
import { getUserInfo } from '@/api/user'

export default {
  name: 'VideoPage',
  components: { Comment, VideoCard, VideoPlayer, UserAvatarCard },
  data() {
    return {
      video: null,
      videoProp: {
        info: null,
        autoPlay: false,
        playlist: []
      },
      user: null,
      similarVideos: [],
      isCollected: false,
      showErrorReportDialog: false,
      errorReportForm: {
        videoId: null,
        errorCode: null
      },
      showPlaylist: false,
      autoPlay: false
    }
  },
  watch: {
    // 地址栏 url 发生变化时重新加载本页面
    $route() {
      this.$router.go()
    }
  },
  created() {
    const videoId = this.$route.params.id
    this.getVideoInfo(videoId)
    this.getSimilarVideos(videoId)
  },
  methods: {
    // 获取视频的详细信息
    getVideoInfo(videoId) {
      videoInfo(videoId).then(res => {
        if (res.code === 0) {
          this.videoProp = res.data

          this.video = res.data
          document.title = res.data.title
          this.userId = res.data.userId
          getUserInfo(this.userId).then(res => {
            if (res.code === 0) {
              this.user = res.data
            } else {
              this.$notify.error({
                message: '用户数据获取失败',
                type: 'warning',
                duration: 3000
              })
            }
          })
        } else {
          this.$notify.error({
            message: '视频数据获取失败',
            type: 'warning',
            duration: 3000
          })
          this.$router.push('/404')
        }
      }).catch(error => {
        this.$notify.error({
          message: error.message,
          type: 'warning',
          duration: 3000
        })
      })
    },
    // 获取和当前视频类似的其他视频
    getSimilarVideos(videoId) {
      similarVideo(videoId).then(res => {
        if (res.code === 0) {
          this.similarVideos = res.data
        } else {
          this.$notify.error({
            message: '推荐视频数据获取失败',
            type: 'warning',
            duration: 3000
          })
        }
      }).catch(error => {
        this.$notify.error({
          message: error.message,
          type: 'warning',
          duration: 3000
        })
      })
    },
    // 换一换
    refreshSimilar() {
      console.log('刷新相关推荐')
    },
    // 用户点击收藏
    collection(videoId) {
      const jsonData = {}
      jsonData.contentType = 1002
      jsonData.contentId = videoId
      jsonData.collected = true
      collectItem(jsonData).then(res => {
        if (res.code !== 0) {
          this.$notify.success({
            title: '视频收藏失败',
            type: 'warning',
            duration: 3000
          })
        }
      })
    },
    getDownloadUrl(videoId) {
      // let filename
      downloadVideo(videoId).then(res => {
        if (res.code === 0) {
          const downloadUrl = res.data.url
          window.open(downloadUrl, '_blank')
          /* fetch(downloadUrl.url, {
            headers: {
              Authorization: 'Bearer ' + downloadUrl.token
            },
            method: 'GET',
            credentials: 'include'
          }).then(res => {
            /!*
            遍历 formdata
            for (const key of res.headers.keys()) {
              console.log(key + ' : ' + res.headers.get(key))
            }*!/
            const header = res.headers.get('Content-Disposition')
            const parts = header.split(';')
            const encodeFilename = parts[1].split('=')[1]
            filename = decodeURI(encodeFilename)
            return res.blob()
          }).then(data => {
            const blobUrl = window.URL.createObjectURL(data)
            const a = document.createElement('a')
            a.download = filename
            a.href = blobUrl
            a.click()
          }).catch(e => {
            this.$notify({
              title: '提示',
              message: '视频下载失败',
              type: 'warning',
              duration: 3000
            })
          })*/
        } else {
          this.$notify({
            title: '提示',
            message: res.msg,
            type: 'warning',
            duration: 3000
          })
        }
      }).catch(error => {
        this.$notify({
          title: '提示',
          message: error.message,
          type: 'error',
          duration: 3000
        })
      })
    },
    cacheBiliVideo(bvId) {
      cacheBiliVideo(bvId).then(res => {
        if (res.code === 0) {
          const resData = res.data
          this.$notify({
            title: '提示',
            message: resData.msg,
            type: 'warning',
            duration: 3000
          })
        }
      })
    },
    displayErrorReportDialog() {
      this.errorReportForm.videoId = this.video.videoId
      this.showErrorReportDialog = true
    },
    submitErrorReport() {
      this.showErrorReportDialog = false
      videoErrorReport(this.errorReportForm).then(res => {
        if (res.code === 0) {
          this.$notify({
            title: '提示',
            message: '视频错误已提交',
            type: 'warning',
            duration: 3000
          })
        }
      }).catch(error => {
        this.$notify({
          title: '提示',
          message: error.message,
          type: 'warning',
          duration: 3000
        })
      })
    }
  }
}
</script>

<style scoped>
/*处于手机屏幕时*/
@media screen and (max-width: 768px) {
  .movie-list {
    padding-top: 8px;
    padding-left: 0.5%;
    padding-right: 0.5%;
  }
}

.movie-list {
  padding-top: 15px;
  padding-left: 5%;
  padding-right: 5%;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.v-tag {
  padding-top: 10px;
}
.tag{
  margin-right: 3px;
}
</style>
