<template>
  <div class="courseware-tab">
    <el-row v-if="isCreator">
      <el-col :span="3.5">
          <el-button
                  @click="uploadDialogVisible = true"
                  type="primary"
                  plain>新建</el-button>
      </el-col>
      <el-col :span="15">
          <span style="font-size: smaller; position: absolute; bottom: 25%">（支持拓展名：.pdf .jpg .jpeg .png .exe .zip，最大文件大小：100MB）</span>
      </el-col>
    </el-row>
    <el-dialog v-model="uploadDialogVisible" :before-close="handleCancelUpload" :width="700">
        <el-form ref="formRef" :model="form" label-width="100px" style="margin-top: 10px">
          <el-form-item label="使用类型" required>
              <el-select v-model="form.useMethod" placeholder="类型">
<!--                  <el-option key="1" label="浏览（支持拓展名：.pdf .ppt .pptx .doc .docx .xls .jpg .jpeg .png）" value="SCAN"></el-option>-->
                  <el-option key="1" label="浏览（支持拓展名：.pdf .jpg .jpeg .png）" value="SCAN"></el-option>
                  <el-option key="2" label="附件（支持拓展名：.exe .zip）" value="ATTACHMENT"></el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="文件" required>
              <el-upload
                  :file-list="fileList"
                  :on-change="handleUploadFile"
                  action=""
                  class="upload-demo"
                  :auto-upload="false"
                  :show-file-list="false"
              >
                  <el-button plain type="primary" class="tabs-function-button" size="small"
                  >上传文件</el-button>（仅支持上传单个文件，最大文件大小：100MB）
              </el-upload>
              <el-tag
                      v-if="isNameUnique"
                      :key="fileTag"
                      color="white"
                      closable
                      @close="handleCloseFileTag(fileTag)">
                  {{file.name}}
              </el-tag>
              <el-icon :size="20" style="color: #337ecc; position: absolute; bottom: 10%; margin-left: 5px"
                                v-if="isNameUnique" @click="handleChangeNameWhenUpload()">
                <Edit />
              </el-icon>
          </el-form-item>
          <el-form-item v-if="isChangeNameWhenUpload">
              <el-row>
                  <el-col :span="12">
                      <el-input v-model="this.newName" placeholder="请输入新课件名称" style="width: 95%;">
                          <template #append>{{nameAppend}}</template>
                      </el-input>
                  </el-col>
                  <el-col :span="4">
                      <el-button size="mini" type="text" @click="handleCancelChangeNameWhenUpload">取消修改</el-button>
                  </el-col>
              </el-row>
          </el-form-item>
          <el-form-item label="允许下载" required v-if="fileType === '.pdf'">
              <el-switch v-model="downloadValue" />
          </el-form-item>
        </el-form>
        <div style="margin: auto; width: fit-content">
          <el-button type="primary" @click="handleConfirmUpload" size="small">确定</el-button>
          <el-button @click="handleCancelUpload" size="small">取消</el-button>
        </div>
        <el-progress  v-if="percentageVisible" :indeterminate="true" :percentage="100" status="warning"
                     style="width: 40%; margin-top: 20px; margin-left: 30%"></el-progress>
    </el-dialog>

      <el-table :data="fileEntryList" style="width: 100%">
        <el-table-column
            type="index"
            width="50"
        >
        </el-table-column>
        <el-table-column
          prop="name"
          label="文件名"
          width="280"
          >
          <template #default="scope">
            <el-icon v-if="scope.row['courseWareVO'].useMethod === 'SCAN'" style="color: #337ecc" class="myicon"><Reading /></el-icon>
            <el-icon v-if="scope.row['courseWareVO'].useMethod === 'ATTACHMENT'" style="color: green" class="myicon"><Paperclip /></el-icon>
              {{scope.row['courseWareVO'].name}}
              <el-button v-if="Number(scope.row['courseWareVO'].senderId) === Number(this.$store.state.user.id)"
                         @click="handleChangeName(scope.row['courseWareVO'].id, scope.row['courseWareVO'].name)"
                         type="text" icon="el-icon-edit-outline" style="color: #337ecc; font-size: 18px">
              </el-button>
          </template>
        </el-table-column>
        <el-table-column
        prop="size"
        label="文件大小"
        width="100">
          <template #default="scope">
            {{getSizeTransition(scope.row["courseWareVO"].size)}}
          </template>
        </el-table-column>
        <el-table-column
        prop="created_time"
        label="上传时间"
        width="160"
        :sortable="true"
        >
          <template #default="scope">
              {{timestampToTime(scope.row["courseWareVO"].createdTime)}}
          </template>
        </el-table-column>
        <el-table-column
          prop="operation"
          label="操作">
          <template #default="scope">
