<!--课件资源-->
<template>
  <div class="app-container el-resources">
    <div v-if="pageType == 1" class="list-max-big-box">
      <div class="top-max-box">
        <div class="left-max-box scrollbar-box" v-hasPermi="['exam:el_category:list']">
          <div class="classify_btn" @click="clickPage(5,'')">管理分类 >></div>
          <el-tree
            :data="treeData"
            :props="defaultProps"
            :highlight-current="true"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            node-key="id"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
        <div class="center-max-box" v-hasPermi="['exam:el_category:list']"></div>
        <div class="right-max-box">
          <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
            <el-form-item label="课件名称" prop="title">
              <el-input
                v-model="queryParams.title"
                maxLength="20"
                placeholder="请输入课件名称"
                clearable
                size="small"
              />
            </el-form-item>
            <el-form-item label="课件类型" prop="type">
              <el-select v-model="queryParams.type" clearable placeholder="请选择课件类型">
                <el-option
                  v-for="item in coursewareType"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="float: right;">
              <el-col :span="1.5">
                <p class="add-button-one-120"
                   @click="handleAdd"
                   v-hasPermi="['exam:el_resources:add']"
                ><i class="el-icon-plus"></i>新增文件课件</p>
              </el-col>
              <el-col :span="1.5">
                <p class="add-button-one-120"
                   style="width:140px;margin-left:10px;"
                   @click="richTextAddClick(1)"
                   v-hasPermi="['exam:el_resources:add']"
                ><i class="el-icon-plus"></i>新增富文本课件</p>
              </el-col>
            </el-form-item>
            <el-form-item>
              <p class="inquire-button-one" @click="handleQuery">查询</p>
              <p class="reset-button-one" @click="resetQuery">重置</p>
            </el-form-item>
          </el-form>
          <div class="min-list-box">
            <el-table v-loading="loading" border :data="el_resourcesList" @selection-change="handleSelectionChange">
              <el-table-column label="课件名称" align="left" prop="title" />
              <el-table-column label="分类" align="left" prop="cateTitle" width="160"/>
              <el-table-column label="类型" align="left" prop="type" width="110">
                <template slot-scope="scope">
                  {{scope.row.type==1?'文档':(scope.row.type==2?'视频':(scope.row.type==3?'图片':(scope.row.type==4?'音频':(scope.row.type==5?'富文本':"其他"))))}}
                </template>
              </el-table-column>
              <el-table-column label="格式" align="left" prop="postfix" width="110"/>
              <el-table-column label="大小" align="left" prop="sizeStr" width="110"/>
              <el-table-column label="上传时间" align="left" prop="createTime" width="220"/>
              <el-table-column label="操作" align="left" class-name="small-padding fixed-width" width="160" v-if="tableButtonType">
                <template slot-scope="scope">
                  <div class="table-button-box">
                    <p class="table-button-null"></p>
                    <p class="table-button-p"
                       @click="handleUpdate(scope.row)"
                       v-hasPermiAnd="['exam:el_resources:query','exam:el_resources:edit']"
                    >修改</p>
                    <p class="table-button-p"
                       @click="handleDelete(scope.row)"
                       v-hasPermi="['exam:el_resources:remove']"
                    >删除</p>
                    <p class="table-button-null"></p>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <div class="bottom-max-box">
        <pagination :page-sizes="[20, 30, 40, 50]"
          v-show="total>0"
          :total="total"
          layout="total, prev, pager, next, sizes, jumper"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
      <!-- 添加资源对话框 -->
      <el-dialog class="el_resources_dialog" @close="handleClose" :title="title" :visible.sync="open" width="700px" append-to-body :before-close="offUpPage" :close-on-click-modal="false">
        <el-form ref="form" :model="form" v-loading="loading" :rules="rules" label-width="80px">
          <el-form-item label="分类" prop="title">
            <el-input
             style="width: 100%;"
              v-model="typeTitle"
              maxLength="25"
              placeholder=""
              disabled
              clearable
              size="small"
            />
          </el-form-item>
          <el-form-item label="课件名称" prop="name">
            <el-input
              disabled
              style="width: 100%;"
              v-model="coursewareName"
              maxLength="25"
              placeholder="课件名称"
              clearable
              size="small"
            />
          </el-form-item>
          <uploader
            :autoStart="false"
            :options="options"
            ref="uploader"
            :file-list="fileList"
            :file-status-text="statusText"
            class="uploader-example"
            @file-complete="fileComplete"
            @complete="complete"
            @file-success="fileSuccess"
            @files-added="filesAdded">
            <uploader-unsupport></uploader-unsupport>
            <uploader-drop>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或 <uploader-btn  :attrs="attrs">点击上传</uploader-btn></div>

            </uploader-drop>
            <!-- <uploader-list></uploader-list> -->
            <uploader-files> </uploader-files>
          </uploader>
          <div class="up-text-box" style="margin-top:20px;max-height:400px;overflow-y: scroll">
            <div v-for="(item,index) in upTextList" :key="index" style="margin-left:30px;">
              <div style="display: flex">
                <p style="flex:1;font-size:14px;margin:0;">{{item.title}}.{{item.postfix}}</p>
                <p style="flex:1;font-size:14px;margin:0;text-align: right;margin-right:50px;">{{item.sizeStr}}</p>
              </div>
              <div>
                <el-progress :percentage="100" status="success"></el-progress>
              </div>
            </div>
          </div>
          <div class="up-data-box-text">
            <p>支持上传视频、图片、文件类型的课件</p>
            <p>图片请上传 png / jpeg / gif 格式</p>
            <p>视频请上传 mp4</p>
            <p>文件请上传 pdf / doc / docx / ppt / pptx 格式</p>
          </div>
        </el-form>
      </el-dialog>
      <!--修改资源对话框-->
      <el-dialog class="el_resources_dialog" @close="handleClose" :title="title" :visible.sync="openEdit" width="700px" append-to-body :before-close="offUpPage" :close-on-click-modal="false">
        <el-form ref="editForm" :model="editForm" v-loading="loading" :rules="rules" label-width="80px">
          <el-form-item label="分类" prop="title">
            <el-input
              style="width: 100%;"
              v-model="editForm.cateTitle"
              maxLength="25"
              placeholder=""
              disabled
              clearable
              size="small"
            />
          </el-form-item>
          <el-form-item label="课件名称" prop="title">
            <el-input
              disabled
              v-model="editForm.title"
              maxLength="20"
              placeholder="请输入课件名称"
              clearable
            />
          </el-form-item>
