<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="filter-container">
      <div class="filter-control">
        <span>视频标题:</span>
        <el-input v-model="listQuery.videoTitle" placeholder="视频标题" @keyup.enter.native="getList" />
      </div>
      <div class="filter-control">
        <span>审核状态:</span>
        <el-select v-model="listQuery.auditStatus" placeholder="审核状态" clearable @change="getList">
          <el-option label="全部" value="" />
          <el-option label="待审核" :value="2" />
          <el-option label="审核通过" :value="1" />
          <el-option label="审核未通过" :value="0" />
        </el-select>
      </div>
      <div class="filter-control">
        <span>上线状态:</span>
        <el-select v-model="listQuery.status" placeholder="上线状态" clearable @change="getList">
          <el-option label="全部" value="" />
          <el-option label="已上线" :value="1" />
          <el-option label="待上线" :value="2" />
          <el-option label="未上线" :value="0" />
        </el-select>
      </div>
      <div class="filter-control">
        <permission-button type="primary" @click="getList">查询</permission-button>
        <permission-button type="primary" @click="handleShowDialog('add')">添加视频</permission-button>
      </div>
    </div>
    <!-- 搜索区域END -->
    <!-- 表格区域 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      style="width: 100%"
      border
      fit
      highlight-current-row
      cell-class-name="table-cell"
      header-row-class-name="tableHeader"
    >
      <el-table-column label="序号" :index="indexMethod" type="index" width="80" align="center" />
      <el-table-column label="视频标题" prop="videoTitle" align="center" />
      <el-table-column label="审核状态" width="120px" align="center">
        <template slot-scope="{ row }">
          <el-tag v-if="row.auditStatus === 2" size="small" type="warning">待审核</el-tag>
          <el-tag v-if="row.auditStatus === 1" size="small" type="success">审核通过</el-tag>
          <!-- 未通过原因展示 -->
          <template v-if="row.auditStatus === 0">
            <!-- <span class="status danger">审核未通过&nbsp;</span> -->
            <el-popover placement="top-start" title="审核说明" width="400" trigger="hover" :content="row.invalidReason">
              <el-tag slot="reference" size="small" type="danger" class="reason">
                <span>审核未通过</span>
                <span class="el-icon-question status danger " />
              </el-tag>
            </el-popover>
            <!-- 未通过原因展示END -->
          </template>
        </template>
      </el-table-column>
      <el-table-column label="上线状态" width="160px" align="center">
        <template slot-scope="{ row }">
          <!-- 只有审核通过了才能操作上下线 auditStatus ：审核状态 -->
          <template v-if="row.auditStatus === 1">
            <template v-if="row.status === 0">
              <span style="margin-right:10px;" class="status danger">已下线</span>
              <permission-button type="primary" size="mini" @click="handleChangeStatus(row)">上线</permission-button>
            </template>
            <template v-else>
              <span style="margin-right:10px;" class="status success ">已上线</span>
              <permission-button type="info" size="mini" plain @click="handleChangeStatus(row)">下线</permission-button>
            </template>
          </template>
          <template v-else>
            <!-- <el-tag type="warning">待上线</el-tag> -->
            <span style="margin-right:10px;" class="status warning">待上线</span>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="160px" align="center">
        <template slot-scope="{ row }">
          {{ row.createTime | formatTime }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280px" align="center">
        <template slot-scope="{ row }">
          <permission-button
            type="primary"
            size="mini"
            style="margin-right:5px"
            @click="handlePlayer(row)"
          >播放</permission-button>
          <permission-button
            type="primary"
            size="mini"
            style="margin-right:5px"
            @click="handleShowDialog('edit', row)"
          >编辑</permission-button>
          <permission-button
            type="danger"
            size="mini"
            style="margin-right:5px"
            @click="handleRemoveVideo(row)"
          >删除</permission-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 表格区域END -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getList(listQuery)"
    />
    <!-- 视频预览对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="40%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="beforeDialogClose"
      @closed="dialogColosed"
    >
      <el-form ref="formRef" :model="dialogData" label-width="110px" :rules="dialogFormRules">
        <el-form-item label="标题：" prop="videoTitle">
          <el-input v-model="dialogData.videoTitle" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item ref="formVideoUrlRef" label="上传视频：" prop="videoPreviewUrl">
          <div class="file-upload-box" style="height:40px;">
            <!-- 上传文件组件 -->
            <el-upload
              ref="uploadRef"
              accept=".mp4"
              :class="{ hidden: hasVideo }"
              :auto-upload="false"
              :headers="headers"
              :action="action"
              :on-success="handleUploadSuccess"
              :on-change="handleUploadChange"
              :on-remove="handleFileRemove"
              :before-upload="beforeUpload"
              :file-list="fileList"
            >
              <permission-button size="mini" type="primary" style="width:100%">上传视频</permission-button>
            </el-upload>
            <el-input v-model="dialogData.videoPreviewUrl" type="hidden" class="hiddenInput" />
          </div>
          <span style="color:#999;font-size:12px">视频大小不能超过<i style="color:red">*500MB*</i></span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <permission-button @click="dialogVisible = false">取 消</permission-button>
        <permission-button type="primary" :loading="submitLoading" @click="handleSubmit">提 交</permission-button>
      </div>
    </el-dialog>
    <!-- 视频预览对话框END -->

    <!-- 视频预览对话框 -->
    <el-dialog title="视频预览" :visible.sync="dialogPreviewVisible" width="60%" @closed="dialogPreviewColosed">
      <video :src="videoPreviewUrl" controls="controls" width="100%">
        您的浏览器不支持播放该视频
      </video>
      <div slot="footer" class="dialog-footer">
        <permission-button type="primary" @click="dialogPreviewVisible = false">关闭</permission-button>
      </div>
    </el-dialog>
    <!-- 视频预览对话框END -->
  </div>
</template>

<script>
import PermissionButton from '@/views/components/PermissionButton'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import { changeVideoStatus, getVideoList, removeVideo, saveVideo } from '@/api/doc'
export default {
  components: { Pagination, PermissionButton },
  data() {
    return {
      dialogPreviewVisible: false,
      listLoading: false, // 列表加载
      submitLoading: false, // 按钮加载
      dialogVisible: false, // 是否显示dialog
      dialogTitle: '添加视频', // dialog标题
      total: 0, // 数据条数
      hasVideo: false, // 是否上传了视频
      chooseNewVideo: false, // 是否重新选择了视频
      fileList: [], // 上传的视频列表
      previewUrl: '', // 上传视频成功的url
      downloadUrl: '',
      listQuery: {
        authUserId: '', // 供应商用户id
        listType: 1, // 列表类型：1视频列表，2视频审核列表
        videoTitle: '', // 供应商类型
        auditStatus: '', // 审核状态：0审核未通过，1审核通过，2待审核
        status: '', // 视频状态：0已下线，1已上线，2待上线
        pageNum: 1, // 页码
        pageSize: 10 // 分页大小
      },
      // dialog中表单的数据
      dialogData: {
        videoId: '',
        authUserId: '',
        videoName: '',
        videoTitle: '',
        // videoUrl: '',
        videoPreviewUrl: '',
        videoDownloadUrl: ''
      },
      // dialog中表单字段校验规则
      dialogFormRules: {
        videoTitle: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        videoPreviewUrl: [{ required: true, message: '链接不能为空', trigger: ['change', 'blur'] }]
      },
      list: [],
      videoPreviewUrl: ''
    }
  },
  computed: {
    ...mapGetters(['authUserId', 'userIdentity']),
    headers() {
      return {
        'X-Token': getToken()
      }
    },
    action() {
      return `${process.env.VUE_APP_UPLOAD_API}/upload/file`
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 播放视频
    handlePlayer(row) {
      this.currentVideoUrl = row.videoPreviewUrl
      this.dialogPreviewVisible = true
    },

    dialogPreviewColosed() {
      this.currentVideoUrl = ''
    },

    // 获取列表数据
    getList() {
      this.listLoading = true
      this.listQuery.authUserId = this.authUserId
      getVideoList(this.listQuery)
        .then(res => {
          if (res.code !== 0) return
          this.list = res.data.list
          this.total = res.data.total
          console.log(res)
        })
        .finally(() => {
          this.listLoading = false
        })
    },
    // 提交
    handleSubmit() {
      if (!this.dialogData.videoPreviewUrl) {
        this.$refs.formRef.validateField('videoTitle')
        this.$refs.formRef.validateField('videoPreviewUrl')
        return
      }
      // 对标题字段进行规则校验
      this.$refs.formRef.validateField('videoTitle', error => {
        if (!error) {
          /**
           * 新增视频和修改视频
           * 表单有两种提交方式
           * 1、直接提交保存，不上传视频
           * 2、上传视频成功后再保存
           * 要针对这两种上传方式做响应的判断
           * 组合：1.新增时，填写视频地址，不上传视频  --直接提交
           *      2.新增时，填写视频地址，再选择上传视频  --上传的视频优先级高
           *      3.新增时，不填写视频地址，选择上传视频  --上传视频后再提交
           *      4.修改时，只修改视频标题，已经有了视频地址  --直接提交
           *      5.修改时，重新选择了视频  --上传视频后再提交
           */
          this.submitLoading = true
          this.dialogData.videoPreviewUrl && (!this.hasVideo || (this.hasVideo && !this.chooseNewVideo))
            ? this.save()
            : this.$refs.uploadRef.submit()
        }
      })
    },
    // 保存视频
    save() {
      this.$refs.formRef.validate(valide => {
        if (!valide) return
        this.dialogData.authUserId = this.authUserId
        // uploadVideoUrl不为空，就代表重新上传了视频，需要为表单中的videoUrl重新赋值，新增时该值也不为空
        if (this.previewUrl && this.downloadUrl) {
          this.dialogData.videoPreviewUrl = this.previewUrl
          this.dialogData.videoDownloadUrl = this.downloadUrl
        }
        saveVideo(this.dialogData)
          .then(res => {
            console.log(res)
            if (res.code !== 0) return
            this.dialogVisible = false
            this.getList()
            this.$message({
              type: 'success',
              message: res.data,
              duration: 500
            })
          })
          .finally(() => {
            this.submitLoading = false
          })
      })
    },
    // 设置表单初始值
    setDialogData(row) {
      if (!row) return
      console.log(row)
      for (const key in this.dialogData) {
        if (Object.hasOwnProperty.call(this.dialogData, key)) {
          this.dialogData[key] = row[key]
        }
      }
      if (this.dialogData.videoPreviewUrl) {
        this.fileList.push({ name: row.videoName, url: row.videoPreviewUrl })
        this.hasVideo = true
      }
    },
    // 删除视频
    async handleRemoveVideo(row) {
      const text = await this.$confirm('视频删除后不可恢复，确认删除该视频吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        this.$message.info('已取消操作')
      })
      if (text !== 'confirm') return
      removeVideo({ videoId: row.videoId }).then(res => {
        if (res.code !== 0) return
        this.$message.success(res.data)
        this.getList()
      })
    },
    // 显示对话框
    handleShowDialog(type, row) {
      this.dialogTitle = type === 'add' ? '添加视频' : '修改视频'
      this.setDialogData(row)
      this.dialogVisible = true
    },
    // 对话框关闭的回调
    dialogColosed() {
      this.fileList = []
      this.hasVideo = false
      this.dialogData.videoId = ''
      this.dialogData.authUserId = ''
      this.dialogData.videoTitle = ''
      this.dialogData.videoPreviewUrl = ''
      this.dialogData.videoDownloadUrl = ''
      this.chooseNewVideo = false
      this.downloadUrl = ''
      this.previewUrl = ''
      this.submitLoading = false
    },
    // 对话框关闭前的回调
    beforeDialogClose() {
      this.$refs.formRef.resetFields()
      // 停止上传文件
      this.$refs.uploadRef.abort()
    },
    // 视频上传成功
    handleUploadSuccess(response, file, fileList) {
      console.log(response)
      // this.dialogData.videoUrl = response.fileUrl
      this.previewUrl = response.previewUrl
      this.downloadUrl = response.downloadUrl
      this.dialogData.videoName = response.fileName
      this.save()
    },
    // 选添加文件、上传成功和上传失败时都会被调用
    handleUploadChange(file, fileList) {
      console.log(file)
      this.chooseNewVideo = true
      this.hasVideo = fileList.length > 0
      this.dialogData.videoPreviewUrl = '-'
      this.dialogData.videoDownloadUrl = '-'
    },
    // 移除视频
    handleFileRemove(file, fileList) {
      this.hasVideo = fileList.length > 0
      this.dialogData.videoPreviewUrl = ''
      this.dialogData.videoDownloadUrl = ''
      this.submitLoading = false
    },
    // 上传视频前判断文件大小
    beforeUpload(file, fileList) {
      const flag = file.size <= 500 * 1024 * 1204
      if (!flag) {
        this.$message({
          message: '文件大小超过100MB，请重新选择！',
          duration: 1000,
          type: 'warning'
        })
        this.fileList = []
      }
      return flag
    },
    // 状态改变
    handleChangeStatus(item) {
      this.listLoading = true
      console.log(item)
      const params = {
        videoId: item.videoId,
        status: item.status === 1 ? 0 : 1
      }
      changeVideoStatus(params)
        .then(res => {
          // this.$message.success(res.data)
          this.$message({
            message: res.data,
            duration: 500,
            type: 'success'
          })
          this.getList()
        })
        .catch(err => {
          console.log(err)
        })
        .finally(() => {
          this.listLoading = false
        })
    },
    indexMethod(index) {
      return index + this.listQuery.pageSize * (this.listQuery.pageNum - 1) + 1
    }
  }
}
</script>

<style lang="scss" scoped>
.el-table .cell {
  overflow: visible;
}
.el-badge {
  margin: 0 6px;
}
.hasBottom {
  padding-bottom: 40px;
}
</style>