<!--            <a :href="scope.row['courseWareVO'].fileUrl" v-if="isPdfOrPicture(scope.row['courseWareVO'].name) === 'OFFICE'">-->
<!--              <el-button style="color: #409EFF; margin-right: 10px" type="text">预览</el-button>-->
<!--            </a>-->

<!--            <el-button v-if="isPdfOrPicture(scope.row['courseWareVO'].name) === 'OFFICE'"-->
<!--                     @click="handlePreviewFile(scope.row['courseWareVO'].id)"-->
<!--                     style="color: #409EFF; margin-right: 10px" type="text">预览</el-button>-->
<!--            <a v-if="isPdfOrPicture(scope.row['courseWareVO'].name) === 'OFFICE'"-->
<!--             :href="getOfficeFileUrl(scope.row['courseWareVO'].fileUrl)">点击预览</a>-->
<!--            <a :href="scope.row['courseWareVO'].fileUrl" v-if="isPdfOrPicture(scope.row['courseWareVO'].name) === 'OFFICE'">-->
<!--              <el-button style="color: #67C23A" type="text">下载</el-button>-->
<!--            </a>-->
            <el-button v-if="isPdfOrPicture(scope.row['courseWareVO'].name) === 'PDF'"
                 @click="handlePreviewFile(scope.row['courseWareVO'].id)"
                       style="color: #409EFF" type="text">打开</el-button>
            <el-button v-if="scope.row['courseWareVO'].useMethod === 'SCAN' && isPdfOrPicture(scope.row['courseWareVO'].name) === 'PICTUREandATTACHMENT'"
                     @click="handlePreviewPicture(scope.row['courseWareVO'])"
                     style="color: #409EFF" type="text">打开</el-button>

<!--              <el-button v-if="checkDownloadButton(scope.row['courseWareVO'].id, scope.row['courseWareVO'].name) === '1'"-->
<!--            <el-button v-if="getCanDownloadById(scope.row['courseWareVO'].id) === true-->
<!--              <el-button v-if="canDownloadList === '1'-->
<!--                     && isPdfOrPicture(scope.row['courseWareVO'].name) === 'PDF'"-->
<!--                     @click="handleDownloadPdfFile(scope.row['courseWareVO'].fileUrl)"-->
<!--                     style="color: #67C23A" type="text">下载</el-button>-->
                          <a :href="scope.row['courseWareVO'].fileUrl"
                             v-if="scope.row['courseWareVO'].useMethod === 'ATTACHMENT' && isPdfOrPicture(scope.row['courseWareVO'].name) === 'PICTUREandATTACHMENT'">
                            <el-button style="color: #67C23A" type="text">下载</el-button>
                          </a>
            <el-button v-if="Number(scope.row['courseWareVO'].senderId) === Number(this.$store.state.user.id)"
                       style="color: #F56C6C; margin-left: 10px" type="text"
                       @click="handleRemoveCourseWare(scope.row['courseWareVO'].id)">删除</el-button>
          </template>
        </el-table-column>
    </el-table>
      <el-dialog
              v-model="picturePreviewDialogVisible"
              width="80%"
              :before-close="handleClosePreviewPicture"
      >
          <img :src="pictureUrl" alt="" style="width: 100%" class="image" />
          <template #footer>
      <span class="dialog-footer">
          <a :href="pictureUrl">
              <el-button type="success" style="margin-right: 10px" size="small">下载</el-button>
          </a>
          <el-button type="primary" @click="handleClosePreviewPicture" plain size="small">关闭</el-button>
      </span>
          </template>
      </el-dialog>
      <el-dialog
          v-model="nameChangeDialogVisible"
          width="30%"
          :before-close="handleCancelChangeName">
          <el-input v-model="this.newName" placeholder="请输入新课件名称">
              <template #append>{{nameAppend}}</template>
          </el-input>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="handleCancelChangeName">取消</el-button>
              <el-button type="primary" @click="handleConfirmChangeName" plain>确定</el-button>
            </span>
          </template>
      </el-dialog>
  </div>
