<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--视频类型-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--视频数据-->
      <el-col :span="20" :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>
            <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 v-if="pid != 0" type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:user:add']"
              >新增</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 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">
            <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="teachingVideoTypeName" :show-overflow-tooltip="true" />
          <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">
            <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>
      <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="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 v-if="form.userId == undefined" 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>
          <el-col :span="12">
            <el-form-item label="视频封面">
              <input type="file" accept="image/*" ref="coverFile" @change="coverUpload" :disabled="form.vodVideoFileId == null" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.userId == undefined" 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">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getUser, delVideo, addUser, updateUser, changeUserStatus, uploadCover } from '@/api/teachingVideo/index'
import { treeselect } from '@/api/videoType'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { vodSignature } from '@/api/upload'
import TcVod from 'vod-js-sdk-v6'
import VideoPreview from '@/components/VideoPreview/index'

export default {
  name: 'User',
  components: { Treeselect },
  data() {
    return {
      pid: 0,
      teachingVideoTypeId: 0,
      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' }]
      }
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  async created() {
    this.tcVod = new TcVod({
      getSignature: vodSignature
    })
    this.getList()
    this.getTreeselect()
    this.getDicts('sys_normal_disable').then(response => {
      this.statusOptions = response.data
    })
  },
  methods: {
    videoPreview(videoSrc) {
      VideoPreview(videoSrc)
    },
    //上传视频
    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)
      let { data } = await uploadCover(formData, e => {
        this.imagePercentage = Math.floor((e.loaded / e.total) * 100 * 100) / 100
      })
      this.$set(this.form, 'coverFileId', data.fileId)
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.userList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.typeName.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.teachingVideoTypeId = data.id
      this.teachingVideoTypeId = data.id
      this.pid = data.pid
      this.getList()
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.shelfStatus === 0 ? '上架' : '下架'
      this.$confirm('确认要"' + text + '""' + row.title + '"视频吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return changeUserStatus(row.id, row.shelfStatus)
        })
        .then(() => {
          this.msgSuccess(text + '成功')
        })
        .catch(() => {
          row.shelfStatus = row.shelfStatus === '0' ? '1' : '0'
        })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {}
      // this.$refs.videoFile.resetFields()
      // this.$refs.coverFile.resetFields()
      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.userId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.getTreeselect()
      this.open = true
      this.title = '添加视频'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getTreeselect()
      const userId = row.id || this.ids
      getUser(userId).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改视频信息'
      })
    },
    /**校验form */
    validate: function(form) {
      console.log(form)
      if (!form.title) {
        this.msgError('标题必填')
        return false
      }
      if (!form.vodVideoFileId) {
        this.msgError('视频未上传成功')
        return false
      }
      if (!form.coverFileId) {
        this.msgError('封面未上传成功')
        return false
      }
      return true
    },
    /** 提交按钮 */
    submitForm: function() {
      if (this.validate(this.form)) {
        if (this.form.id != undefined) {
          let data = {
            teachingVideoTypeId: this.form.teachingVideoTypeId,
            id: this.form.id,
            title: this.form.title,
            videoDescribe: this.form.videoDescribe,
            videoFileId: this.form.vodVideoFileId,
            coverFileId: this.form.coverFileId
          }
          updateUser(data).then(response => {
            this.msgSuccess('修改成功')
            this.open = false
            this.getList()
          })
        } else {
          let data = {
            teachingVideoTypeId: this.teachingVideoTypeId,
            id: this.form.id,
            title: this.form.title,
            videoDescribe: this.form.videoDescribe,
            videoFileId: this.form.vodVideoFileId,
            coverFileId: this.form.coverFileId
          }
          addUser(data).then(response => {
            this.msgSuccess('新增成功')
            this.open = false
            this.getList()
          })
        }
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      console.log(row)
      const userIds = row.id
      this.$confirm('是否确认删除id为"' + userIds + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          console.log('确定')
          return delVideo(userIds)
        })
        .then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
    }
  }
}
</script>

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