<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">
          <el-form-item label="课程封面图" class="kcfmt" prop="ks_img">
            <file-upload-progress v-model:part="ks_img" list-type="picture-card" accept=".jpg,.png,.jpeg" :size-limit="5 * 1024" @compile="handleCompile">
              <template #default>
                <el-icon size="38" color="#9d9ab9" v-if="formline.ks_img == ''">
                  <Picture />
                </el-icon>
                <img v-else :src="getFullUrl(formline.ks_img)" alt="" style="width: 100%;height: 100%;" />
              </template>
              <template #tip>
                <div style="color: #949494;font-size: 12px;margin-left: 20px;display: inline-block;vertical-align: top;line-height: 20px;">
                  支持格式：jpg,png,jpeg（5M以内） 建议尺寸600x320</div>
              </template>
            </file-upload-progress>
          </el-form-item>
          <!-- <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（5MB以内）</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="ks_img_cropping">
            <div class="w-300px h-160px">
              <VueCropper ref="cropper" autoCrop :img="cropImg" fixed centerBox>
              </VueCropper>
            </div>

          </el-form-item>
          <el-form-item label="课程名称" prop="ks_name">
            <el-input v-model="formline.ks_name" />
          </el-form-item>
          <!-- <el-form-item label="课时数" prop="ks_kss">
            <el-input v-model="formline.ks_kss" />
          </el-form-item> -->
          <el-form-item label="课程简介">
            <el-input v-model="formline.ks_brief" type="textarea" rows="5" />
          </el-form-item>
          <div style="display: flex;">
            <el-form-item style="flex: 1;" label="开始时间" prop="ks_start_datetime">
              <el-config-provider :locale="local">
                <el-date-picker popper-class="ssystime" v-model="formline.ks_start_datetime" value-format="YYYY-MM-DD HH:mm:ss" :disabled-date="pickerStartTime" :disabled-hours="pickerStartHour" :disabled-minutes="pickerStartMinute" :disabled-seconds="pickerStartSecond" type="datetime"
                  placeholder="选择日期时间"></el-date-picker>
              </el-config-provider>
            </el-form-item>
            <el-form-item style="flex: 1;margin-left: 20px;" label="结束时间" prop="ks_end_datetime">
              <el-config-provider :locale="local">
                <el-date-picker popper-class="ssystime" v-model="formline.ks_end_datetime" value-format="YYYY-MM-DD HH:mm:ss" :disabled-date="pickerEndTime" :disabled-hours="pickerEndHour" :disabled-minutes="pickerEndMinute" :disabled-seconds="pickerEndSecond" type="datetime" placeholder="选择日期时间">
                </el-date-picker>
              </el-config-provider>
            </el-form-item>
          </div>
          <!-- <el-form-item label="开始时间 - 结束时间" prop="ks_start_datetime">
            <el-date-picker v-model="time" type="datetimerange" @change="handleTimeChange" value-format="YYYY-MM-DD HH:mm:ss" />
          </el-form-item> -->
          <div class="flex">
            <el-form-item class="flex-1" label="年级" prop="grade_id">
              <remote-multi-select v-model="formline.grade_id" v-model:model-name="formline.grade_name" to="grade"></remote-multi-select>
            </el-form-item>
            <el-form-item class="flex-1" style="margin-left: 20px;" label="学科" prop="subject_id">
              <remote-multi-select v-model="formline.subject_id" v-model:model-name="formline.subject_name" to="subject"></remote-multi-select>
            </el-form-item>
          </div>
          <!-- <div class="must" style="display: block;">
            <div class="label" style="margin-bottom: 12px;">类型（每个类型只能选一个）</div>
            <div class="showType">
              <div class="typeItem" style="background: #00a3ff;">{{ formline.grade_name }}</div>
              <div class="typeItem" style="background: rgba(0,131,197,0.8);">{{ formline.subject_name }}</div>
            </div>
          </div>
          <div class="type">
            <div class="flex">
              <div class="label">年级</div>
              <div class="valueDiv">
                <div class="item pointer" :class="formline.grade_id == item.grade_id ? 'active' : ''" @click="initGrade(item)" v-for="item in gradeData" :key="item.grade_id">{{ item.grade_name }}</div>
              </div>
            </div>
            <div class="flex">
              <div class="label">分类</div>
              <div class="valueDiv">
                <div class="item pointer" :class="formline.subject_id == item.subject_id ? 'active' : ''" @click="initSubject(item)" v-for="item in subjectData" :key="item.subject_id">{{ item.subject_name }}
                </div>
              </div>
            </div>
          </div> -->
          <el-form-item label="附件">
            <file-upload-progress v-model:part="formline.ks_kj" :limit="1" accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.mp4,.mp3" :size-limit="1500 * 1024">
              <template #default>
                <div class="flex_center w-65px h-65px border border-dashed border-hex-E4E6E8 bg-hex-F9F9F9 text-hex-9D9AB9">
                  <i-akar-icons:plus class="text-xl" />
                </div>
              </template>
              <template #tip>
                <div class="mt-2">支持格式：doc,docx,xls,xlsx,ppt,pptx,pdf,mp4,mp3（1500M以内）</div>
              </template>
            </file-upload-progress>
          </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.yys_id" :label="item.yys_name" :value="item.yys_id" />
            </el-select>
          </el-form-item>

          <!-- <el-form-item label="结对老师/组" prop="ks_jdjs_json">
            <teacher-json v-model="formline.ks_jdjs_json"></teacher-json>
          </el-form-item> -->
          <el-form-item label="客座名师" prop="ks_kzms_json">
            <teacher-json v-model="formline.ks_kzms_json" :compare="formline.ks_qkls_json"></teacher-json>
          </el-form-item>
          <el-form-item label="全科老师" prop="ks_qkls_json">
            <teacher-json v-model="formline.ks_qkls_json" :compare="formline.ks_kzms_json"></teacher-json>
          </el-form-item>
          <!-- <el-form-item label="结对班级">
            <el-select v-model="activeClass" placeholder=" " multiple size="large" value-key="class_id" @change="initActiveClass">
              <el-option v-for="item in classData" :key="item.class_id" :label="item.class_name" :value="item" />
            </el-select>
          </el-form-item> -->
          <el-form-item label="回放视频">
            <file-upload-progress v-model:part="formline.ks_lzsp" accept=".mp4">
              <template #default>
                <div class="flex_center w-65px h-65px border border-dashed border-hex-E4E6E8 bg-hex-F9F9F9 text-hex-9D9AB9">
                  <i-akar-icons:plus class="text-xl" />
                </div>
              </template>
              <template #tip>
                <div class="mt-2">支持格式：mp4</div>
              </template>
            </file-upload-progress>
          </el-form-item>

          <div style="display: flex;">
            <el-form-item style="flex: 1;" label="是否手机端推荐课程">
              <el-radio-group v-model="formline.ks_sfsjdtjkc">
                <el-radio v-for="item in sfsjdtjkcData" :key="item.v" :label="item.v" size="large">{{
                  item.n
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item style="flex: 1;margin-left: 50px;" label="是否精品">
              <el-radio-group v-model="formline.ks_sfjp">
                <el-radio v-for="item in sfjpData" :key="item.v" :label="item.v" size="large">{{ item.n }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div style="display: flex;">
            <el-form-item style="flex: 1;" label="是否前台显示">
              <el-radio-group v-model="formline.is_qtxs">
                <el-radio label="1" size="large">是</el-radio>
                <el-radio label="2" size="large">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item style="flex: 1;margin-left: 50px;" label="是否需要审核">
              <el-radio-group v-model="formline.ks_sfxysh">
                <el-radio v-for="item in sfxyshData" :key="item.v" :label="item.v" size="large">{{ item.n }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <!-- <el-form-item label="审核状态">
            <el-select v-model="formline.ks_shzt" placeholder=" " size="large">
              <el-option v-for="item in shztData" :key="item.v" :label="item.n" :value="item.v" />
            </el-select>
          </el-form-item>
          <el-form-item label="审核对象">
            <el-select v-model="formline.shdx" placeholder=" " size="large">
              <el-option v-for="item in shdxData" :key="item.value" :label="item.label" :value="item.value" />
            </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 { VueCropper } from 'vue-cropper'
import 'vue-cropper/dist/index.css'
import { grade_list, subject_list, ssyskc_list, upload_file, ssyskc_add, ssyskc_edit, ssyskc_detail } from "./api";

import { Picture, FolderOpened, ArrowDownBold, CircleClose, Back, Right } from "@element-plus/icons-vue";
import { ElConfigProvider } from 'element-plus'
import zhcn from 'element-plus/dist/locale/zh-cn.mjs'
import { getFullUrl, base64toBlob } from '@/utils/helper';
import request from '@/utils/request';
import TeacherJson from "./components/TeacherJson.vue";
import user from '~/store/user';
export default {
  data() {
    return {
      loading: false,
      local: zhcn,
      editId: "",
      time: [],
      ks_img: "",
      formline: {
        ks_img: "",
        ks_kj: "",
        ks_lzsp: "",
        ks_name: "1",
        ks_kss: "1",
        ks_brief: "1",
        ks_start_datetime: "2022-01-01 11:00",
        ks_end_datetime: "2022-01-02 11:00",
        grade_id: "",
        grade_name: "",
        subject_id: "",
        subject_name: "",
        yys_id: "",
        ks_jdjs_json: "",
        ks_kzms_json: "",
        ks_qkls_json: "",
        ks_jdbj_json: "",
        ks_sfsjdtjkc: "",
        ks_sfjp: "",
        is_qtxs: "",
        ks_sfxysh: "",
        // ks_shzt: "",
        // shdx: "",
      },
      rules: {
        ks_img: [{ required: true, message: "请选择课程封面图", trigger: "submit" }],
        ks_name: [
          { required: true, message: '请输入课程名称', trigger: 'blur' },
        ],
        ks_kss: [
          { required: true, message: '请输入课时数', trigger: 'blur' },
        ],
        // ks_brief: [
        //   { required: true, message: '请输入简介', trigger: 'blur' },
        // ],
        ks_start_datetime: [
          { required: true, message: '请选择时间', trigger: 'change', type: 'date' },
        ],
        ks_end_datetime: [
          { required: true, message: '请选择结束时间', trigger: 'change', type: 'date' },
        ],
        // ks_kj: [{ required: true, message: '请上传源文件', trigger: 'submit' }],
        // ks_jdjs_json: [
        //   { required: true, message: '请选择结对老师/组', trigger: 'change' },
        // ],
        grade_id: [{ required: true, message: "请选择年级", trigger: "submit" }],
        subject_id: [{ required: true, message: "请选择学科", trigger: "submit" }],
        ks_kzms_json: [
          { required: true, message: '请选择客座名师', trigger: 'change' },
        ],
        ks_qkls_json: [
          { required: true, message: '请选择全科老师', trigger: 'change' },
        ],
      },
      fileList: [],
      mainFileData: ["png", "jpg", "jpeg"],
      mainFileSize: 5120,
      mainTip: "",
      attachList: [],
      attachFileData: ["doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf", "mp3", "mp4"],
      attachFileSize: 500,
      attachTip: "",
      attachLoading: "",
      gradeData: ["一年级", "二年级", "三年级", "四年级", "五年级", "六年级", "初一", "初二", "初三", "高一", "高二", "高三"],
      subjectData: ["美术", "音乐", "舞蹈"],
      userIdData1: [],
      userIdData2: [],
      workData: [],
      linkWork: [],
      classData: [],
      activeClass: [],
      sfsjdtjkcData: [],
      sfjpData: [],
      sfxyshData: [],
      shztData: [],
      shdxData: [],
      isRead: false,
      pickerTime: (time) => {
        return time.getTime() < new Date() - 8.64e7
      },
      pickerStartTime: (time) => {
        let endDateVal = this.formline.ks_end_datetime;
        // if (beginDateVal) {
        //   return time.getTime() < new Date() || time.getTime() > new Date(beginDateVal).getTime();
        // } else {
        //   return time.getTime() < new Date()
        // }
        if (endDateVal) {
          return time.getTime() > new Date(endDateVal).getTime();
        }
      },
      pickerStartHour: () => {
        let beginDateVal = this.formline.ks_start_datetime;
        let endDateVal = this.formline.ks_end_datetime;
        if (beginDateVal) {
          // 若为同一天设置禁用
          if (new Date(beginDateVal).toDateString() === new Date(endDateVal).toDateString()) {
            return Array.from({ length: 24 - new Date(endDateVal).getHours() }, (v, i) => i + 1 + new Date(endDateVal).getHours());
          } else {
            return []
          }
        } else {
          return []
        }
      },
      pickerStartMinute: () => {
        let beginDateVal = this.formline.ks_start_datetime;
        let endDateVal = this.formline.ks_end_datetime;
        if (beginDateVal) {
          // 若为同一天同一小时设置禁用
          if (new Date(beginDateVal).toDateString() === new Date(endDateVal).toDateString() && new Date(beginDateVal).getHours() === new Date(endDateVal).getHours()) {
            return Array.from({ length: 60 - new Date(endDateVal).getMinutes() }, (v, i) => i + 1 + new Date(endDateVal).getMinutes());
          } else {
            return []
          }
        } else {
          return []
        }
      },
      pickerStartSecond: () => {
        let beginDateVal = this.formline.ks_start_datetime;
        let endDateVal = this.formline.ks_end_datetime;
        if (beginDateVal) {
          // 若为同一天同一小时同一分钟设置禁用
          if (new Date(beginDateVal).toDateString() === new Date(endDateVal).toDateString() && new Date(beginDateVal).getHours() === new Date(endDateVal).getHours() && new Date(beginDateVal).getMinutes() === new Date(endDateVal).getMinutes()) {
            return Array.from({ length: 60 - new Date(endDateVal).getSeconds() }, (v, i) => i + 1 + new Date(endDateVal).getSeconds());
          } else {
            return []
          }
        } else {
          return []
        }
      },
      pickerEndTime: (time) => {
        let beginDateVal = this.formline.ks_start_datetime;
        // if (beginDateVal) {
        //   return time.getTime() < new Date(beginDateVal).getTime();
        // } else {
        //   return time.getTime() < new Date()
        // }
        if (beginDateVal) {
          if (new Date(beginDateVal).getTime() == new Date(new Date(beginDateVal).toLocaleDateString()).getTime()) {
            return time.getTime() < new Date(beginDateVal).getTime();
          } else {
            return time.getTime() < new Date(beginDateVal).getTime() - 8.64e7;
          }
        }
      },
      pickerEndHour: () => {
        let beginDateVal = this.formline.ks_start_datetime;
        let endDateVal = this.formline.ks_end_datetime;
        if (beginDateVal) {
          // 若为同一天设置禁用
          if (new Date(beginDateVal).toDateString() === new Date(endDateVal).toDateString()) {
            return Array.from({ length: new Date(beginDateVal).getHours() }, (v, i) => i);
          } else {
            return []
          }
        } else {
          return []
        }
      },
      pickerEndMinute: () => {
        let beginDateVal = this.formline.ks_start_datetime;
        let endDateVal = this.formline.ks_end_datetime;
        if (beginDateVal) {
          // 若为同一天同一小时设置禁用
          if (new Date(beginDateVal).toDateString() === new Date(endDateVal).toDateString() && new Date(beginDateVal).getHours() === new Date(endDateVal).getHours()) {
            return Array.from({ length: new Date(beginDateVal).getMinutes() }, (v, i) => i);
          } else {
            return []
          }
        } else {
          return []
        }
      },
      pickerEndSecond: () => {
        let beginDateVal = this.formline.ks_start_datetime;
        let endDateVal = this.formline.ks_end_datetime;
        if (beginDateVal) {
          // 若为同一天同一小时同一分钟设置禁用
          if (new Date(beginDateVal).toDateString() === new Date(endDateVal).toDateString() && new Date(beginDateVal).getHours() === new Date(endDateVal).getHours() && new Date(beginDateVal).getMinutes() === new Date(endDateVal).getMinutes()) {
            return Array.from({ length: new Date(beginDateVal).getSeconds() }, (v, i) => i);
          } else {
            return []
          }
        } else {
          return []
        }
      },
      commitLoading: false,
      cropImg: undefined
    }
  },
  watch: {
    formline: {
      deep: true,
      handler(val) {
        if (val.ks_kzms_json) {
          let data1 = JSON.parse(val.ks_kzms_json);
          this.userIdData1 = data1.map(item => { return item.user_id });
        } else {
          this.userIdData1 = [];
        }
        if (val.ks_qkls_json) {
          let data2 = JSON.parse(val.ks_qkls_json);
          this.userIdData2 = data2.map(item => { return item.user_id });
        } else {
          this.userIdData2 = [];
        }
        this.initWorkData();
      }
    },
  },
  components: { Picture, FolderOpened, ElConfigProvider, ArrowDownBold, CircleClose, Back, Right, VueCropper, TeacherJson },
  methods: {
    getBase64(url) {
      return request({
        url: '/common/main/img2base64',
        data: {
          image_url: url
        }
      }).then(res => {
        if (res.code === '1') {
          this.cropImg = base64toBlob(res.data?.image?.replace(/\r\n/g, "")?.replace("\n", ""))
        }
      })
    },
    goBack() {
      this.$router.go(-1);
    },
    handleTimeChange(data) {
      if (data != null) {
        this.formline.ks_start_datetime = data[0];
        this.formline.ks_end_datetime = data[1];
      } else {
        this.formline.ks_start_datetime = "";
        this.formline.ks_end_datetime = "";
      }
    },
    initValue() {
      for (let key in this.formline) {
        this.formline[key] = "";
      }

      this.formline.ks_sfsjdtjkc = "1";
      this.formline.ks_sfjp = "1";
      this.formline.is_qtxs = "1";
      this.formline.ks_sfxysh = "1";
      // if (this.gradeData[0]) {
      //   this.formline.grade_name = this.gradeData[0].grade_name;
      //   this.formline.grade_id = this.gradeData[0].grade_id;
      // }
      // if (this.subjectData[0]) {
      //   this.formline.subject_name = this.subjectData[0].subject_name;
      //   this.formline.subject_id = this.subjectData[0].subject_id;
      // }

      let obj = {
        user_id: user.user_id,
        user_realname: user.user_realname,
        user_name: user.user_name
      }
      this.formline.ks_kzms_json = JSON.stringify([obj]);
    },
    // 编辑获取详情
    initDetailInfo() {
      this.loading = true;
      ssyskc_detail({ ks_id: this.editId }).then(async (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.time = [this.formline.ks_start_datetime, this.formline.ks_end_datetime];

          this.fileList = [{
            url: getFullUrl(this.formline.ks_img)
          }]
          // this.cropImg =
          await this.getBase64(this.formline.ks_img)
          if (this.formline.ks_kj) {
            let arr = this.formline.ks_kj.split("/");
            this.attachList = [{
              name: arr[arr.length - 1],
              url: getFullUrl(this.formline.ks_kj)
            }]
          }
          // if (this.formline.yys_id != "") {
          //   this.linkWork = this.formline.yys_id.split(",");
          // }

          if (this.formline.ks_jdbj_json != "") {
            this.activeClass = JSON.parse(this.formline.ks_jdbj_json);
          }
          this.formline.ks_lzsp = this.formline.ks_lzsp.replaceAll(/,/g, ';');
          this.loading = false;
        }
      });
    },
    // 获取下拉数据
    initSelectData() {
      ssyskc_list().then((res) => {
        if (res.code == 1) {
          // 是否手机端推荐课程
          this.sfsjdtjkcData = res.data.table_structure.field.ks_sfsjdtjkc.option;
          // 是否精品
          this.sfjpData = res.data.table_structure.field.ks_sfjp.option;
          // 是否需要审核
          this.sfxyshData = res.data.table_structure.field.ks_sfxysh.option;
          // 审核对象
          this.shztData = res.data.table_structure.field.ks_shzt.option;
        }
      });
    },
    // 年级
    initGradeData() {
      this.gradeData = [];
      grade_list({ limit: 50 }).then((res) => {
        if (res.code == 1) {
          this.gradeData = res.data.page_data;

          // if (this.gradeData[0] && this.editId == "") {
          //   this.formline.grade_name = this.gradeData[0].grade_name;
          //   this.formline.grade_id = this.gradeData[0].grade_id;
          // }
        }
      });
    },
    // 分类
    initSubjectData() {
      this.subjectData = [];
      subject_list({ limit: 50 }).then((res) => {
        if (res.code == 1) {
          this.subjectData = res.data.page_data;

          // if (this.subjectData[0] && this.editId == "") {
          //   this.formline.subject_name = this.subjectData[0].subject_name;
          //   this.formline.subject_id = this.subjectData[0].subject_id;
          // }
        }
      });
    },
    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;
    },
    initWorkData() {
      let arr = this.userIdData1.concat(this.userIdData2);
      console.log(arr)
      return request({
        url: '/yzy/zy_ssys/index',
        data: {
          teacher_user_ids_str: arr.join(","),
          limit: "100"
        }
      }).then(res => {
        if (res.code == 1) {
          this.workData = res.data.page_data;

          if (this.editId && this.formline.yys_id != "") {
            this.linkWork = this.formline.yys_id.split(",");
          }
        }
      })
    },
    // 班级
    initClassData() {
      request({
        url: '/jcxx/class/index',
        data: {}
      }).then(res => {
        if (res.code == 1) {
          this.classData = res.data.page_data;
        }
      })
    },
    initActiveClass(value) {
      let data = [];
      value.map((item) => {
        let obj = {
          class_id: item.class_id,
          class_name: item.class_name
        }
        data.push(obj);
      })
      this.formline.ks_jdbj_json = JSON.stringify(data);
    },
    handleCompile(fileList) {
      let data = fileList[fileList.length - 1];
      this.formline.ks_img = data.response.data.url;
      this.cropImg = data.url;
    },
    // 封面图
    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 = "上传文件不能超过5MB";
      }
      if (isJPG && sizeLimit) {
        this.fileList = [file];
      } else {
        this.fileList = [];
      }

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

      console.log('file :>> ', file);
      upload_file(file.raw).then(res => {
        if (res.code == 1) {
          this.formline.ks_img = res.data.url;
          this.cropImg = file.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 = "上传文件不能超过1500MB";
      }
      if (isJPG && sizeLimit) {
        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.ks_kj = res.data.url;
        } else {
          this.attachTip = "上传失败";
        }
        this.attachLoading = false;
      })
    },
    async submitForm(formName) {
      try {
        const crop = new Promise((resolve, reject) => {
          this.$refs.cropper.getCropBlob(cropBlob => {
            const cropFile = new File([cropBlob], 'crop.jpeg', { type: cropBlob.type })
            console.log('cropFile :>> ', cropFile);
            upload_file(cropFile).then(res => {
              if (res.code == 1) {
                this.formline.ks_img_cropping = res.data.url;
                resolve(res.data.url)
              } else {
                reject(null)
              }
            })
          })
        })

        crop.then(res => {
          this.$refs[formName].validate((valid) => {
            if (valid && this.formline.ks_img != "" && !this.attachLoading) {
              this.formline.yys_id = this.linkWork.join(",");
              let data = {
                kzkt_ssyskc: this.formline
              }
              if (this.formline.ks_sfxysh == "1") {
                data.kzkt_ssyskc.ks_shzt = "2";
              } else {
                data.kzkt_ssyskc.ks_shzt = "1";
              }
              if (new Date(this.formline.ks_end_datetime).getTime() < new Date(this.formline.ks_start_datetime).getTime()) {
                this.$message.warning("结束时间必须大于开始时间！");
                return;
              }

              this.formline.ks_lzsp = this.formline.ks_lzsp.replaceAll(/;/g, ',');
              if (this.editId == "") {
                if (!this.isRead) {
                  this.$message.error("请勾选已阅读并同意《课程上传协议》");
                  return false;
                }
                this.commitLoading = true;
                ssyskc_add(data).then(res => {
                  if (res.code == 1) {
                    this.$message.success("保存成功！");
                    this.goBack();
                  }
                })
              } else {
                this.commitLoading = true;
                data.ks_id = this.editId;
                ssyskc_edit(data).then(res => {
                  if (res.code == 1) {
                    this.$message.success("保存成功！");
                    this.goBack();
                  }
                })
              }
            } else {
              if (this.attachLoading) {
                this.$message.error("附件上传中！");
              }
              if (this.formline.ks_img == "") {
                this.mainTip = "请上传课程封面图";
              }
              // if (this.formline.ks_kj == "") {
              //   this.attachTip = "请上传源文件";
              // }
            }
          });
        })
      } catch (error) {
        console.log("error：", error);
        return
      }
    }
  },
  created() {
    this.initSelectData();
    this.initGradeData();
    this.initSubjectData();
    this.initClassData();
  },
  mounted() {
    this.editId = this.$route.query.id || "";
    if (this.editId == "") {
      this.initValue();
    } else {
      this.initDetailInfo();
    }
  }
}
</script>

<style lang="scss" scoped>
.createCourse {
  .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;

    .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;
      }
    }

    :deep() {
      .kcfmt {
        .el-upload--picture-card {
          width: 180px;
          height: 96px;
        }

        .el-upload-list.el-upload--picture-card,
        .el-upload-list__item {
          display: none;
        }
      }
    }

    .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>

<style lang="scss">
.createCourse {
  .el-card {
    margin-bottom: 15px;
    background: #fff;

    .el-form {
      .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-date-editor {
            box-shadow: none;
            background: #f9f9f9;
            border-radius: 6px;
          }

          .el-checkbox.read {
            .el-checkbox__inner {
              border-radius: 50%;
            }
          }

          .el-input__inner {
            // color: #d0d0d0;
          }
        }
      }

      .uploadDiv {
        .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;
          }
        }
      }
    }
  }
}

.ssystime {
  .el-picker-panel__footer {
    display: none;
  }
}
</style>