</template>

<script>
    import portal from "@/utils/portal/portal";
    import {ElMessageBox} from "element-plus";
    import * as pdfjs from "pdfjs-dist";
    import * as pdfjsWorker from "pdfjs-dist/build/pdf.worker.entry";

    pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker;

export default {
  name: "CoursewareTab",
  components: {
  },
  props: {
    courseId: {
      required: true,
    },
    teacherId: {
      required: true,
    },
  },

  data() {
    return {
      form: {
        useMethod: "SCAN",
        useTime: "BEFORE_CLASS",
      },
      file: null,
      fileList: [],
      fileEntryList: [],
      uploadDialogVisible: false,
      picturePreviewDialogVisible: false,
      nameChangeDialogVisible: false,
      isChangeNameWhenUpload: false,
      isNameUnique: false,
      pictureUrl: null,
      pictureName: null,
      idToBeChangeName: null,
      newName: null,
      nameAppend: null,
      fileType: null,
      fileTag: null,
      fileNum: 0,
      pdfName: "",
      downloadValue: true,
      canDownloadList: [],
      courseWareNum: 0,
      //percentage: 0,
      percentageVisible: false
    };
  },

  computed: {
    isCreator() {
      return Number(this.teacherId) === Number(this.$store.state.user.id);
    },
  },
  mounted() {
      this.init();
  },
  methods: {
      init() {
          this.$apis.getCourseWaresByCourseId(this.courseId).then(res => {
              this.fileEntryList = res.data.data;
              this.courseWareNum = this.fileEntryList.length;
          });
      },

      handleChangeNameWhenUpload() {
          this.isChangeNameWhenUpload = true;
          this.nameAppend = this.file.name.substring(this.file.name.lastIndexOf("."));
      },

      handleCancelChangeNameWhenUpload() {
          this.isChangeNameWhenUpload = false;
          this.nameAppend = null;
      },

      handleChangeName(id, oldName) {
        this.nameChangeDialogVisible = true;
        this.idToBeChangeName = id;
        this.nameAppend = oldName.substring(oldName.lastIndexOf("."));
      },

      handleCancelChangeName() {
          ElMessageBox.confirm("是否退出修改课件名称？推出后将不保存已填写信息。", "提示", {
              confirmButtonText: "确认退出",
              cancelButtonText: "我再想想",
              type: "warning",
              center: true,
          })
          .then(() => {
              this.newName = null;
              this.nameAppend = null;
              this.nameChangeDialogVisible = false;
          });
      },

      handleConfirmChangeName() {
          if (this.newName === null  && this.nameAppend !== null) {
              this.$message({
                  message: "课件名称不可为空，请重新修改课件名称",
                  type: "error"
              });
              return;
          }
          // ElMessageBox.confirm("是否确定修改课件名称？", "提示", {
          //     confirmButtonText: "确认修改",
          //     cancelButtonText: "我再想想",
          //     type: "warning",
          //     center: true,
          // })
          // .then(res => {
              this.$apis.checkCourseWareNameUnique(this.courseId, this.newName + this.nameAppend)
              .then(res=> {
                  const isNameUnique = res.data.data;
                  if (!isNameUnique) {
                      this.$message({
                          message: "该课程下已存在同名课件",
                          type: "error"
                      });
                  } else {
                      this.$message({
                          message: "正在修改课件名称",
                          type: "success"
                      });
                      this.$apis.changeCourseWareName(this.idToBeChangeName, this.newName + this.nameAppend)
                          .then(res=> {
                              this.$apis.getCourseWaresByCourseId(this.courseId).then(res => {
                                  this.fileEntryList = res.data.data;
                              });
                              this.newName = null;
                              this.nameAppend = null;
                              this.nameChangeDialogVisible = false;
                          });
                  }
              });
         // });
      },

      timestampToTime: portal.functions.timestampToTime,

      handleUploadFile(file, fileList) {
          console.log(file);
          console.log(fileList);
          const fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
          console.log(this.form.useMethod + " + " + file.name.substring(file.name.lastIndexOf(".") + 1));
          if (this.form.useMethod === "SCAN") {
              if (!(fileType === "pdf" || fileType === "png" || fileType === "jpeg" || fileType === "jpg")) {
                  this.$message({
                      message: "该文件类型不属于支持的可浏览课件类型",
                      type: "error"
                  });
                  return;
              }
          } else {
              if (!(fileType === "exe" || fileType === "zip")) {
                  this.$message({
                      message: "该文件类型不属于支持的附件类型",
                      type: "error"
                  });
                  return;
              }
          }
          if (this.fileNum === 1) {
              this.$message({
                  message: "一次只能选择上传一个课件",
                  type: "error"
              });
              return;
          }
          this.file = file;
          this.fileList = fileList;
          this.$apis.checkCourseWareNameUnique(this.courseId, this.file.name)
          .then(res => {
              const isNameUnique = res.data.data;
              if (!isNameUnique) {
                  this.$message({
                      message: "该课程下已存在同名课件",
                      type: "error"
                  });
              } else {
                  this.isNameUnique = true;
                  this.fileNum = 1;
                  this.fileType = "." + fileType;
              }
          });
      },

      handleConfirmUpload() {
        if (this.file === null) {
            this.$message({
              message: "尚未上传课件",
              type: "error"
            });
        }
        else if (this.newName !== null) {
            this.$apis.checkCourseWareNameUnique(this.courseId, this.newName + this.nameAppend)
            .then(res => {
                const isNameUnique = res.data.data;
                if (!isNameUnique) {
                    this.$message({
                        message: "该课程下已存在同名课件",
                        type: "error"
                    });
                    this.newName = null;
                } else {
                    //this.percentage= 0;
                    this.percentageVisible = true;
                    this.$apis.uploadCourseWareFile(this.courseId + "/" + this.newName + this.nameAppend, this.file.raw)
                        .then(res => {
                            const fileUrl = res.data.data;
                            this.$apis.createCourseWare({
                                name: this.newName + this.nameAppend,
                                size: this.file.size,
                                senderId: this.$store.state.user.id,
                                courseId: this.courseId,
                                createdTime: new Date(),
                                useTime: "BEFORE_CLASS",
                                useMethod: this.form.useMethod,
                                fileUrl: fileUrl,
                            }).then(res => {
                                //this.percentage= 100;
                                this.$apis.setCanDownloadById(res.data.data.id, this.downloadValue);
                                this.$apis.getCourseWaresByCourseId(this.courseId)
                                    .then(res => {
                                        this.fileEntryList = res.data.data;
                                        this.courseWareNum = this.fileEntryList.length;
                                        this.$message({
                                            message: "上传课件成功",
                                            type: "success"
                                        });
                                        this.uploadDialogVisible = false;
                                        this.isChangeNameWhenUpload = false;
                                        this.isNameUnique = false;
                                        this.fileNum = 0;
                                        this.newName = null;
                                        this.nameAppend = null;
                                        this.file = null;
                                        this.fileType = null;
                                        this.percentageVisible = false;
                                    });
                            });
                        });
                }
            });
        }
        else if (this.nameAppend !== null) {
              this.$message({
                  message: "课件名称不可为空，请重新修改课件名称",
                  type: "error"
              });
              this.nameAppend = null;
        }
        else {
            //this.percentage= 0;
            this.percentageVisible = true;
            this.$message({
                message: "上传中，请稍候",
                type: "warning",
                duration: 5000
            });
            this.$apis.uploadCourseWareFile(this.courseId + "/" + this.file.name, this.file.raw)
                .then(res => {
                    const fileUrl = res.data.data;
                    this.$apis.createCourseWare({
                        name: this.file.name,
                        size: this.file.size,
                        senderId: this.$store.state.user.id,
                        courseId: this.courseId,
                        createdTime: new Date(),
                        useTime: "BEFORE_CLASS",
                        useMethod: this.form.useMethod,
                        fileUrl: fileUrl,
                    }).then(res => {
                        //this.percentage= 100;
                        this.$apis.setCanDownloadById(res.data.data.id, this.downloadValue);
                        this.$apis.getCourseWaresByCourseId(this.courseId)
                            .then(res => {
                                this.fileEntryList = res.data.data;
                                this.courseWareNum = this.fileEntryList.length;
                                this.$message({
                                    message: "上传课件成功",
                                    type: "success"
                                });
                                this.uploadDialogVisible = false;
                                this.isChangeNameWhenUpload = false;
                                this.isNameUnique = false;
                                this.fileNum = 0;
                                this.file = null;
                                this.fileType = null;
                                this.percentageVisible = false;
                            });
                    });
                });
        }
      },

      handleCancelUpload(done) {
        ElMessageBox.confirm("是否确认退出？退出后将不保存表格信息。", "提示", {
          confirmButtonText: "确认退出",
          cancelButtonText: "我再想想",
          type: "warning",
          center: true,
        })
        .then(() => {
          this.uploadDialogVisible = false;
          this.isChangeNameWhenUpload = false;
          this.isNameUnique = false;
          this.fileNum = 0;
          this.newName = null;
          this.nameAppend = null;
          this.fileType = null;
          this.percentageVisible = false;
          this.clearForm();
          // Zhurui修改，关闭dialog
          done();
        })
        .catch((err) => {
          console.log(err);
        });
      },

      handleCloseFileTag() {
        ElMessageBox.confirm("是否取消上传该课件？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "我再想想",
            type: "warning",
            center: true,
        })
        .then(() => {
            this.isChangeNameWhenUpload = false;
            this.nameAppend = null;
            this.fileType = null;
            this.isNameUnique = false;
            this.file = null;
            this.fileNum = 0;
            this.clearForm();
            done();
        })
        .catch((err) => {
            console.log(err);
        });
      },

      handleRemoveCourseWare(id) {
        ElMessageBox.confirm("是否确认删除该课件？", "提示", {
            confirmButtonText: "确认删除",
            cancelButtonText: "我再想想",
            type: "warning",
            center: true,
        })
        .then(() => {
            this.$apis.deleteCourseWare(id).then(async () => {
                this.fileEntryList = (await this.$apis.getCourseWaresByCourseId(this.courseId)).data.data;
                this.courseWareNum = this.fileEntryList.length;
            });
            this.uploadDialogVisible = false;
            this.fileNum = 0;
            this.clearForm();
            // Zhurui修改，关闭dialog
            done();
        })
        .catch((err) => {
            console.log(err);
        });
      },

      handleDownloadPdfFile(fileUrl) {
          window.open(fileUrl, "_blank");
      },

      handlePreviewFile(id) {
          this.$router.push("/courseWare/" + id + "/details");
          //window.open("/courseWare/" + id + "/details");
          // let nextURL = `https://p.seec.seecoder.cn/courseWare/?courseWareId=${id}/details&id_token=${this.$store.state.user.token}`;

          //const url = "https://p.seec.seecoder.cn/courseWare/" + id + "/details";
          //console.log(this.$store.state.user.token);
          //window.open("/courseWare/" + id + "/details");
      },

      handlePreviewPicture(courseWareVO) {
        this.picturePreviewDialogVisible = true;
        this.pictureUrl = courseWareVO.fileUrl;
        this.pictureName = courseWareVO.name;
      },

      isPdfOrPicture(name) {
        const fileType = name.substring(name.lastIndexOf(".") + 1);
        if (fileType === "pdf") {
            return "PDF";
        } else if (fileType === "png" || fileType === "jpg" || fileType === "jpeg"
                  || fileType === "zip"|| fileType === "exe") {
            return "PICTUREandATTACHMENT";
        } else {
            return "OFFICE";
        }
      },

      getSizeTransition(size) {
        if (size < 1024 * 1024) {
            return (size * 1.0 / 1024).toFixed(2) + " KB";
        } else {
            return (size * 1.0 / 1024 / 1024).toFixed(2) + " MB";
        }
      },

      handleClosePreviewPicture() {
          ElMessageBox.confirm("确定关闭图片预览？",{
              confirmButtonText: "关闭",
              cancelButtonText: "我再想想",
          })
            .then(() => {
                this.picturePreviewDialogVisible = false;
            });
      }
  }
};
</script>

<style scoped>
@import "tabs.css";

.myicon {
    position: relative;
    top: 2px;
    font-size: 14px;
    margin-right: 2px;
    transform: scale(1.2);
}

.mytag {
    transition: .2s;
    display: inline-block;
    padding: 3px;
    border-radius: 4px;
    margin-left: 2px;
    font-size: 12px;
    font-weight: bold;
    line-height: 1;
    vertical-align: middle;
    position: relative;
    bottom: 2px;
}

</style>
