<template>
  <!-- 课程资源创建课程 -->
  <div class="createCourse" 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">
              <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>
          </div>
          <el-form-item label="责任教师" prop="kk_zrjs">
            <el-input v-model="formline.kk_zrjs" />
          </el-form-item>
          <el-form-item label="学校/机构名称" prop="kk_jgmc">
            <el-input v-model="formline.kk_jgmc" />
          </el-form-item>
          <el-form-item label="课程名称" prop="kk_name">
            <el-input v-model="formline.kk_name" />
          </el-form-item>
          <el-form-item label="课程简介" prop="kc_jj">
            <el-input v-model="formline.kc_jj" type="textarea" rows="5" />
          </el-form-item>
          <div style="display: flex">
            <el-form-item style="flex: 1" label="年级" prop="grade_id">
              <el-select v-model="activeGrade" placeholder=" " size="large" @change="initGrade" value-key="grade_id">
                <el-option v-for="item in gradeData" :key="item.grade_id" :label="item.grade_name" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item style="flex: 1; margin-left: 50px" label="学科" prop="subject_id">
              <el-select v-model="activeSubject" placeholder=" " size="large" @change="initSubject" value-key="subject_id">
                <el-option v-for="item in subjectData" :key="item.subject_id" :label="item.subject_name" :value="item" />
              </el-select>
            </el-form-item>
          </div>
          <el-form-item label="分类">
            <el-cascader :options="cateData" placeholder=" " :props="cateProps" v-model="cateValue" @change="initCate" />
          </el-form-item>
          <div class="must">
            <div class="label">上传附件</div>
            <div class="uploadDiv" v-loading="attachLoading">
              <div style="position: relative">
                <el-upload class="attachUpload" action="" accept=".xls, .xlsx" :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;
                    ">
                    支持格式：xls,xlsx
                  </div>
                  <div style="
                      color: #f35421;
                      position: absolute;
                      white-space: nowrap;
                      top: 50px;
                    " v-if="attachList.length == 0">
                    {{ attachTip }}
                  </div>
                </div>
              </div>
            </div>
          </div>
          <el-form-item label="是否推送名师在线">
            <el-radio-group v-model="formline.kc_tsms">
              <el-radio label="1" size="large">是</el-radio>
              <el-radio label="2" size="large">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <div style="display: flex;">
            <el-form-item style="flex: 1;" label="推送时间" prop="kc_ts_dateline">
              <el-config-provider :locale="local">
                <el-date-picker popper-class="ssystime" v-model="formline.kc_ts_dateline" value-format="YYYY-MM-DD HH:mm" :disabled-date="pickerStartTime" type="datetime" placeholder="选择日期时间"></el-date-picker>
              </el-config-provider>
            </el-form-item>
            <el-form-item style="flex: 1;margin-left: 20px;" label="下线时间" prop="kc_ts_xxtime">
              <el-config-provider :locale="local">
                <el-date-picker popper-class="ssystime" v-model="formline.kc_ts_xxtime" value-format="YYYY-MM-DD HH:mm" :disabled-date="pickerEndTime" type="datetime" placeholder="选择日期时间"></el-date-picker>
              </el-config-provider>
            </el-form-item>
          </div>
          <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 {
  grade_list,
  subject_list,
  cate_list,
  cate_tree_list,
  upload_file,
  kc_add,
  kc_edit,
  kc_detail,
} from "./api";
import { Picture, FolderOpened } from "@element-plus/icons-vue";
import { getFullUrl } from "@/utils/helper";
export default {
  data() {
    return {
      loading: false,
      editId: "",
      gradeData: [
        "一年级",
        "二年级",
        "三年级",
        "四年级",
        "五年级",
        "六年级",
        "初一",
        "初二",
        "初三",
        "高一",
        "高二",
        "高三",
      ],
      subjectData: ["美术", "音乐", "舞蹈"],
      cateData: [],
      cateProps: {
        value: "kc_id",
        label: "kc_name",
        children: "treeList",
      },
      cateValue: [],
      formline: {
        kk_img: "",
        kk_fj: "",
        kk_zrjs: "",
        kk_jgmc: "",
        kk_name: "",
        kc_jj: "",
        grade_id: "",
        grade_name: "",
        subject_id: "",
        subject_name: "",
        kc_cate_level_1: "",
        kc_cate_level_2: "",
        kc_tsms: "1",
        kc_ts_dateline: "",
        kc_ts_xxtime: "",
      },
      activeGrade: {},
      activeSubject: {},
      rules: {
        kk_zrjs: [{ required: true, message: "请输入创建人", trigger: "blur" }],
        kk_jgmc: [{ required: true, message: "请输入学校/机构名称", trigger: "blur" }],
        kk_name: [{ required: true, message: "请输入课程名称", trigger: "blur" }],
        kc_jj: [{ required: true, message: "请输入简介", trigger: "blur" }],
        grade_id: [{ required: true, message: "请选择年级", trigger: "change" }],
        subject_id: [{ required: true, message: "请选择学科", trigger: "change" }],
        kc_ts_dateline: [{ required: true, message: '请选择推送时间', trigger: 'change', type: 'date' }],
        kc_ts_xxtime: [{ required: true, message: '请选择下线时间', trigger: 'change', type: 'date' }]
      },
      fileList: [],
      mainFileData: ["png", "jpg", "jpeg"],
      mainFileSize: 200,
      mainTip: "",
      attachList: [],
      attachFileData: ["xls", "xlsx"],
      // attachFileSize: 500,
      attachTip: "",
      attachLoading: false,
      isRead: false,
      pickerStartTime: (time) => {
        let beginDateVal = this.formline.kc_ts_xxtime;
        if (beginDateVal) {
          return time.getTime() < new Date() || time.getTime() > new Date(beginDateVal).getTime();
        } else {
          return time.getTime() < new Date()
        }
      },
      pickerEndTime: (time) => {
        let beginDateVal = this.formline.kc_ts_dateline;
        if (beginDateVal) {
          return time.getTime() < new Date(beginDateVal).getTime();
        } else {
          return time.getTime() < new Date()
        }
      },
      commitLoading: false,
    };
  },
  components: { Picture, FolderOpened },
  methods: {
    // 年级
    initGradeData() {
      this.gradeData = [];
      grade_list({ limit: 50 }).then((res) => {
        if (res.code == 1) {
          this.gradeData = res.data.page_data;
        }
      });
    },
    // 科目
    initSubjectData() {
      this.subjectData = [];
      subject_list({ limit: 50 }).then((res) => {
        if (res.code == 1) {
          this.subjectData = res.data.page_data;
        }
      });
    },
    // 分类
    initCateData() {
      this.cateData = [];
      cate_tree_list().then((res) => {
        if (res.code == 1) {
          this.cateData = res.data;
        }
      });
    },
    goBack() {
      this.$router.go(-1);
    },
    initValue() {
      for (let key in this.formline) {
        this.formline[key] = "";
      }
      this.formline.kc_tsms = "1";
    },
    // 编辑获取详情
    initDetailInfo() {
      this.loading = true;
      kc_detail({ kk_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.gradeData.map((item) => {
            if (item.grade_id == this.formline.grade_id) {
              this.activeGrade = item;
            }
          });

          this.subjectData.map((item) => {
            if (item.subject_id == this.formline.subject_id) {
              this.activeSubject = item;
            }
          });

          this.cateValue = [
            this.formline.kc_cate_level_1,
            this.formline.kc_cate_level_2,
          ];

          this.fileList = [
            {
              url: getFullUrl(this.formline.kk_img),
            },
          ];
          if (this.formline.kk_fj != "") {
            let arr = this.formline.kk_fj.split("/");
            this.attachList = [
              {
                name: arr[arr.length - 1],
                url: getFullUrl(this.formline.kk_fj),
              },
            ];
          }
          this.loading = false;
        }
      });
    },
    initGrade(value) {
      this.formline.grade_name = value.grade_name;
      this.formline.grade_id = value.grade_id;
    },
    initSubject(value) {
      this.formline.subject_name = value.subject_name;
      this.formline.subject_id = value.subject_id;
    },
    initCate(value) {
      this.formline.kc_cate_level_1 = value[0];
      this.formline.kc_cate_level_2 = value[1];
    },
    // 封面图
    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.kk_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 = "上传文件只能是ppt,pptx,pdf,mp4格式";
      }
      // if (!sizeLimit) {
      //   this.attachTip = "上传文件不能超过500MB";
      // }
      // if (isJPG && sizeLimit) {
      if (isJPG) {
        this.attachList = [file];
      } else {
        this.attachList = [];
      }

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

      this.attachLoading = true;
      upload_file(file.raw).then((res) => {
        if (res.code == 1) {
          this.formline.kk_fj = res.data.url;
        } else {
          this.attachTip = "上传失败";
        }
        this.attachLoading = false;
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (
          valid &&
          this.formline.kk_img != "" &&
          this.formline.kk_fj != "" &&
          !this.attachLoading
        ) {
          let data = {
            kczy_kc: this.formline,
          };
          if (this.editId == "") {
            if (!this.isRead) {
              this.$message.error("请勾选已阅读并同意《课程上传协议》");
              return false;
            }
            this.commitLoading = true;
            kc_add(data).then((res) => {
              if (res.code == 1) {
                this.$message.success("保存成功！");
                this.goBack();
              }
            });
          } else {
            this.commitLoading = true;
            data.kk_id = this.editId;
            kc_edit(data).then((res) => {
              if (res.code == 1) {
                this.$message.success("保存成功！");
                this.goBack();
              }
            });
          }
        } else {
          if (this.attachLoading) {
            this.$message.error("附件上传中！");
          }
          if (this.formline.kk_img == "") {
            this.mainTip = "请上传课程封面图";
          }
          if (this.formline.kk_fj == "") {
            this.attachTip = "请上传附件";
          }
        }
      });
    },
  },
  async created() {
    this.initValue();
    await this.initGradeData();
    await this.initSubjectData();
    await this.initCateData();

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

<style lang="scss" scoped>
.createCourse::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,
        .el-cascader {
          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;
          }
        }
      }
    }
    .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>