<template>
  <div>
    <div style="display: flex">
      <div style="width: 300px">
        <el-card>
          <dic-tree
            v-model="listQuery.params.catId"
            dic-code="course_file_catalog"
          />
        </el-card>
      </div>
      <div style="flex-grow: 1; padding-left: 20px">
        <data-table
          ref="pagingTable"
          :options="options"
          :list-query="listQuery"
          @add="handleAdd"
          @edit="handleEdit"
        >
          <template slot="filter-content">
            <dic-list-select
              v-model="listQuery.params.fileType"
              dic-code="course_file_type"
              title="课件类型"
              class="filter-item"
            />
            <el-input
              v-model="listQuery.params.title"
              placeholder="搜索课件名称"
              style="width: 200px"
              class="filter-item"
            />
          </template>

          <template slot="data-columns">
            <el-table-column
              label="课件名称"
              prop="title"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <detail-link
                  :id="scope.row.id"
                  :title="scope.row.title"
                  permission="course:file:update"
                  @click="handleEdit"
                />
              </template>
            </el-table-column>

            <el-table-column
              label="课件类型"
              prop="fileType_dictText"
              align="center"
              width="150px"
            />

            <el-table-column
              label="课程类目"
              prop="catId_dictText"
              align="center"
            />

            <el-table-column
              label="文件大小"
              prop="fileSize"
              align="center"
              width="120px"
            />

            <el-table-column
              label="课件时长"
              align="center"
              width="120px"
              show-overflow-tooltip
            >
              <template v-slot="scope">
                <span v-if="scope.row.duration === 0">无</span>
                <span v-else>
                  <sec-format :value="scope.row.duration" />
                </span>
              </template>
            </el-table-column>

            <el-table-column
              label="创建人"
              align="center"
              prop="createBy_dictText"
              width="120px"
            />

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

            <el-table-column label="操作" align="center" width="150px">
              <template slot-scope="scope">
                <el-link
                  type="primary"
                  icon="el-icon-view"
                  style="margin-left: 10px"
                  @click="handlePreview(scope.row)"
                  >在线预览</el-link
                >
              </template>
            </el-table-column>
          </template>
        </data-table>
      </div>
    </div>

    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      title="课件管理"
      width="50%"
    >
      <el-form
        ref="postForm"
        :model="postForm"
        :rules="rules"
        label-position="left"
        label-width="120px"
      >
        <el-form-item label="课件类型" prop="fileType">
          <dic-list-select
            v-model="postForm.fileType"
            :disabled="isEdit"
            dic-code="course_file_type"
          />
        </el-form-item>

        <el-form-item label="课件名称" prop="title">
          <el-input v-model="postForm.title" />
        </el-form-item>

        <el-form-item label="课件分类">
          <dic-catalog-tree
            v-model="postForm.catId"
            dic-code="course_file_catalog"
          />
        </el-form-item>

        <el-form-item v-if="postForm.fileType" label="上传文件" prop="fileUrl">
          <file-upload
            v-model="postForm.fileUrl"
            :limit="1"
            :tips="tips"
            :accept="accept"
            list-type="file"
          />
        </el-form-item>

        <el-form-item
          v-if="postForm.fileType === '33' && postForm.fileUrl"
          label="视频时长"
        >
          <el-input-number v-model="postForm.duration" /> 单位：秒
          <div style="color: #ff4949">
            <small
              >MP4视频可以直接读取视频时长，其他格式视频将在提交后异步读取.</small
            >
          </div>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-alert type="success" style="margin-bottom: 20px">
          课件保存后，您可以从列表来预览它！
        </el-alert>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="handleSave"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="previewVisible"
      title="文件预览"
      width="60%"
      @close="closePreview"
    >
      <div style="max-height: 650px; overflow-x: hidden; overflow-y: auto">
        <div v-if="previewData.fileType === '33'">
          <video-player
            v-model="previewData.viewUrl"
            :ref-id="previewData.id"
          />
        </div>
        <pdf-reader
          v-if="previewData.fileType === '11'"
          :src="previewData.viewUrl"
        />
        <pdf-reader
          v-if="previewData.fileType === '22'"
          :src="previewData.fileUrl"
        />
      </div>
    </el-dialog>

    <div
      v-if="postForm.fileType === '33' && postForm.fileUrl"
      style="display: none"
    >
      <video-player v-model="postForm.fileUrl" @loaded="videoLoaded" />
    </div>
  </div>
</template>

