<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="filter-container">
      <span>视频标题:</span>
      <el-input
        v-model="listQuery.videoTitle"
        placeholder="视频标题"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="getList"
      />
      <span>审核状态:</span>
      <el-select
        v-model="listQuery.auditStatus"
        placeholder="审核状态"
        clearable
        style="width: 200px"
        class="filter-item"
        @change="getList"
      >
        <el-option label="全部" value="" />
        <el-option label="待审核" :value="2" />
        <el-option label="审核通过" :value="0" />
        <el-option label="审核未通过" :value="1" />
      </el-select>
      <span>上线状态:</span>
      <el-select
        v-model="listQuery.status"
        placeholder="上线状态"
        clearable
        style="width: 200px"
        class="filter-item"
        @change="getList"
      >
        <el-option label="全部" value="" />
        <el-option label="已上线" :value="1" />
        <el-option label="待上线" :value="2" />
        <el-option label="未上线" :value="0" />
      </el-select>
      <el-button type="primary" icon="el-icon-search" @click="getList">查询</el-button>
      <el-button v-if="userIdentity === 2 || proxyInfo!==null" icon="el-icon-edit" type="primary" @click="handleShowDialog('add')">添加视频</el-button>
    </div>
    <!-- 搜索区域END -->
    <!-- 表格区域 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      style="width: 100%"
      border
      fit
      highlight-current-row
      cell-class-name="table-cell"
    >
      <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="180px" 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="180px" 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>
              <el-button v-if="userIdentity===2 || proxyInfo!==null" type="primary" size="mini" @click="handleChangeStatus(row)">上线</el-button>
            </template>
            <template v-else>
              <span style="margin-right:10px;" class="status success ">已上线</span>
              <el-button v-if="userIdentity===2 || proxyInfo!==null" type="info" size="mini" plain @click="handleChangeStatus(row)">下线</el-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="240px" align="center">
        <template slot-scope="{row}">
          {{ row.createTime | formatTime }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="240px" align="center">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" style="margin-right:5px" icon="el-icon-edit" @click="handleShowDialog('edit',row)">编辑</el-button>
          <el-button type="danger" size="mini" style="margin-right:5px" icon="el-icon-s-check" @click="handleRemoveVideo(row)">删除</el-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"
      @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="videoUrl">
          <div class="clearfix video-upload-box" :class="{hasBottom:hasVideo}">
            <el-input v-model="dialogData.videoUrl" style="width:80%" class="fl" :disabled="hasVideo" />
            <el-upload
              ref="uploadRef"
              class="upload-demo fr"
              accept=".mp4"
              :limit="1"
              :auto-upload="false"
              :show-file-list="true"
              :headers="headers"
              :action="action"
              :file-list="fileList"
              :on-success="handleUploadSuccess"
              :on-change="handleUploadChange"
              :on-remove="handleFileRemove"
            >
              <el-button :disabled="hasVideo" type="primary" style="width:100%">选择视频</el-button>
            </el-upload>
          </div>
          <span style="color:#999;font-size:12px">如果没有链接，可以点击右侧的上传视频，视频大小不能超过<i style="color:red">*50MB*</i></span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">提 交</el-button>
      </div>
    </el-dialog>
    <!-- 视频预览对话框END -->
  </div>
</template>

<script>
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { formatDate } from '@/utils'
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import { changeVideoStatus, getVideoList, removeVideo, saveVideo } from '@/api/doc'
export default {
  components: { Pagination },
  filters: {
    formatTime(time) {
      if (!time) {
        return ''
      }
      return formatDate(time, 'yyyy-MM-DD HH:mm:ss')
    }
  },
  data() {
    return {
      listLoading: false, // 列表加载
      submitLoading: false, // 按钮加载
      dialogVisible: false, // 是否显示dialog
      dialogTitle: '添加视频', // dialog标题
      total: 0, // 数据条数
      hasVideo: false, // 是否上传了视频
      chooseNewVideo: false, // 是否重新选择了视频
      fileList: [], // 上传的视频列表
      uploadVideoUrl: '', // 上传视频成功的url
      listQuery: {
        authUserId: '', // 供应商用户id
        listType: 1, // 列表类型：1视频列表，2视频审核列表
        videoTitle: '', // 供应商类型
        auditStatus: '', // 审核状态：0审核未通过，1审核通过，2待审核
        status: '', // 视频状态：0已下线，1已上线，2待上线
        pageNum: 1, // 页码
        pageSize: 10 // 分页大小
      },
      // dialog中表单的数据
      dialogData: {
        videoId: '',
        authUserId: '',
        videoTitle: '',
        videoUrl: ''
      },
      // dialog中表单字段校验规则
      dialogFormRules: {
        videoTitle: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        videoUrl: [{ required: true, message: '链接不能为空', trigger: ['change', 'blur'] }]
      },
      list: []
    }
  },
  computed: {
    ...mapGetters(['authUserId', 'userIdentity', 'proxyInfo']),
    headers() {
      return {
        'X-Token': getToken()
      }
    },
    action() {
      return `${process.env.VUE_APP_UPLOAD_API}/upload/file`
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取列表数据
    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
        })
    },
    // 初始化预览图片列表
    initPreviewList(list) {
      list.forEach(item => this.srcList.push(item.articleCover))
    },
    // 提交
    handleSubmit() {
      // 对标题字段进行规则校验
      this.$refs.formRef.validateField('videoTitle', (error) => {
        if (!error) {
          /**
           * 新增视频和修改视频
           * 表单有两种提交方式
           * 1、直接提交保存，不上传视频
           * 2、上传视频成功后再保存
           * 要针对这两种上传方式做响应的判断
           * 组合：1.新增时，填写视频地址，不上传视频  --直接提交
           *      2.新增时，填写视频地址，再选择上传视频  --上传的视频优先级高
           *      3.新增时，不填写视频地址，选择上传视频  --上传视频后再提交
           *      4.修改时，只修改视频标题，已经有了视频地址  --直接提交
           *      5.修改时，重新选择了视频  --上传视频后再提交
           */
          this.submitLoading = true;
          (this.dialogData.videoUrl && (!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.uploadVideoUrl) {
          this.dialogData.videoUrl = this.uploadVideoUrl
        }
        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.videoUrl) {
        this.fileList.push({ name: `删除当前视频后可上传新视频`, url: row.videoUrl })
        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
      this.$refs?.formRef?.clearValidate()
    },
    // 对话框关闭的回调
    dialogColosed() {
      this.fileList = []
      this.hasVideo = false
      this.dialogData.videoId = ''
      this.dialogData.authUserId = ''
      this.dialogData.videoTitle = ''
      this.dialogData.videoUrl = ''
      this.chooseNewVideo = false
      this.uploadVideoUrl = ''
    },
    // 视频上传成功
    handleUploadSuccess(response, file, fileList) {
      console.log(response)
      // this.dialogData.videoUrl = response.fileUrl
      this.uploadVideoUrl = response.fileUrl
      this.save()
    },
    // 选添加文件、上传成功和上传失败时都会被调用
    handleUploadChange(file, fileList) {
      console.log(file)
      this.chooseNewVideo = true
      this.hasVideo = fileList.length > 0
      this.dialogData.videoUrl = '-'
    },
    // 移除视频
    handleFileRemove(file, fileList) {
      this.hasVideo = fileList.length > 0
      this.dialogData.videoUrl = ''
    },
    // 状态改变
    handleChangeStatus(item) {
      this.listLoading = true
      // const params = {
      //   authId: item.authId,
      //   status: item.status ? 1 : 0
      // }
      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>
.filter-container {
  span {
    display: inline-block;
    margin-bottom: 10px;
    vertical-align: middle;
    font-size: 14px;
  }
  .el-button {
    display: inline-block;
    margin-bottom: 10px;
    vertical-align: middle;
  }
  .el-input,
  .el-select {
    margin-right: 10px;
    margin-left: 10px;
  }
}
.el-table .cell {
  overflow: visible;
}
.el-badge{
  margin: 0 6px;
}
.hasBottom{
  padding-bottom: 40px;
}
</style>
