<template>
  <div class="createZyCourse" v-loading="loading">
    <el-card>
      <div style="padding: 0 75px;">
        <span class="title">课程资源</span>
        <span class="subTitle">我的课程 - 我创建的 - <span class="pointer" @click="goBack">课程资源</span> - <span style="color: #000;">{{editId=="" ? "添加" : "编辑"}}</span></span>
      </div>
    </el-card>

    <el-card>
      <div style="color: #050026;font-size: 18px;font-weight: 400;">{{editId=="" ? "添加" : "编辑"}}</div>
      <div class="formContent">
        <el-form :model="formline" ref="formline" :rules="rules" size="large" label-position="top" class="demo-ruleForm">
          <div class="must">
            <div class="label">上传源文件</div>
            <div class="uploadDiv" v-loading="attachLoading">
              <div style="position: relative;">
                <el-upload class="attachUpload" action="" accept=".doc, .docx, .xls, .xlsx, .ppt, .pptx, .pdf, .mp3, .mp4" :auto-upload="false" drag :on-change="handleAttachChange" :file-list="attachList">
                  <el-icon size="19" color="#9d9ab9">
                    <FolderOpened />
                  </el-icon>
                </el-upload>
                <div style="font-size: 12px;position: absolute;left: 85px;top: 0;">
                  <div style="color: #949494;position: absolute;white-space: nowrap;">支持格式：doc,docx,xls,xlsx,ppt,pptx,pdf,mp3,mp4（500M以内）</div>
                  <div style="color: #F35421;position: absolute;white-space: nowrap;top: 50px;" v-if="attachList.length==0">{{attachTip}}</div>
                </div>
              </div>
            </div>
          </div>
          <div class="must">
            <div class="label" :style="{marginTop: imageData.length!=0 ? '-100px' : 0}">课程封面图</div>
            <div class="uploadDiv">
              <div style="display: flex;">
                <el-upload class="mainUpload" action="" accept=".png, .jpg, .jpeg" :auto-upload="false" list-type="picture-card" :on-change="handleMainChange" :file-list="fileList">
                  <el-icon size="38" color="#9d9ab9" v-if="fileList.length==0">
                    <Picture />
                  </el-icon>
                  <img v-else :src="fileList[0].url" alt="" style="width: 100%;height: 100%;" />
                </el-upload>
                <div style="font-size: 12px;margin-left: 20px;position: relative;">
                  <div style="color: #949494;">支持格式：jpg,png,jpeg（200kb以内） 建议尺寸600x320</div>
                  <div style="color: #F35421;position: absolute;bottom: 0;" v-if="fileList.length==0">{{mainTip}}</div>
                </div>
              </div>
              <div class="tips" v-if="imageData.length!=0">
                <div style="color: #f35421;font-size: 12px;margin: 10px 0;">如上不上传，封面自动抓取，提供前5帧当中的任意三张图片（如下）供教师选择</div>
                <div class="flex">
                  <!-- <img class="user" src="/images/personal/user.png" />
                  <img class="user" src="/images/personal/user.png" /> -->
                  <img class="pointer" v-for="(item, index) in imageData" :key="index" :src="getFullUrl(item)" alt="" @click="initImg(item)" />
                </div>
              </div>
            </div>
          </div>
          <el-form-item label="资源名称" prop="kf_name">
            <el-input v-model="formline.kf_name" />
          </el-form-item>
          <el-form-item label="关联的作业">
            <el-select v-model="linkWork" multiple placeholder=" " size="large">
              <el-option v-for="item in workData" :key="item.yzk_id" :label="item.yzk_name" :value="item.yzk_id" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="editId==''">
            <el-checkbox class="read" v-model="isRead" label="已阅读并同意《课程上传协议》" size="large" />
          </el-form-item>
          <el-form-item>
            <div class="btnDiv">
              <el-button type="primary" @click="submitForm('formline')" :loading="commitLoading">提 交</el-button>
              <el-button @click="goBack">关 闭</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { upload_file, files_add, files_edit, files_detail } from "./api";