<!--          <el-form-item label="分类" prop="title">
            <div class="scrollbar-box" style="height:140px;">
              <el-tree
                :data="editTree"
                show-checkbox
                default-expand-all
                node-key="id"
                :check-strictly="true"
                ref="ditTree"
                highlight-current
                @node-click="editCheck"
                @check="editCheck"
                :props="defaultProps">
              </el-tree>
            </div>
          </el-form-item>-->
          <div class="up-button-box">

            <uploader
              :autoStart="false"
              :options="options"
              ref="uploader"
              :file-list="fileList"
              :file-status-text="statusText"
              class="uploader-example"
              @file-complete="fileComplete"
              @complete="complete"
              @file-success="fileSuccess"
              @files-added="filesAdded">
              <uploader-unsupport></uploader-unsupport>
              <uploader-drop>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或 <uploader-btn  :attrs="attrs">点击上传</uploader-btn></div>

              </uploader-drop>
              <!-- <uploader-list></uploader-list> -->
              <uploader-files> </uploader-files>
            </uploader>
            <div class="up-text-box" style="margin-top:20px;max-height:400px;overflow-y: scroll">
              <div v-for="(item,index) in upTextList" :key="index" style="margin-left:30px;">
                <div style="display: flex">
                  <p style="flex:1;font-size:14px;margin:0;">{{item.title}}.{{item.postfix}}</p>
                  <p style="flex:1;font-size:14px;margin:0;text-align: right;margin-right:50px;">{{item.sizeStr}}</p>
                </div>
                <div>
                  <el-progress :percentage="100" status="success"></el-progress>
                </div>
              </div>
            </div>
            <div class="up-data-box-text">
              <p>支持上传视频、图片、文件类型的课件</p>
              <p>图片请上传 png / jpeg / gif 格式</p>
              <p>视频请上传 mp4 / WebM格式 </p>
              <p>文件请上传 pdf / doc / docx / ppt / pptx 格式</p>
            </div>
