<template>
  <div class="coursewareManagement-addPage">
    <div class="page-container-top-max-big-box-shadow">
      <p class="top-1-p">{{newData.id?'编辑课件':'添加课件'}}</p>
      <p class="top-2-p" @click="backPage()">返回</p>
      <p class="top-3-p" v-if="newData.id" @click="resetButton()">重置</p>
      <p class="top-4-p" @click="submitButton()">保存</p>
    </div>
    <div class="bottom-max-big-box scrollbar-box">
      <el-form class="add-form-box" :model="newData" ref="form" label-width="160px"
               :rules="rules">
        <div class="form-big-box">
          <div class="form-box">
            <div class="form-flex-box">
              <el-form-item label="类型" prop="materialType">
                <el-select v-model="newData.materialType" @change="changeUpDataNumType" placeholder="请选择课件类型" style="width: 400px">
                  <el-option
                    v-for="dict in optionListA"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="知识点" prop="knowledgePointId">
                <el-cascader
                  style="width: 400px"
                  v-model="newData.knowledgePointId"
                  :options="optionListB"
                  :props="{
                    emitPath:false,
                    checkStrictly: true,
                    value: 'id',
                    label: 'knowledgePointName',
                    children: 'children',
                  }"
                  :show-all-levels="false"
                  filterable
                  placeholder="请选择知识点"
                ></el-cascader>
              </el-form-item>
            </div>
          </div>
          <div class="form-box">
            <div class="form-flex-box">
              <el-form-item label="是否共享" prop="shareStatus" style="width:560px;">
                <el-switch
                  :active-value="1"
                  :inactive-value="0"
                  v-model="newData.shareStatus"
                  active-color="#0183FB"
                  inactive-color="#AAAAAA">
                </el-switch>
                <span style="margin-left:15px;">{{newData.shareStatus==1?'共享开启，全校所有学院单位都可见':'不共享，仅本学院单位及上级都可见'}}</span>
              </el-form-item>
              <el-form-item label="课件分类" prop="disciplineTypeId">
                <el-select v-model="newData.disciplineTypeId" placeholder="请选择课件分类" style="width: 400px">
                  <el-option
                    v-for="dict in optionListC"
                    :key="dict.id"
                    :label="dict.disciplineName"
                    :value="dict.id"
                  />
                </el-select>
              </el-form-item>
            </div>
          </div>
          <div class="form-box" v-if="newData.materialType == 1">
            <el-form-item label="视频上传" prop="attachments">
              <div class="form-flex-box" v-show="!uploadType">
                <uploader
                  style="width:400px;"
                  :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 style="height:240px;background-color: #fff">
                    <i class="el-icon-upload" style="font-size:80px;color:#D7D7D7;margin:20px 0 20px 150px;"></i>
                    <div class="el-upload__text" style="text-align: center">将文件拖到此处，或 <uploader-btn style="border:none;color:#0183fa;" :attrs="attrs">点击上传</uploader-btn></div>
                    <p style="color:#999;text-align: center;">上传视频类型 支持mp4 大小不超过{{fileSizeLimit}}G</p>
                  </uploader-drop>
                  <!--                 <uploader-list></uploader-list> -->
                  <!--                <uploader-files> </uploader-files>-->
                </uploader>
                <video v-if="newData.attachments[0]" :src="newData.attachments[0].attachmentSourcePath?newData.attachments[0].attachmentSourcePath:newData.attachments[0].attachmentPath"
                       controls style="width: 424px;height:240px;margin-left: 20px;"></video>
              </div>
              <div class="upLoad-box" v-if="uploadType">
                <div v-loading="uploadType" style="width:400px;height:200px;"></div>
                <p v-if="uploadType">正在上传请耐心等待</p>
              </div>
            </el-form-item>
          </div>
          <div class="form-box" v-if="newData.materialType == 1">
            <el-form-item label="">
              <el-input v-model="newData.watermark" placeholder="添加视频水印文字" maxLength="20" style="width:960px;"></el-input>
            </el-form-item>
          </div>
          <div class="form-box" v-if="newData.materialType == 3">
            <el-form-item label="文档上传" prop="attachments">
              <div class="form-flex-box">
                <el-upload
                  v-if="!newData.id"
                  style="width:400px;"
                  drag multiple
                  accept=".xlsx, .docx, .pdf"
                  :action="uploadImgUrl"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :headers="headers"
                  :before-upload="beforeAvatarUpload">
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                  <p style="line-height:25px;color:#333;">上传文件大小不超过1G</p>
                  <p style="line-height:25px;color:#333;">支持docx/xlsx/pdf格式文档</p>
                  <p style="line-height:25px;color:#333;">支持批量上传文档</p>
                </el-upload>
                <el-upload
                  v-if="newData.id"
                  style="width:400px;"
                  drag
                  accept=".xlsx, .docx, .pdf"
                  :action="uploadImgUrl"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :headers="headers"
                  :before-upload="beforeAvatarUpload">
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                  <p style="line-height:25px;color:#333;">上传文件大小不超过1G</p>
                  <p style="line-height:25px;color:#333;">支持docx/xlsx/pdf格式文档</p>
                  <p style="line-height:25px;color:#333;">支持批量上传文档</p>
                </el-upload>
                <div class="for-up-list-box scrollbar-box">
                  <div v-for="(item,index) in newData.attachments" :key="index">
                    <p class="el-icon-circle-check"></p>
                    <p>{{item.attachmentName}}</p>
                    <p class="el-icon-close" @click="delList(index)"></p>
                  </div>
                </div>
              </div>
            </el-form-item>
          </div>
          <div class="form-box" v-if="newData.materialType == 4" style="width:1120px;">
            <el-form-item label="文章内容" prop="articleContent">
              <div class="rich-text" >
                <tinymce-container
                  v-model="newData.articleContent"
                  :height="500"
                  :max-length="5000"
                  :upload-url="editorUploadUrl"
                  :upload-headers="editorUploadHeaders"
                />
              </div>
            </el-form-item>
          </div>
          <div class="form-box">
            <el-form-item label="课件名称" prop="coursewareName" v-if="!newData.attachments[1]">
              <el-input v-model="newData.coursewareName" placeholder="请输入课件名称" maxLength="20" style="width:960px;"></el-input>
            </el-form-item>
            <el-form-item label="课件名称" v-if="newData.attachments[1]">
              <el-input :disabled="newData.attachments[1]" placeholder="系统自动使用文件名" maxLength="20" style="width:960px;"></el-input>
            </el-form-item>
          </div>
          <div class="form-box">
            <el-form-item label="要求时长" prop="minLearningDuration">
              <el-input-number  class="form-input-number"
                                @change="examElCoursewareCalculateLearningReward"
                                style="width:200px"
                                :min="0"
                                :max="9999"
                                :step="1" :precision="0" step-strictly
                                v-model="newData.minLearningDuration">
              </el-input-number>
              <span style="margin-left:15px;">分钟</span>
            </el-form-item>
          </div>
          <div class="form-box">
            <div class="form-flex-box">
              <el-form-item label="可得学时" prop="autoCreditHours" style="width:410px;">
                <el-switch
                  :active-value="0"
                  :inactive-value="1"
                  v-model="newData.autoCreditHours"
                  active-color="#0183FB"
                  inactive-color="#AAAAAA">
                </el-switch>
                <span style="margin-left:15px;">{{newData.autoCreditHours==0?'手工填写开启':'手工填写关闭，系统自动计算'}}</span>
              </el-form-item>
              <el-form-item label="" prop="creditHours" label-width="0">
                <el-input-number  class="form-input-number"
                                  :disabled="newData.autoCreditHours==1"
                                  style="width:120px"
                                  :min="0"
                                  :max="9999"
                                  :step="0.1" :precision="1" step-strictly
                                  v-model="newData.creditHours">
                </el-input-number>
                <span style="margin-left:15px;">学时</span>
              </el-form-item>
              <el-form-item label="可得积分" prop="autoPoints" style="width:410px;" label-width="150px">
                <el-switch
                  :active-value="0"
                  :inactive-value="1"
                  v-model="newData.autoPoints"
                  active-color="#0183FB"
                  inactive-color="#AAAAAA">
                </el-switch>
                <span style="margin-left:15px;">{{newData.autoPoints==0?'手工填写开启':'手工填写关闭，系统自动计算'}}</span>
              </el-form-item>
              <el-form-item label="" prop="points" label-width="0">
                <el-input-number  class="form-input-number"
                                  :disabled="newData.autoPoints==1"
                                  style="width:120px"
                                  :min="0.00"
                                  :max="9999"
                                  :step="0.01" :precision="2" step-strictly
                                  v-model="newData.points">
                </el-input-number>
                <span style="margin-left:15px;">积分</span>
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
  //import { getDicts } from "@/api/commonality/noPermission";
  //import { systemUserSelect } from "@/api/commonality/permission";
  import {
    examElKnowledgePointTreeList,examElDisciplineTypeList,examElCoursewareCalculateLearningReward,
    examElCoursewareAdd,examElCoursewareEdit,examElCoursewareDetail,
  } from "@/api/safetyEducationExaminationNew/index";
  import { getToken } from "@/utils/auth";
  import TinymceContainer from "@/components/tinymceContainer/index.vue";
  import axios from "axios";
  import SparkMD5 from "spark-md5";
  let httpHeader=window.location.href.split('://')[0]+'://'
  export default {
    name: 'addPage',
    components: { TinymceContainer },
    props:{
      propsData:{},
    },
    data(){
      return{
        editorUploadUrl: this.uploadUrl(),
        editorUploadHeaders: {
          Authorization:getToken(),
        },
        //文件上传相关
        uploadImgUrl: this.uploadUrl(), // 上传的图片服务器地址
        headers: {
          Authorization:getToken(),
        },
        //页面状态
        buttonType:1,
        optionListA:[{value:1,label:'视频'},{value:3,label:'文档'},{value:4,label:'文章'}],
        optionListB:[],
        optionListC:[],
        newData:{
          materialType:null,
          knowledgePointId:null,
          disciplineTypeId:null,
          watermark:'',
          attachments:[],
          articleContent:'',
          coursewareName:'',
          minLearningDuration:0,
          autoCreditHours:0,
          creditHours:0,
          autoPoints:0,
          points:0,
          shareStatus:1,
        },
        rules:{
          materialType: [
            { required: true, message: "请选择课件类型", trigger: "blur" },
            { required: true, message: "请选择课件类型", validator: this.spaceJudgment, trigger: "blur" }
          ],
          knowledgePointId: [
            { required: true, message: "请选择知识点", trigger: "blur" },
            { required: true, message: "请选择知识点", validator: this.spaceJudgment, trigger: "blur" }
          ],
          disciplineTypeId: [
            { required: true, message: "请选择课件分类", trigger: "blur" },
            { required: true, message: "请选择课件分类", validator: this.spaceJudgment, trigger: "blur" }
          ],
          attachments: [
            { required: true, message: "请上传课件", trigger: "blur" },
            { required: true, message: "请上传课件", validator: this.spaceJudgment, trigger: "blur" }
          ],
          articleContent: [
            { required: true, message: "请输入文章", trigger: "blur" },
            { required: true, message: "请输入文章", validator: this.spaceJudgment, trigger: "blur" }
          ],
          coursewareName: [
            { required: true, message: "请输入课件名称", trigger: "blur" },
            { required: true, message: "请输入课件名称", validator: this.spaceJudgment, trigger: "blur" }
          ],
        },
        //批量上传
        fileSizeLimit:1,
        fileList:[],
        options: {
          target: httpHeader+this.judgmentNetworkReturnAddress()+"/exam/file/upload/chunk2",
          // 开启服务端分片校验功能
          testChunks: true,
          single: true,
          fileParameterName: 'file',
          // testMethod: 'post',
          //uploadMethod: 'get',
          headers: {
            Authorization: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: ["video/mp4"]
        },
        statusText: {
          success: "上传成功",
          error: "上传出错了",
          uploading: "上传中...",
          paused: "暂停中...",
          waiting: "等待中...",
          cmd5: "计算文件MD5中...",
        },
        uploadType:false,
      }
    },
    watch: {
      fileList(o, n) {
        this.disabled = false;
      },
    },
    created(){
      this.getData();
    },
    mounted(){
      this.examElKnowledgePointTreeList();
      this.examElDisciplineTypeList();
    },
    methods:{
      getData(){
        if(this.propsData.id){
          examElCoursewareDetail({id:this.propsData.id}).then(response => {
            this.$set(this,'newData',{
              id:response.data.id,
              materialType:response.data.materialType,
              knowledgePointId:response.data.knowledgePointId,
              disciplineTypeId:response.data.disciplineTypeId,
              watermark:response.data.watermark?response.data.watermark:'',
              coursewareName:response.data.coursewareName,
              minLearningDuration:response.data.minLearningDuration,
              autoCreditHours:response.data.autoCreditHours,
              creditHours:response.data.creditHours?response.data.creditHours:0,
              autoPoints:response.data.autoPoints,
              points:response.data.points?response.data.points:0,
              shareStatus:response.data.shareStatus,
            });
            if(response.data.materialType == 1 || response.data.materialType == 3){
              this.$set(this.newData,'attachments',[{
                attachmentPath:response.data.attachmentPath,
                attachmentName:response.data.attachmentName?response.data.attachmentName:'',
                attachmentSize:response.data.attachmentSize,
              }]);
              this.$set(this.newData,'articleContent','');
            }else if(response.data.materialType == 4){
              this.$set(this.newData,'attachments',[]);
              this.$set(this.newData,'articleContent',response.data.articleContent);
            }
          });
        }
      },
      // 返回按钮
      backPage(){
        this.$parent.tableButton(6);
      },
      //重置
      resetButton(){
        let self = this;
        this.$confirm('确认重置数据?', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
        }).then(() => {
          self.getData();
        }).catch(() => {});
      },
      //提交
      submitButton(){
        let self = this;
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.$confirm('是否确认保存?', "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(function() {
            }).then(() => {
              if(self.newData.id){
                //编辑课件
                self.examElCoursewareEdit();
              }else{
                //新增课件
                self.examElCoursewareAdd();
              }
            }).catch(() => {});
          }
        })
      },
      //计算时长
      examElCoursewareCalculateLearningReward(num){
        examElCoursewareCalculateLearningReward({minLearningDuration:num}).then(response => {
          this.$set(this.newData,'creditHours',response.data.creditHours);
          this.$set(this.newData,'points',response.data.points);
        });
      },
      //新增课件
      examElCoursewareAdd(){
        let obj = this.newData;
        examElCoursewareAdd(obj).then(response => {
          this.msgSuccess(response.message)
          this.$parent.tableButton(6);
        });
      },
      //编辑课件
      examElCoursewareEdit(){
        let obj = this.newData;
        examElCoursewareEdit(obj).then(response => {
          this.msgSuccess(response.message)
          this.$parent.tableButton(6);
        });
      },
      //类型切换
      changeUpDataNumType(){
        this.$set(this.newData,'attachments',[]);
      },
      //删除文档
      delList(index){
        this.newData.attachments.splice(index,1);
        if(!this.newData.attachments[1]){
          this.$set(this.newData,'coursewareName',this.getLeftPart(this.newData.attachments[0].attachmentName));
        }else{
          this.$set(this.newData,'coursewareName','');
        }
      },
      //文档上传验证
      handleAvatarSuccess(res) {
        if(this.newData.attachments.length>9){
          this.msgError('已到达上传数量上限')
          return
        }
        if(this.newData.id){
          this.$set(this.newData,'attachments',[{
            attachmentSourcePath:res.data.url,
            attachmentName:this.getLeftPart(res.data.name),
            attachmentSize:res.data.size+'',
          }]);
        }else{
          this.newData.attachments.push({
            attachmentSourcePath:res.data.url,
            attachmentName:this.getLeftPart(res.data.name),
            attachmentSize:res.data.size+'',
          });
        }
        if(!this.newData.attachments[1]){
          this.$set(this.newData,'coursewareName',this.getLeftPart(res.data.name));
        }else{
          this.$set(this.newData,'coursewareName','');
        }
      },
      beforeAvatarUpload(file) {
        let type = false;
        let num = 0;
        for(let i=0;i<file.name.length;i++){
          if(file.name[i] == '.'){
            num++
          }
        }
        if(num != 1){
          this.msgError('文件名称不能包含 " . "')
          return false
        }
        if (file.type == 'application/pdf' || file.type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'|| file.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
          if(file.size> 5250000){
            this.msgError('上传大小不能超过5M')
            return false
          }
          this.upDataName = file.name;
          type = true;
        }else{
          this.msgError('只能上传docx/xlsx/pdf格式')
          type = false;
        }
        return type;
      },
      //大文件上传
      fileSuccess(rootFile, file, response, chunk) {
        const result = JSON.parse(response);
        if (result.code==200 && !this.skip) {
          axios.post(httpHeader+this.judgmentNetworkReturnAddress()+"/exam/file/upload/merge", {
            identifier: file.uniqueIdentifier,
            filename: file.name,
            totalChunks: chunk.offset,
          },{
            headers: {
              Authorization:getToken()
            }
          }).then((res) => {
            if (res.data.code==200) {
              this.$set(this,'uploadType',false);
              this.$set(this.newData,'attachments',[{
                attachmentSourcePath:res.data.data.url,
                attachmentName:this.getLeftPart(res.data.data.name),
                attachmentSize:res.data.data.size+'',
              }]);
              this.$set(this.newData,'coursewareName',this.getLeftPart(res.data.data.name));
              this.$set(this.newData,'minLearningDuration',Math.max(1, Math.round(res.data.data.duration / 60)));
              this.examElCoursewareCalculateLearningReward(Math.max(1, Math.round(res.data.data.duration / 60)));
            } else {
              this.msgError('上传出错,请稍后再试')
            }
          }).catch(function (error) {
          });
        } else {
          this.msgError('上传出错,请稍后再试')
        }
      },
      getLeftPart(str) {
        const index = str.lastIndexOf('.');
        // 如果没有找到 '.'，直接返回原字符串
        if (index === -1) return str;
        return str.substring(0, index);
      },
      fileComplete(rootFile) {
        // 一个根文件（文件夹）成功上传完成。
        this.fileName=rootFile.name;
        this.fileSize=rootFile.size;
      },
      complete(file) {
        // 上传完毕。
      },
      filesAdded(file, fileList, event) {
        file.forEach((item)=>{
          if(["video/mp4"].indexOf(item.fileType) === -1){
            this.msgError("文件格式不支持,请上传正确的文件.");
            file.ignored = true;
          }else{
            this.$set(this,'uploadType',true);
            this.fileList.push(item);
            this.computeMD5(item);
          }
        })
      },
      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));
        }
      },
      //知识点
      examElKnowledgePointTreeList(){
        examElKnowledgePointTreeList({}).then(response => {
          const list = response.data || [];
          this.formatTreeData(list);
          this.$set(this, 'optionListB', list);
        });
      },
      //查询全部专业类别
      examElDisciplineTypeList(){
        examElDisciplineTypeList({}).then(response => {
          this.$set(this,'optionListC',response.data);
        });
      },
    },
  }
