<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-button type="primary" 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"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['video:AUXILIARYVIDEO:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['video:AUXILIARYVIDEO:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['video:AUXILIARYVIDEO:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['video:AUXILIARYVIDEO:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="AUXILIARYVIDEOList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="标题" align="center" prop="title">

      </el-table-column>
      <el-table-column label="封面" align="center" prop="cover">

      </el-table-column>
      <el-table-column label="视频地址" align="center" prop="sourcePath">

      </el-table-column>
      <el-table-column label="是否置顶" align="center" prop="topFlat">

      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort">

      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime">

      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy">

      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateTime">

      </el-table-column>
      <el-table-column label="来源" align="center" prop="sourceFrom">

      </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="['video:AUXILIARYVIDEO:edit']"
          >修改
          </el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['video:AUXILIARYVIDEO: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="视频预览" :append-to-body="true" :visible.sync="dialogVisible" width="50%">
      <video :src="videoUrl" controls width="100%" height="auto"></video>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="open" title="Dialog Title">
      <el-row :gutter="15">
        <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
          <el-col :span="17">
            <el-form-item label="视频文件" prop="sourcePath" required>
              <el-upload ref="sourcePath"
                         :file-list="sourcePathfileList"
                         :multiple="false"
                         :limit="1"
                         :action="sourcePathAction"
                         list-type="picture"
                         accept="video/*">
                <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>

          <el-col :span="20">
            <el-form-item label="标题" prop="title">
              <el-input v-model="formData.title" placeholder="请输入标题" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="来源" prop="sourceFrom">
              <el-input v-model="formData.sourceFrom" placeholder="请输入来源" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="17">
            <el-form-item label="置顶" prop="topFlat">
              <el-radio-group v-model="formData.topFlat" size="medium">
                <el-radio v-for="(item, index) in topFlatOptions" :key="index" :label="item.value"
                          :disabled="item.disabled">{{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getAUXILIARYVIDEO, listAUXILIARYVIDEO} from "@/api/auxiliary/auxiliary";

export default {
  name: "AUXILIARYVIDEO",
  data() {
    return {
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      formData: {
        sourcePath: null,
        cover: null,
        title: undefined,
        sourceFrom: undefined,
        topFlat: 1,
      },
      rules: {
        title: [{
          required: true,
          message: '请输入标题',
          trigger: 'blur'
        }],
        sourceFrom: [],
      },
      sourcePathAction: process.env.VUE_APP_BASE_API + '/portal_api/common/uploadVideo',
      sourcePathfileList: [],
      coverAction: 'https://jsonplaceholder.typicode.com/posts/',
      coverfileList: [],
      topFlatOptions: [{
        "label": "是",
        "value": 1
      }, {
        "label": "否",
        "value": 0
      }],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 通关视频表格数据
      AUXILIARYVIDEOList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        title: null,
        cover: null,
        sourcePath: null,
        topFlat: null,
        sort: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        sourceFrom: null
      },
      fileList: [],
      dialogVisible: false,
      videoUrl: '',
      // 表单参数
      form: {},

    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleConfirm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        this.close()
      })
    },


    handleBeforeUpload(file) {
      console.log(file.size);
      // 清空之前的上传记录，只保留最新上传的视频
      this.fileList = [file];
      // 执行截图操作
      this.captureThumbnail(file);
      return false; // 禁止自动上传
    },
    handleUploadSuccess(response, file) {
      // 上传成功后处理
      this.$message.success('上传成功');
      // 可以在这里保存视频的相关信息，如视频地址等
    },
    handleUploadError(err, file) {
      // 上传失败处理
      this.$message.error('上传失败，请重试');
    },
    captureThumbnail(file) {
      const video = document.createElement('video');
      video.preload = 'metadata';
      console.log(111);
      console.log(video);
      // 监听视频加载元数据完成事件
      video.onloadedmetadata = () => {
        // 创建 canvas 元素用于绘制截图
        const canvas = document.createElement('canvas');
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        const ctx = canvas.getContext('2d');

        // 在 canvas 上绘制视频第一帧
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

        // 生成截图的 base64 数据 URL
        const thumbnailUrl = canvas.toDataURL('image/jpeg');

        // 打印截图的数据 URL
        console.log(thumbnailUrl);

        // 显示截图
        this.dialogVisible = true;
        this.videoUrl = thumbnailUrl;
      };

      video.src = URL.createObjectURL(file);
    },
    /** 查询通关视频列表 */
    getList() {
      this.loading = true;
      listAUXILIARYVIDEO(this.queryParams).then(response => {
        this.AUXILIARYVIDEOList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        cover: null,
        sourcePath: null,
        topFlat: null,
        sort: null,
        sourceFrom: 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 = "添加通关视频";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAUXILIARYVIDEO(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改通关视频";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAUXILIARYVIDEO(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAUXILIARYVIDEO(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除通关视频编号为"' + ids + '"的数据项？').then(function () {
        return delAUXILIARYVIDEO(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('video/AUXILIARYVIDEO/export', {
        ...this.queryParams
      }, `AUXILIARYVIDEO_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