<!--            <div slot="footer" class="dialog-footer-edit">
              <p class="null-p"></p>
              <el-button @click="cancel">取 消</el-button>
              <el-button type="primary" @click="updateResource">确 定</el-button>
            </div>-->
          </div>
        </el-form>
      </el-dialog>
      <!--富文本新增课件-->
      <el-dialog class="el_resources_dialog" @close="handleClose" :title="title" :visible.sync="richTextAddType"  :close-on-click-modal="false"
                 v-if="richTextAddType" width="1100px" append-to-body :before-close="offUpPage">
        <el-form ref="richTextForm" :model="richTextForm" v-loading="loading" :rules="richTextRules" label-width="100px" style="flex-direction: column;display: flex;">
          <el-form-item label="分类">
            <el-input
              style="width: 100%;"
              v-model="typeTitle"
              maxLength="25"
              placeholder=""
              disabled
              clearable
              size="small"
            />
          </el-form-item>
          <el-form-item label="课件名称" prop="title">
            <el-input
              style="width: 100%;"
              v-model="richTextForm.title"
              maxLength="20"
              placeholder="请输入课件名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="课件内容" prop="content" style="width:1000px;height:500px;overflow-y: scroll" class="scrollbar-box">
            <editor v-model="richTextForm.content" :min-height="192"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="richTextCancel">取 消</el-button>
          <el-button type="primary" @click="richTextClick">确 定</el-button>
        </div>
      </el-dialog>
      <!--富文本修改课件-->
      <el-dialog class="el_resources_dialog" @close="handleClose" :title="title" :visible.sync="richTextEditType"  :close-on-click-modal="false"
                 v-if="richTextEditType" width="1100px" append-to-body :before-close="offUpPage">
        <el-form ref="richTextForm" :model="richTextForm" v-loading="loading" :rules="richTextRules" label-width="80px">
          <el-form-item label="分类" prop="title">
            <el-input
              style="width: 100%;"
              v-model="typeTitle"
              maxLength="25"
              placeholder=""
              disabled
              clearable
              size="small"
            />
          </el-form-item>
          <el-form-item label="课件名称" prop="title">
            <el-input
              v-model="richTextForm.title"
              maxLength="20"
              placeholder="请输入课件名称"
              clearable
            />
          </el-form-item>
<!--          <el-form-item label="分类" prop="title">
            <div class="scrollbar-box" style="height:140px;">
              <el-tree
                :data="editTree"
                show-checkbox
                default-expand-all
                node-key="id"
                :check-strictly="true"
                ref="ditTree"
                highlight-current
                @node-click="editCheckTwo"
                @check="editCheckTwo"
                :props="defaultProps">
              </el-tree>
            </div>
          </el-form-item>-->
          <el-form-item label="课件内容" prop="content" style="width:1000px;height:500px;overflow-y: scroll" class="scrollbar-box">
            <editor v-model="richTextForm.content" :min-height="192"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="richTextCancel">取 消</el-button>
          <el-button type="primary" @click="richTextClick">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!--管理分类-->
    <add-classify v-if="pageType == 5" :pageData="pageData"></add-classify>
  </div>
</template>

<script>
  import { listEl_category} from "@/api/exam/el_category";
  import {
    listEl_resources,
    getEl_resources,
    delEl_resources,
    addEl_resources,
    updateEl_resources,
    addText,
    updateText
  } from "@/api/exam/el_resources";
  import { getToken } from "@/utils/auth";
  import addClassify from "../el_category/index";
  import axios from "axios";
  import SparkMD5 from "spark-md5";
  let httpHeader=window.location.href.split('://')[0]+'://'