<script>
import DataTable from "@/components/DataTable";
import DicListSelect from "@/components/DicListSelect";
import { saveData, fetchDetail } from "@/api/course/file";
import FileUpload from "@/components/FileUpload";
import DicCatalogTree from "@/components/DicTreeSelect";
import { fetchTree } from "@/api/sys/dict/value";
import DicTree from "@/components/DicTree/index";
import DetailLink from "@/components/DetailLink";
import VideoPlayer from "@/components/VideoPlayer";
import PdfReader from "@/components/PdfReader";
import SecFormat from "@/components/SecFormat";

export default {
  name: "CourseFileList",
  components: {
    SecFormat,
    PdfReader,
    VideoPlayer,
    DetailLink,
    DicTree,
    DicCatalogTree,
    FileUpload,
    DicListSelect,
    DataTable,
  },
  data() {
    return {
      dialogVisible: false,
      fileList: [],
      isEdit: false,

      tips: "",
      accept: "",
      data: {},

      loading: false,
      postForm: {
        fileType: "",
        fileUrl: "",
        needLearn: 0,
      },

      rules: {
        title: [{ required: true, message: "课件名称不能为空！" }],

        fileType: [{ required: true, message: "课件类型不能为空！" }],

        fileUrl: [{ required: true, message: "课件文件必须上传！" }],
      },

      listQuery: {
        current: 1,
        size: 10,
        params: {
          courseId: this.courseId,
          catId: null,
        },
      },

      options: {
        // 可批量操作
        multi: true,

        add: {
          enable: true,
          permission: "course:file:add",
        },
        edit: {
          enable: true,
          permission: "course:file:update",
        },
        delete: {
          enable: true,
          permission: "course:file:delete",
          url: "/api/course/file/delete",
        },

        // 列表请求URL
        listUrl: "/api/course/file/paging",
      },

      previewVisible: false,
      previewData: {},

      treeData: [],
      defaultProps: {
        children: "children",
        label: "title",
      },
    };
  },
  watch: {
    "postForm.fileType": {
      handler(val) {
        if (val === "11") {
          this.tips = "包含doc,docx,xls,xlsx,ppt,pptx等Office类型文件";
          this.accept = ".doc, .docx, .xls, .xlsx, .ppt, .pptx";
          this.data = {};
          this.previewData.fileType = "11";
        }
        if (val === "22") {
          this.tips = "PDF文件可以直接在线预览";
          this.accept = ".pdf";
          this.data = {};
          this.previewData.fileType = "22";
        }
        if (val === "33") {
          this.tips =
            "视频文件,尽可能使用mp4格式兼容性较好，也支持flv,mkv,rm,rmvb等格式";
          this.accept = ".mp4, .mov, .flv, .mkv, .rm, .rmvb, .webm, .ogv, .avi";
          this.data = {};
          this.previewData.fileType = "33";
        }
      },
    },
  },

  created() {
    const id = this.$route.params.courseId;
    if (id !== undefined) {
      this.listQuery.params.courseId = id;
    }

    fetchTree({ dicCode: "course_file_catalog" }).then((res) => {
      this.treeData = res.data;
    });
  },

  methods: {
    handleAdd() {
      this.postForm = { courseId: this.listQuery.params.courseId };
      this.dialogVisible = true;
      this.isEdit = false;
    },

    handleEdit(id) {
      // 先清理表单
      this.postForm = {};
      this.isEdit = true;
      this.dialogVisible = true;
      fetchDetail(id).then((res) => {
        this.postForm = res.data;
      });
    },

    handleSave() {
      this.$refs.postForm.validate((valid) => {
        if (!valid) {
          return;
        }

        this.loading = true;

        saveData(this.postForm)
          .then(() => {
            this.$message({
              type: "success",
              message: "课件保存成功!",
            });
            this.dialogVisible = false;
            this.$refs.pagingTable.getList();

            this.loading = false;
          })
          .catch((err) => {
            console.log(err);
            this.loading = false;
          });
      });
    },

    catalogSelected(node) {
      console.log("node", node);
      this.listQuery.params.catId = node.id;
    },

    handlePreview(data) {
      this.previewVisible = true;
      this.previewData.fileType = data.fileType;
      this.previewData.viewUrl = data.viewUrl;
      this.previewData.fileUrl = data.fileUrl;
    },

    closePreview() {
      this.previewData = {};
    },

    // 读取视频长度
    videoLoaded(d) {
      console.log("++++++视频长度" + d);
      this.postForm["duration"] = parseInt(d);
    },
  },
};
</script>