</script>

<style scoped lang="scss">
  .coursewareManagement-addPage{
    flex:1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    .bottom-max-big-box{
      flex:1;
      display: flex;
      border-radius:10px;
      margin:5px 20px 20px 10px;
      box-shadow: 0 0 8px 1px rgba(0, 0, 0, 0.1);
      .form-big-box{
        padding:20px;
        .form-box{

        }
        .upLoad-box{
          width:400px;
          height:240px;
          div{
            width:400px;
            height:200px;
          }
          p{
            line-height: 40px;
            font-size:14px;
            text-align: center;
            color:#0183fa;
          }
        }
        .form-flex-box{
          display: flex;
          ::v-deep .el-upload-dragger{
            width:400px;
            height:240px;
          }
          .for-up-list-box{
            border:1px dashed #dedede;
            height:240px;
            width:540px;
            margin-left:20px;
            border-radius:6px;
            padding:20px;
            div{
              display: flex;
              p:nth-child(1){
                width: 40px;
                height: 40px;
                text-align: center;
                font-weight: 700;
                font-size: 30px;
                line-height: 40px;
                color: #70B603;
              }
              p:nth-child(2){
                flex:1;
                font-size:14px;
                height:40px;
                line-height:40px;
                margin-left:10px;
              }
              p:nth-child(3){
                width: 40px;
                height: 40px;
                text-align: center;
                font-weight: 700;
                font-size: 30px;
                line-height: 40px;
                cursor: pointer;
                color:#999;
              }
              p:nth-child(3):hover{
                color:#FF6666;
              }
            }
          }
        }
      }
    }
  }
</style>