export default {
  name: "El_resources",
  components: {
    addClassify
  },
  data() {
    let checkName = (rule, value, callback) => {
    let reg = /^\s+$/;
      if(reg.test(value)){
        return callback(new Error(''));
      }
    }
    return {
      tableButtonType:this.hasPermiDom(['exam:el_resources:query','exam:el_resources:edit','exam:el_resources:remove']),
      aa:'1111111',
      //页面状态
      pageType:1,
      pageData:{
        type:1,//1资源管理2课程管理
      },
      // 上传相关
      uploadImgUrl: "",
      headers: {
        Authorization: "Bearer " + getToken()
      },
      cateId:"",
      //树数据
      treeData:[],
      defaultProps: {
        children: "children",
        label: "title"
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课件资源表格数据
      el_resourcesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //文件路径
      filePath:null,
      //文件名称
      fileName: null,
      //文件大小
      fileSize: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize:20,
        userId: null,
        deptId: null,
        deptName: null,
        cateId: "",
        title: null,
        type: null,
        postfix: null,
        size: null,
        duration: null,
        path: null
      },
      // 表单参数
      form: {},
      typeTitle:'',//点击的分类名称
      coursewareName:'',//课件名称
      // 表单校验
      rules: {
        cateId: [
          { required: true, message: "分类id不能为空", trigger: "blur" }
        ],
      },
      richTextRules: {
        title: [
          { required: true, message: "请输入课件名称", trigger: "blur" },
          { required: true, message: "请输入课件名称", validator: this.spaceJudgment, trigger: "blur" }
        ],
        content: [
          { required: true, message: "请输入课件内容", trigger: "blur" },
          { required: true, message: "请输入课件内容", validator: this.spaceJudgmentHTML, trigger: "blur" }
        ],
      },
      //课件类型
      coursewareType:[
        {dictLabel:"文档", dictValue:"1",},
        {dictLabel:"视频", dictValue:"2",},
        {dictLabel:"图片", dictValue:"3",},
        // {dictLabel:"音频", dictValue:"4",},
		    {dictLabel:"富文本", dictValue:"5",}
      ],
      //上传成功展示列表
      upTextList:[],
      //修改页面
      openEdit:false,
      editForm:{
        id:'',
      },
      //修改上传
      editTree:[],
      fileList:[],
      //富文本数据
      richTextForm:{},
      //富文本课件状态
      richTextAddType:false,
      //富文本课件状态
      richTextEditType:false,
      skip: false,
      options: {
        target: httpHeader+this.judgmentNetworkReturnAddress()+"/base/file/upload/chunk",
        // 开启服务端分片校验功能
        testChunks: true,
        single: true,
        fileParameterName: 'file',
        headers: {
          Authorization: "Bearer " + getToken()
        },
        parseTimeRemaining: function (timeRemaining, parsedTimeRemaining) {
          return parsedTimeRemaining
            .replace(/\syears?/, "年")
            .replace(/\days?/, "天")
            .replace(/\shours?/, "小时")
            .replace(/\sminutes?/, "分钟")
            .replace(/\sseconds?/, "秒");
        },
        // // 服务器分片校验函数
        checkChunkUploadedByResponse: (chunk, message) => {
          const result = JSON.parse(message);
          if (result.data.skipUpload) {
            this.skip = true;
            return true;
          }
          return (result.data.uploaded || []).indexOf(chunk.offset + 1) >= 0;
        },
      },
      attrs: {
        accept: ["image/png","image/jpeg","image/gif","application/pdf","video/mp4","application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document"]
      },
      statusText: {
        success: "上传成功",
        error: "上传出错了",
        uploading: "上传中...",
        paused: "暂停中...",
        waiting: "等待中...",
        cmd5: "计算文件MD5中...",
      },
      disabled: true,
    };
  },
  watch: {
    fileList(o, n) {
      this.disabled = false;
    },
  },
  created() {
    this.getTreeData();
  },
  methods: {
    /*
    unescape(response.data.content)  解码
    escape(this.form.content) 编码
    */

    clickPage(type){
      if(type==1){
        this.pageType=1
        this.getTreeData();
        this.getList();
      }else if(type==5){
        this.pageType=5
      }
    },
    //监听弹窗关闭
    handleClose(){
      console.log('监听弹窗关闭')
      // this.typeTitle='';
      // this.coursewareName='';
      // this.queryParams.cateId='';
      // this.$refs.tree.setCurrentKey(null);
    },
    //富文本课件提交按钮
    richTextClick(){
      this.$refs["richTextForm"].validate(valid => {
        if (valid) {
          console.log('valid',valid);
          if(this.richTextAddType){
            //新增
            let obj = {
              cateId:this.richTextForm.cateId,
              title:this.richTextForm.title,
              content:escape(this.richTextForm.content),
              type:"5",
            }
            this.loading = true;
            addText(obj).then( response => {
              this.msgSuccess("新增成功");
              this.loading = false;
              this.richTextCancel();
              this.getList();
            });
          }else if(this.richTextEditType){
            //修改
            let obj = {
              id:this.richTextForm.id,
              cateId:this.richTextForm.cateId,
              title:this.richTextForm.title,
              content:escape(this.richTextForm.content),
              type:"5",
            };
            updateText(obj).then( response => {
              this.msgSuccess("修改成功");
              this.loading = false;
              this.richTextCancel();
              this.getList();
            });
          }
        }
      });
    },
    //新增富文本按钮
    richTextAddClick(type,row){
      let self = this;
      if(type == 1){
        if(!this.queryParams.cateId){
          this.msgError('请在左侧列表选择分类')
          return
        }
        this.richTextForm = {};
        this.title = "新增课件"
        this.richTextForm.cateId = this.queryParams.cateId;
        this.richTextAddType = true;
      }else if(type == 2){
        this.title = "编辑课件"
        this.richTextForm = row;
        this.richTextForm.cateId = row.cateId;
        this.richTextForm.content = unescape(row.content);
        this.richTextEditType = true;
      }
    },
    //关闭富文本按钮
    richTextCancel(){
      this.richTextAddType = false;
      this.richTextEditType = false;
    },
    //上传
    handleRemove(file, fileList) {
      this.fileList = [];
    },
    fileListAdd(file, fileList){
      this.fileList.push(file);
      this.$forceUpdate()
    },
    //树点击事件
    editCheck(event) {
      this.$refs.ditTree.setCheckedKeys([event.id]);
      this.editForm.cateId = event.id;
    },
    editCheckTwo(event) {
      this.$refs.ditTree.setCheckedKeys([event.id]);
      this.richTextForm.cateId = event.id;
    },
    beforeAvatarUpload(file) {
      let type = false;
      if (
        //图片
        file.type == 'image/png' || file.type == 'image/jpeg' || file.type == 'image/gif' ||
        //pdf
        file.type == 'application/pdf' ||
        //视频
        file.type == 'video/mp4' ||
        //ppt
        file.type == 'application/vnd.ms-powerpoint' || file.type == 'application/vnd.openxmlformats-officedocument.presentationml.presentation' ||
        //word
        file.type == 'application/msword' || file.type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
      ) {
        type = true;
      }else{
        this.$message.error('只能上传png/jpeg/gif格式图片');
        type = false;
      }
      return type;
    },
    //开始上传
    progressUpEdit(event, file, fileList){
      console.log("开始上传");
      this.loading = true;
    },
    //上传成功
    handleAvatarSuccessEdit(res, file,index) {
      if(res.code == 200){
        this.msgSuccess("上传成功");
        this.loading = false;
        this.openEdit = false;
        this.getList();
      }else{
        this.loading = false;
        this.msgError(res.msg);
      }
    },
    //上传失败
    errorUpEdit(err, file, fileList){
      console.log("上传失败");
      this.loading = false;
    },
    editUpClick(){
      let self = this;
      this.uploadImgUrl = window.location.href.split('://')[0]+'://' + this.judgmentNetworkReturnAddress() + "/exam/el_resources/update?cateId=" + this.editForm.cateId +'&id=' + this.editForm.id + '&title=' + this.editForm.title
      if(this.fileList[0]){
        setTimeout(function(){
          self.submitUpload();
        },100);
      }else{
        let obj = {
          id:this.editForm.id,
          cateId:this.editForm.cateId,
          title:this.editForm.title,
        };
        updateEl_resources(obj).then( response => {
          this.msgSuccess("修改成功");
          this.loading = false;
          this.openEdit = false;
          this.getList();
        });
      }
    },
    submitUpload() {
      if(this.loading){
        return
      }
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          this.$refs.editFormUp.submit();
        }
      });
    },
    //关闭新增上传页面
    offUpPage(done){
      if(this.upTextList[0]){
        this.getList();
      }
      done();
    },
    /** 查询分类树 */
    getTreeData() {//type 1资源 2课程
      this.loading = true;
      listEl_category({},1).then( response => {
        let list = [];
        let obj = {
          children:[],
          title:"所有分类",
          id:"",
        };
        list.push(obj);
        for(let i=0;i<response.data.length;i++){
          list.push(response.data[i]);
        }
        this.treeData = list;
        this.editTree = JSON.parse(JSON.stringify(response.data));
        this.getList();
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data,node) {
      let self = this;
      this.queryParams.cateId = data.id;
      let text = '';
      for(let i=0;i<self.treeData.length;i++){
        if (data.id == self.treeData[i].id){
          text = self.treeData[i].title;
          break
        }
        for(let o=0;o<self.treeData[i].children.length;o++){
          if (data.id == self.treeData[i].children[o].id){
            text = self.treeData[i].title +'/'+ self.treeData[i].children[o].title;
            break
          }
          for(let x=0;x<self.treeData[i].children[o].children.length;x++){
            if (data.id == self.treeData[i].children[o].children[x].id){
              text = self.treeData[i].title +'/'+ self.treeData[i].children[o].title + '/' + self.treeData[i].children[o].children[x].title;
              break
            }
          }
        }
      }
      self.typeTitle=text
      console.log('当前节点的父节点:',node.parent.data);
      //根据id查找父元素
      console.log(this.familyTree(this.treeData,data.id))

      this.getList();
    },
    //根据id查找父元素
    familyTree (arr1, id) {
      var temp = []
      var forFn = function (arr, id) {
        for (var i = 0; i < arr.length; i++) {
          var item = arr[i]
          if (item.id === id) {
            temp.push(item)
            forFn(arr1, item.parentId)
            break
          } else {
            if (item.children) {
              forFn(item.children, id)
            }
          }
        }
      }
      forFn(arr1, id)
      return temp
    },

    //开始上传
    progressUp(event, file, fileList){
      console.log("开始上传");
      this.loading = true;
    },
    //上传成功
    handleAvatarSuccess(res, file,index) {
      console.log("上传成功");
      let obj = {
        title:res.data.title,
        postfix:res.data.postfix,
        sizeStr:res.data.sizeStr
      }
      this.upTextList.push(obj);
      this.loading = false;
    },
    //上传失败
    errorUp(err, file, fileList){
      console.log("上传失败");
      this.loading = false;
    },
    /** 查询课件资源列表 */
    getList() {
      this.loading = true;
      listEl_resources(this.queryParams).then( response => {
        this.el_resourcesList =  response.rows;
        this.total =  response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      if(this.loading){
        return
      }
      this.editForm = {};
      this.fileList = [];
      this.upTextList = [];
      this.openEdit = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        createBy: null,
        updateBy: null,
        deptId: null,
        deptName: null,
        createTime: null,
        updateTime: null,
        remark: null,
        cateId: null,
        title: null,
        type: null,
        postfix: null,
        size: null,
        duration: null,
        path: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm("queryForm");
      this.$set(this,'queryParams',{
        pageNum: 1,
        pageSize:20,
        cateId:"",
        title: '',
        type:'',
        id:'',
      });
      this.$refs.tree.setCurrentKey();
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      if(!this.queryParams.cateId){
        this.msgError('请在左侧列表选择分类')
        return
      }
      console.log(this.form.title)
      this.reset();
      this.coursewareName='';
      this.editForm.cateId='';
      this.editForm.id='';
      this.uploadImgUrl = window.location.href.split('://')[0]+'://' + this.judgmentNetworkReturnAddress() + "/exam/el_resources?cateId=" + this.queryParams.cateId
      this.upTextList = [];
      this.open = true;
      this.title = "添加课件资源";
    },

    addResource(filePath){
      let _this=this;
      let obj={
        cateId:this.queryParams.cateId,
        id:this.queryParams.id,
        path:filePath,
        fileName:this.fileName,
        size:this.fileSize
      }
      addEl_resources(obj).then( response => {
        this.msgSuccess("新增成功");
        this.coursewareName=response.data.fileName;//课件名称
        this.loading = false;
        setTimeout(function (){
          _this.open = false;
        },2000)

        this.richTextCancel();
        this.allRemove();
        this.getList();
      });
    },
    updateResource(filePath) {
      let _this=this;
      let obj = {
        id: this.editForm.id,
        cateId: this.editForm.cateId,
        title: this.editForm.title,
        path: filePath,
        fileName: this.fileName,
        size: this.fileSize
      }
      updateEl_resources(obj).then(response => {
        this.msgSuccess("修改成功");
        this.loading = false;
        this.openEdit = false;
        this.coursewareName=response.data.fileName;//课件名称
        this.loading = false;
        setTimeout(function (){
          _this.open = false;
        },2000)
        this.allRemove();
        this.getList();
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      let self = this;

      //根据id查找父元素
      console.log(this.familyTree(this.treeData,row.cateId))
      let treeName=this.familyTree(this.treeData,row.cateId)
      let treeName1=treeName.reverse()
      let treeArr=[]
      treeName1.forEach(function (item){
        treeArr.push(item.title)

      })
      // self.typeTitle=treeArr.join('/')
      let text = '';
      for(let i=0;i<self.treeData.length;i++){
        if (row.cateId == self.treeData[i].id){
          text = self.treeData[i].title;
          break
        }
        for(let o=0;o<self.treeData[i].children.length;o++){
          if (row.cateId == self.treeData[i].children[o].id){
            text = self.treeData[i].title +'/'+ self.treeData[i].children[o].title;
            break
          }
          for(let x=0;x<self.treeData[i].children[o].children.length;x++){
            if (row.cateId == self.treeData[i].children[o].children[x].id){
              text = self.treeData[i].title +'/'+ self.treeData[i].children[o].title + '/' + self.treeData[i].children[o].children[x].title;
              break
            }
          }
        }
      }
      if(text[0]){
        self.typeTitle=text
      }else{
        self.typeTitle='该分类已删除'
      }

      if(row.type=='5'){
        this.richTextAddClick(2,row)
        return
      }


      this.coursewareName=row.title
      // this.queryParams.cateId=row.cateId
      //this.queryParams.id=row.id
       this.editForm.cateId=row.cateId
       this.editForm.id=row.id

      this.reset();
      this.uploadImgUrl = window.location.href.split('://')[0]+'://' + this.judgmentNetworkReturnAddress() + "/exam/el_resources?cateId=" + this.queryParams.cateId
      this.upTextList = [];
      this.open = true;
      this.title = "修改课件资源";
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delEl_resources(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('exam/el_resources/export', {
        ...this.queryParams
      }, `exam_el_resources.xlsx`)
    },
    fileSuccess(rootFile, file, response, chunk) {

      const result = JSON.parse(response);
      if (result.code==200 && !this.skip) {
        axios.post(httpHeader+this.judgmentNetworkReturnAddress()+"/base/file/upload/merge", {
            identifier: file.uniqueIdentifier,
            filename: file.name,
            totalChunks: chunk.offset,
          },{
            headers: {
              Authorization: "Bearer " + getToken()
            }
        }).then((res) => {
            if (res.data.code==200) {
              if(!this.editForm.id){//新增
                console.log(1)
                this.addResource(res.data.data);
              }else{//修改
                console.log(2)
                this.updateResource(res.data.data);
              }
              this.filePath=res.data.data;
            } else {
              console.log(res);
            }
          }).catch(function (error) {
            console.log(error);
          });
      } else {
        console.log("上传成功，不需要合并");
      }
      if (this.skip) {
        this.skip = false;
      }
    },
    fileComplete(rootFile) {
      // 一个根文件（文件夹）成功上传完成。
       this.fileName=rootFile.name;
       this.fileSize=rootFile.size;
      console.log("rootFile",rootFile)
    },
    complete(file) {
      console.log("complete file:",file)
      // 上传完毕。
    },
    filesAdded(file, fileList, event) {
      file.forEach((e) => {
        this.fileList.push(e);
        this.computeMD5(e);
      });
    },
    computeMD5(file) {
      let fileReader = new FileReader();
      let time = new Date().getTime();
      let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
      let currentChunk = 0;
      const chunkSize = 1024 * 1024;
      let chunks = Math.ceil(file.size / chunkSize);
      let spark = new SparkMD5.ArrayBuffer();
      // 文件状态设为"计算MD5"
      file.cmd5 = true; //文件状态为“计算md5...”
      file.pause();
      loadNext();
      fileReader.onload = (e) => {
        spark.append(e.target.result);
        if (currentChunk < chunks) {
          currentChunk++;
          loadNext();
          // 实时展示MD5的计算进度
        } else {
          let md5 = spark.end();
          spark.destroy(); //释放缓存
          file.uniqueIdentifier = md5; //将文件md5赋值给文件唯一标识
          file.cmd5 = false; //取消计算md5状态
          file.resume(); //开始上传
        }
      };
      fileReader.onerror = function () {
        this.error(`文件${file.name}读取出错，请检查该文件`);
        file.cancel();
      };
      function loadNext() {
        let start = currentChunk * chunkSize;
        let end = start + chunkSize >= file.size ? file.size : start + chunkSize;
        fileReader.readAsArrayBuffer(blobSlice.call(file.file, start, end));
      }
    },
    allStart() {
      this.fileList.map((e) => {
        if (e.paused) {
          e.resume();
        }
      });
    },
    allStop() {
      this.fileList.map((e) => {
        if (!e.paused) {
          e.pause();
        }
      });
    },
    allRemove() {
      this.fileList.map((e) => {
        e.cancel();
      });
      this.fileList = [];
    },
  }
};
</script>

<style scoped lang="scss">
  .el-resources {
    display: flex!important;
    flex-direction: column;
    box-shadow: 0 0 8px 2px rgba(0, 0, 0, 0.1);
    /*padding:20px!important;*/
    .list-max-big-box{
      flex:1;
      display: flex!important;
      flex-direction: column;
      padding:20px!important;
      overflow: hidden;
      .top-max-box{
        flex:1;
        display: flex;
        overflow: hidden!important;
        .left-max-box{
          width:250px;
          .classify_btn{
            font-size: 14px;
            font-family: Microsoft YaHei;
            font-weight: 400;
            color: #0183FA;
            line-height: 70px;
            cursor: pointer;
            text-align: left;
          }
        }
        .center-max-box{
          border-right:2px dashed #E0E0E0;
          margin-right:30px;
          margin-top:20px;
        }
        .right-max-box{
          flex:1;
          display: flex;
          flex-direction: column;
          overflow: hidden!important;
          .min-list-box{
            flex: 1;
            overflow: hidden!important;
            display: flex;
            margin-bottom:15px;
            .button-box{
              width:190px;
              display: flex;
            }
          }
        }
      }
      .bottom-max-box{
        height:50px;
      }

    }

  }
  .uploader{
    .uploader-drop{
      height: 200px;
      background: #fff;
      border-radius: 6px;
      text-align: center;
      >i{
        width: 100px;
        height: 78px;
        font-size: 78px;
        color: #0183FA;
        margin-top: 20px;
      }
      .uploader-btn{
        padding: 0;
        color: #0183FA;
        border: 0;
        cursor: pointer;
        background: none;
        outline: none;
        font-size: 14px;
      }
    }
  }
</style>
