<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" :xs="24">
        <!--搜索模块-->
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="视频标题" prop="title">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入视频标题"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="上架状态" prop="title">
            <el-select v-model="queryParams.shelfStatus" placeholder="请选择状态">
              <el-option label="全部" :value="null"> </el-option>
              <el-option label="已上架" :value="0"> </el-option>
              <el-option label="未上架" :value="1"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="删除状态" prop="title">
            <el-select v-model="queryParams.status" placeholder="请选择状态">
              <el-option label="全部" :value="null"> </el-option>
              <el-option label="未删除" :value="0"> </el-option>
              <el-option label="已删除" :value="1"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <!--全局按钮模块-->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:user:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:role:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" size="mini" :disabled="multiple" @click="putShelf" v-hasPermi="['system:role:remove']">批量上架</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" size="mini" :disabled="multiple" @click="offShelf" v-hasPermi="['system:role:remove']">批量下架</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!--列表数据模块-->
        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="ID" align="center" prop="id" />
          <el-table-column label="视频标题" align="center" prop="title" />
          <el-table-column label="视频描述" align="center" prop="videoDescribe" />
          <!-- <el-table-column label="视频预览" align="center" width="300px">
            <template slot-scope="scope">
              <video :src="scope.row.fileUrl" class="videoPreview" :poster="scope.row.coverFileUrl" controls preload="meta"></video>
            </template>
          </el-table-column> -->
          <el-table-column label="视频封面" align="center" width="200px">
            <template slot-scope="scope">
              <div>
                <el-card :body-style="{ padding: '0 0 5px' }">
                  <img :src="scope.row.coverFileUrl" class="imgPreview" />
                  <el-button type="primary" size="mini" @click="videoPreview(scope.row.fileUrl)" :disabled="!scope.row.fileUrl">预览视频</el-button>
                </el-card>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="视频时长" align="center" prop="videoDuration">
            <template slot-scope="scope">
              <span>{{ new Date(scope.row.videoDuration * 1000).toISOString().slice(11, 19) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="视频顺序" align="center" prop="sort" />
          <el-table-column label="上架状态" align="center">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.shelfStatus" :active-value="0" :inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:user:edit']"
                >修改</el-button
              >
              <el-button
                v-if="scope.row.userId !== 1"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:user:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="视频标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入视频标题" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="视频描述">
              <el-input v-model="form.videoDescribe" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="视频顺序">
              <el-input v-model="form.sort" type="number" placeholder="请输入数值"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="视频文件">
              <input type="file" accept="video/*" ref="videoFile" @change="fileUpload" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上传进度">
              <el-progress
                :text-inside="true"
                :stroke-width="24"
                :percentage="videoPercentage"
                :status="form.vodVideoFileId ? 'success' : ''"
              ></el-progress>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.vodVideoFileId">
          <el-col :span="12">
            <el-form-item label="视频封面">
              <input type="file" accept="image/*" ref="coverFile" @change="coverUpload" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上传进度">
              <el-progress
                :text-inside="true"
                :stroke-width="24"
                :percentage="imagePercentage"
                :status="form.coverFileId ? 'success' : ''"
              ></el-progress>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="!form.coverFileId && !form.coverFileUrl">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import shortVideoApi from '@/api/stortVideo/index'
import { vodSignature } from '@/api/upload'
import TcVod from 'vod-js-sdk-v6'
import VideoPreview from '@/components/VideoPreview/index'

export default {
  name: 'stortVideo',
  data() {
    return {
      videoPercentage: 0,
      imagePercentage: 0,
      mediaFile: null,
      coverFile: null,
      tcVod: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: '',
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'typeName',
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单校验
      rules: {
        userName: [{ required: true, message: '用户名称不能为空', trigger: 'blur' }],
      },
    }
  },
  async created() {
    this.tcVod = new TcVod({
      getSignature: vodSignature,
    })
    this.getList()
    this.getDicts('sys_normal_disable').then((response) => {
      this.statusOptions = response.data
    })
  },
  methods: {
    videoPreview(videoSrc) {
      VideoPreview(videoSrc)
    },
    /** 查询短视频列表 */
    async getList() {
      this.loading = true
      const params = this.addDateRange(this.queryParams, this.dateRange)
      const res = await shortVideoApi.getList(params)
      this.userList = res.rows
      this.total = res.total
      this.loading = false
    },
    //上传视频
    async fileUpload(e) {
      this.mediaFile = e.target.files[0]
      if (!this.mediaFile.type.includes('video')) {
        this.msgError('请选择视频文件')
        return false
      }
      this.videoPercentage = 0
      const uploader = this.tcVod.upload({
        mediaFile: this.mediaFile, // 媒体文件（视频或音频或图片），类型为 File
      })
      uploader.on('media_progress', (info) => {
        this.videoPercentage = Math.floor(info.percent * 100 * 100) / 100
      })
      uploader.done().then((doneResult) => {
        this.$set(this.form, 'vodVideoFileId', doneResult.fileId)
      })
    },
    //上传封面
    async coverUpload(e) {
      this.coverFile = e.target.files[0]
      if (!this.coverFile.type.includes('image')) {
        this.msgError('请选择图片文件')
        return false
      }
      this.imagePercentage = 0
      let formData = new FormData()
      formData.append('coverFile', this.coverFile)
      formData.append('fileId', this.form.vodVideoFileId)
      const { data } = await shortVideoApi.uploadCover(formData, (e) => {
        this.imagePercentage = Math.floor((e.loaded / e.total) * 100 * 100) / 100
      })
      this.$set(this.form, 'coverFileId', data.fileId)
    },
    /** 视频状态修改 */
    async handleStatusChange(row) {
      const text = row.shelfStatus === 0 ? '上架' : '下架'
      try {
        await this.$confirm(`确认要 ${text} ${row.title}吗?`, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        await shortVideoApi.changeUserStatus(row.id, row.shelfStatus)
      } catch (error) {
        console.log(error)
        row.shelfStatus = row.shelfStatus === 0 ? 1 : 0
      }
    },
    /** 取消按钮,关闭修改窗口 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 表单重置 */
    reset() {
      this.form = {}
      this.videoPercentage = 0
      this.imagePercentage = 0
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加视频'
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset()
      const res = await shortVideoApi.getVideoInfo(row.id)
      this.form = res.data
      this.open = true
      this.title = '修改视频信息'
    },
    /** 提交按钮 */
    async submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            const data = {
              id: this.form.id,
              title: this.form.title,
              sort: this.form.sort,
              videoDescribe: this.form.videoDescribe,
              videoFileId: this.form.vodVideoFileId,
              coverFileId: this.form.coverFileId,
            }
            shortVideoApi.updateVideo(data).then((response) => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            const data = {
              id: this.form.id,
              sort: this.form.sort,
              title: this.form.title,
              videoDescribe: this.form.videoDescribe,
              videoFileId: this.form.vodVideoFileId,
              coverFileId: this.form.coverFileId,
            }
            shortVideoApi.addVideo(data).then((response) => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      try {
        const ids = row.id || this.ids
        await this.$confirm(`是否删除ID为${ids}的短视频`, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        await shortVideoApi.delVideo(ids)
        this.getList()
      } catch (error) {}
    },
    /**批量下架 */
    async offShelf() {
      try {
        const ids = this.ids
        await this.$confirm(`是否下架ID为${ids}的短视频`, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        await shortVideoApi.offShelf(ids)
        this.getList()
      } catch (error) {}
    },
    /**批量上架 */
    async putShelf() {
      try {
        const ids = this.ids
        await this.$confirm(`是否上架ID为${ids}的短视频`, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        await shortVideoApi.putShelf(ids)
        this.getList()
      } catch (error) {}
    },
  },
}
</script>

<style lang="scss" scoped>
.videoPreview {
  object-fit: contain;
  height: 180px;
}
.imgPreview {
  width: 100%;
}
</style>