import { Picture, FolderOpened } from "@element-plus/icons-vue";
import { getFullUrl } from '@/utils/helper';
export default {
  data() {
    return {
      loading: false,
      parentId: "",
      editId: "",
      formline: {
        kf_img: "",
        kf_path: "",
        kf_name: "",
        yzk_id: "",
      },
      rules: {
        kf_name: [{ required: true, message: '请输入资源名称', trigger: 'blur' }],
      },
      workData: [],
      linkWork: [],
      imageData: [],
      fileList: [],
      mainFileData: ["png", "jpg", "jpeg"],
      mainFileSize: 200,
      mainTip: "",
      attachList: [],
      attachFileData: ["doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf", "mp3", "mp4"],
      attachFileSize: 500,
      attachTip: "",
      attachLoading: false,
      commitLoading: false,
    }
  },
  components: { Picture, FolderOpened },
  methods: {
    goBack() {
      this.$router.go(-1);
    },
    // 编辑获取详情
    initDetailInfo() {
      this.loading = true;
      files_detail({ kf_id: this.editId }).then((res) => {
        if (res.code == 1) {
          for (let key in this.formline) {
            for (let key1 in res.data.one_info) {
              if (key == key1) {
                this.formline[key] = res.data.one_info[key1];
              }
            }
          }

          this.fileList = [{
            url: getFullUrl(this.formline.kf_img)
          }]
          if (this.formline.kf_path != "") {
            let arr = this.formline.kf_path.split("/");
            this.attachList = [{
              name: arr[arr.length - 1],
              url: getFullUrl(this.formline.kf_path)
            }]
          }
          if (this.formline.yzk_id != "") {
            this.linkWork = this.formline.yzk_id.split(",");
          }
          this.loading = false;
        }
      });
    },
    // 封面图
    handleMainChange(file) {
      let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
      const isJPG = this.mainFileData.includes(fileType);
      const sizeLimit = file.size / 1024 < this.mainFileSize;
      if (!isJPG) {
        this.mainTip = "上传文件只能是jpg,png,jpeg格式";
      }
      if (!sizeLimit) {
        this.mainTip = "上传文件不能超过200KB";
      }
      if (isJPG && sizeLimit) {
        this.fileList = [file];
      } else {
        this.fileList = [];
      }

      if (this.fileList.length == 0) {
        return false;
      }

      upload_file(file.raw).then(res => {
        if (res.code == 1) {
          this.formline.kf_img = res.data.url;
        } else {
          this.mainTip = "上传失败";
        }
      })
    },
    // 源文件
    handleAttachChange(file) {
      let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
      const isJPG = this.attachFileData.includes(fileType);
      const sizeLimit = file.size / 1024 / 1024 < this.attachFileSize;
      if (!isJPG) {
        this.attachTip = "上传文件只能是doc,docx,xls,xlsx,ppt,pptx,pdf,mp3,mp4格式";
      }
      if (!sizeLimit) {
        this.attachTip = "上传文件不能超过500MB";
      }
      if (isJPG && sizeLimit) {
        this.attachList = [file];
      } else {
        this.attachList = [];
      }

      if (this.attachList.length == 0) {
        return false;
      }

      this.attachLoading = true;
      let firstpage = fileType == "mp3" || fileType == "MP3" ? "" : 1;
      let lastpage = fileType == "mp3" || fileType == "MP3" ? "" : 3;
      let convert = fileType == "mp3" || fileType == "MP3" ? "" : "jpg";
      upload_file(file.raw, firstpage, lastpage, convert).then(res => {
        console.log(res)
        if (res.code == 1) {
          this.formline.kf_path = res.data.url;
          this.imageData = res.data.filelist || [];
          if (this.imageData.length != 0 && this.formline.kf_img == "") {
            this.formline.kf_img = this.imageData[0];
            this.fileList = [{
              url: getFullUrl(this.formline.kf_img)
            }]
          }
        } else {
          this.attachTip = "上传失败";
        }
        this.attachLoading = false;
      })
    },
    initImg(img) {
      this.formline.kf_img = img;
      this.fileList = [{
        url: getFullUrl(this.formline.kf_img)
      }]
    },
    initWorkData() {
      request({
        url: '/yzy/zy_kczy/index',
        data: {}
      }).then(res => {
        if (res.code == 1) {
          this.workData = res.data.page_data;
        }
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid && this.formline.kf_img != "" && this.formline.kf_path != "" && !this.attachLoading) {
          this.formline.yzk_id = this.linkWork.join(",");
          this.formline.kk_id = this.parentId;
          let data = {
            kczy_files: this.formline
          }
          if (this.editId == "") {
            if (!this.isRead) {
              this.$message.error("请勾选已阅读并同意《课程上传协议》");
              return false;
            }
            this.commitLoading = true;
            files_add(data).then(res => {
              if (res.code == 1) {
                this.$message.success("保存成功！");
                this.goBack();
              }
            })
          } else {
            this.commitLoading = true;
            data.kf_id = this.editId;
            files_edit(data).then(res => {
              if (res.code == 1) {
                this.$message.success("保存成功！");
                this.goBack();
              }
            })
          }
        } else {
          if (this.attachLoading) {
            this.$message.error("源文件上传中！");
          }
          if (this.formline.kf_img == "") {
            this.mainTip = "请上传资源封面图";
          }
          if (this.formline.kf_path == "") {
            this.attachTip = "请上传源文件";
          }
        }
      });
    }
  },
  created() {
    this.initWorkData();

    this.parentId = this.$route.query.parentId;
    this.editId = this.$route.query.id || "";
    if (this.editId != "") {
      this.initDetailInfo();
    }
  }
}
</script>

