<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="素材名称" prop="resourceName">
        <el-input
          v-model="queryParams.resourceName"
          placeholder="请输入素材名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </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="['course:videoResource:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['course:videoResource:edit']"
        >修改</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="['course:videoResource:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="resourceList" @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="resourceName" />
      <el-table-column label="文件名称" align="center" prop="fileName" />
      <el-table-column label="缩略图" align="center">
        <template slot-scope="scope">
          <el-popover
              placement="right"
              title=""
              trigger="hover"
          >
            <img alt="" slot="reference" :src="scope.row.thumbnail" style="width: 80px; height: 50px" />
            <img alt="" :src="scope.row.thumbnail" style="max-width: 150px;" />
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="文件大小" align="center">
        <template slot-scope="scope">
          <span>{{ (scope.row.fileSize / (1024 * 1024)).toFixed(2) }} MB</span>
        </template>
      </el-table-column>
      <el-table-column label="视频时长" align="center">
        <template slot-scope="scope">
          <span>{{ formatDuration(scope.row.duration) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" 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="['course:videoResource:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['course:videoResource: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-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="素材名称" prop="resourceName">
          <el-input v-model="form.resourceName" placeholder="请输入素材名称" />
        </el-form-item>

        <!-- 使用VideoUpload组件 -->
        <video-upload
          ref="videoUpload"
          :type = "1"
          :isPrivate = "1"
          :video-url.sync="form.videoUrl"
          :file-key.sync="form.fileKey"
          :file-size.sync="form.fileSize"
          :file-name.sync="form.fileName"
          :line_1.sync="form.line1"
          :line_2.sync="form.line2"
          :line_3.sync="form.line3"
          :thumbnail.sync="form.thumbnail"
          :upload-type.sync="form.uploadType"
          :show-control="false"
          @video-duration="handleVideoDuration"
        ></video-upload>
      </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 { listVideoResource, getVideoResource, addVideoResource, updateVideoResource, deleteVideoResource } from '@/api/course/videoResource'
import VideoUpload from '@/components/VideoUpload'

export default {
  name: 'VideoResource',
  components: {
    VideoUpload
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 视频素材库表格数据
      resourceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        resourceName: null
      },
      // 表单参数
      form: {
        id: null,
        resourceName: null,
        fileName: null,
        thumbnail: null,
        line1: null,
        line2: null,
        line3: null,
        duration: null,
        uploadType: null,
        fileSize: null,
        fileKey: null,
        videoUrl: null
      },
      // 表单校验
      rules: {
        resourceName: [
          { required: true, message: "素材名称不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询视频素材库列表 */
    getList() {
      this.loading = true;
      listVideoResource(this.queryParams).then(response => {
        this.resourceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        resourceName: null,
        fileName: null,
        thumbnail: null,
        line1: null,
        line2: null,
        line3: null,
        duration: null,
        uploadType: null,
        fileSize: null,
        fileKey: null,
        videoUrl: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      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 = "添加视频素材库";
      // 打开对话框后，使用nextTick确保组件已渲染
      this.$nextTick(() => {
        if (this.$refs.videoUpload) {
          this.$refs.videoUpload.resetUpload();
        }
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getVideoResource(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改视频素材库";
        // 打开对话框后，使用nextTick确保组件已渲染
        this.$nextTick(() => {
          if (this.$refs.videoUpload) {
            this.$refs.videoUpload.resetUpload();
          }
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateVideoResource(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addVideoResource(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除视频素材库编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return deleteVideoResource(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 处理视频时长 */
    handleVideoDuration(duration) {
      this.form.duration = duration;
    },
    /** 格式化视频时长 */
    formatDuration(seconds) {
      if (!seconds) return '00:00';

      const minutes = Math.floor(seconds / 60);
      const remainingSeconds = seconds % 60;

      return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
    }
  }
}
</script>

<style>
/* 自定义表格样式 */
.el-table .video-cell {
  padding: 5px;
}

/* 设置删除和修改按钮的间距 */
.el-button + .el-button {
  margin-left: 5px;
}
</style>