<style lang="scss" scoped>
.createZyCourse::v-deep {
  .el-card {
    margin-bottom: 15px;
    background: #fff;
  }
  .pointer {
    cursor: pointer;
  }
  .title {
    font-size: 18px;
    color: #050026;
  }
  .subTitle {
    font-size: 14px;
    color: #949494;
    margin-left: 45px;
  }
  .formContent {
    width: 575px;
    margin: auto;
    .el-form-item {
      &.is-required {
        .el-form-item__label {
          &::before {
            display: none;
          }
          &::after {
            content: "*";
            color: #f35421;
            margin-left: 4px;
          }
        }
      }
      .el-form-item__label {
        color: #949494;
        font-size: 14px;
        position: relative;
      }
      .el-form-item__content {
        .el-select {
          width: 100%;
        }
        .el-input {
          width: 100%;
          .el-input__wrapper {
            width: 100%;
            box-shadow: none;
            background: #f9f9f9;
            border-radius: 6px;
          }
        }
        .el-textarea {
          .el-textarea__inner {
            box-shadow: none;
            background: #f9f9f9;
            border-radius: 6px;
            // color: #d0d0d0;
          }
        }
        .el-checkbox.read {
          .el-checkbox__inner {
            border-radius: 50%;
          }
        }
        .el-input__inner {
          // color: #d0d0d0;
        }
      }
    }
    .must {
      display: flex;
      align-items: center;
      margin-bottom: 22px;
      .label {
        color: #949494;
        font-size: 14px;
        margin-right: 15px;
        &::after {
          content: "*";
          color: #f35421;
          margin-left: 4px;
        }
      }
      .uploadDiv {
        flex: 1;
        .el-upload--picture-card {
          width: 180px;
          height: 96px;
        }
        .mainUpload {
          .el-upload--picture-card {
            width: 180px;
            height: 96px;
          }
          .el-upload-list--picture-card .el-upload-list__item {
            display: none;
          }
        }
        .attachUpload {
          .el-upload-dragger {
            width: 65px;
            height: 65px;
            padding: 0;
            line-height: 65px;
            background: #f9f9f9;
          }
        }
        .tips {
          img {
            width: 90px;
            height: 48px;
            border-radius: 4px;
            margin-right: 10px;
          }
        }
      }
    }
    .showType {
      width: 100%;
      height: 40px;
      background: #f9f9f9;
      border-radius: 6px;
      display: flex;
      align-items: center;
      padding: 0 20px;
      .typeItem {
        color: #fff;
        font-size: 13px;
        padding: 3px 8px;
        border-radius: 6px;
        margin-right: 20px;
        line-height: 22px;
      }
    }
    .type {
      padding: 0 20px;
      margin-bottom: 10px;
      .flex {
        display: flex;
        align-items: baseline;
        .label {
          font-size: 13px;
          color: #333;
          &::after {
            content: "*";
            color: #f35421;
            margin-left: 4px;
          }
        }
        .valueDiv {
          margin-left: 15px;
          flex: 1;
          display: flex;
          flex-wrap: wrap;
          color: #949494;
          padding-bottom: 15px;
          font-weight: 400;
          font-size: 14px;
          .item {
            padding: 3px 5px;
            margin-right: 20px;
            margin-bottom: 5px;
            &.active {
              color: #00a3ff;
              border-radius: 6px;
              background: rgba($color: #00a3ff, $alpha: 0.1);
            }
          }
        }
      }
    }
    .btnDiv {
      text-align: center;
      width: 100%;
      .el-button {
        background: #f4f4f4;
        border: none;
        width: 160px;
        height: 50px;
        color: #41387f;
        font-family: PingFangSC, PingFangSC-Semibold;
      }
      .el-button--primary {
        background: #00a3ff;
        margin-right: 80px;
        color: #fff;
      }
    }
  }
}
</style>