<template>
  <div class="edit-course-wrapper">
    <el-dialog
      class="dialog-title-border"
      ref="testDialogRef"
      title="上传课程"
      :model-value="dialogVisible"
      @close="backToOrgCourse"
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="860px"
    >
      <template v-slot:title>
        <div style="text-align: left">
          <span style="font-weight: 700">上传课程</span>
          <span style="font-size: 12px; color: #ed3131; margin-left: 4px"
            >上传信息需要审核，请认真核对上传内容，一旦提交后将不能修改</span
          >
        </div>
      </template>
      <div v-show="step == 1" class="course-content">
        <el-form
          ref="formDataRef"
          :model="formData"
          label-width="120px"
          class="basic-form"
        >
          <div class="basic-item-icon">
            <span class="require">*</span>
            <el-form-item label="课程名称：" class="valid-msg">
              <el-col :span="20">
                <el-input
                  size="small"
                  v-model="formData.courseName"
                  placeholder="请输入课程名称"
                  style="width: 360px"
                  maxlength="25"
                  :disabled="disabled"
                ></el-input>
                <span class="word-num">
                  {{
                    (formData.courseName || '').replace(/\s+/g, '').length
                  }}/25
                </span>
                <div
                  v-show="!needShowAuditMsg && noCouseName"
                  class="error"
                  style="maring-top: 2px"
                >
                  <span>请输入课程名称</span>
                </div>
                <div
                  v-show="needShowAuditMsg && formData.courseNameCheck"
                  class="error"
                  style="maring-top: 2px"
                >
                  <span>{{ formData.courseNameCheck }}</span>
                </div>
              </el-col>
            </el-form-item>
          </div>

          <div class="basic-item-icon">
            <span class="require">*</span>
            <el-form-item label="学科分类：" class="valid-msg">
              <el-col :span="18">
                <!-- :props="{ expandTrigger: 'hover' }" -->
                <el-cascader
                  style="width: 360px"
                  size="small"
                  v-model="formData.subjectIdList"
                  :options="labelOptions"
                  :props="{ value: 'id', label: 'name', children: 'subList' }"
                >
                </el-cascader>
                <div
                  v-show="!needShowAuditMsg && noLabel"
                  class="error"
                  style="margin-top: 4px"
                >
                  <span>请选择学科分类</span>
                </div>
              </el-col>
            </el-form-item>
          </div>
          <div class="basic-item-icon">
            <span class="require">*</span>
            <el-form-item label="开放范围：">
              <el-radio-group v-model="formData.shareType">
                <el-radio :label="1">机构共享</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>

          <div class="basic-item-icon">
            <span class="require">*</span>
            <el-form-item label="课程视频：" prop="range" class="valid-msg">
              <el-upload
                ref="uploadFileCom"
                class="upload-video"
                :class="{
                  disabled:
                    needShowUploadProcess ||
                    formData.courseCustomChapterModels[0]
                      .courseCustomLectureModelList.length >=
                      orgCourseInfo.limitModel.maxLimitVideoCount,
                }"
                action="#"
                :before-upload="beforeUploadVideo"
                :show-file-list="false"
                :disabled="
                  needShowUploadProcess ||
                  formData.courseCustomChapterModels[0]
                    .courseCustomLectureModelList.length >=
                    orgCourseInfo.limitModel.maxLimitVideoCount
                "
              >
                <template v-slot:trigger>
                  <el-button ref="uploadFileBtn" type="primary"
                    ><img
                      style="
                        width: 12px;
                        height: 12px;
                        position: relative;
                        top: 1px;
                      "
                      src="../../../assets/image/phrase3/icon-upload.png"
                    />
                    <span style="font-size: 14px"> 上传文件</span></el-button
                  >
                </template>
                <template v-slot:tip>
                  <div class="el-upload__tip">
                    <span class="upload-tips"
                      >只支持MP4格式，课程视频最多上传100个，单文件最大500M</span
                    >
                    <ul
                      v-show="
                        formData.courseCustomChapterModels[0]
                          .courseCustomLectureModelList.length
                      "
                      class="custom-list"
                    >
                      <li
                        v-for="(lecture, index) in formData
                          .courseCustomChapterModels[0]
                          .courseCustomLectureModelList"
                        :key="index"
                        class="valid-msg video-wrappe"
                      >
                        <ul class="video">
                          <li style="height: 46px; line-height: 48px">
                            <span class="title">视频{{ index + 1 }}</span>
                            <img
                              src="../../../assets/image/phrase3/icon-pin.png"
                            />
                            <span
                              class="name"
                              @click="previewVideoAction(lecture)"
                              >{{ lecture.resourceModel.name }}</span
                            >
                          </li>
                          <li class="other-action">
                            <div>
                              <el-upload
                                ref="uploadFileCom"
                                class="upload-video"
                                action="#"
                                :before-upload="beforeUploadVideo"
                                :show-file-list="false"
                              >
                                <img
                                  @click="replaceLecture(index)"
                                  class="replace"
                                  src="../../../assets/image/phrase3/replace.png"
                                />
                              </el-upload>
                            </div>
                            <img
                              @click="deleteLecture(index)"
                              class="delete"
                              src="../../../assets/image/phrase3/close.png"
                            />
                          </li>
                          <div
                            style="color: red; position: absolute; top: 22px"
                            v-show="
                              needShowAuditMsg &&
                              formData.courseCustomChapterModels[0]
                                .courseCustomLectureModelList[index]
                                .contentCheck
                            "
                            class="error-video"
                          >
                            <span>{{
                              formData.courseCustomChapterModels[0]
                                .courseCustomLectureModelList[index]
                                .contentCheck
                            }}</span>
                          </div>
                        </ul>
                        <div class="video-name">
                          <span class="title">
                            <span style="color: red">*</span>
                            <span class="video-title"
                              >视频名称{{ index + 1 }}</span
                            >
                          </span>
                          <el-input
                            size="small"
                            v-model="lecture.name"
                            placeholder="请输入课程名称"
                            style="width: 260px"
                            maxlength="25"
                            :disabled="disabled"
                          ></el-input>
                          <span class="word-num">
                            {{
                              (lecture.name || '').replace(/\s+/g, '').length
                            }}/25
                          </span>
                        </div>
                        <div
                          v-show="
                            lecture.name &&
                            needShowAuditMsg &&
                            formData.courseCustomChapterModels[0]
                              .courseCustomLectureModelList[index].nameCheck
                          "
                          class="error-video"
                        >
                          <span>{{
                            formData.courseCustomChapterModels[0]
                              .courseCustomLectureModelList[index].nameCheck
                          }}</span>
                        </div>
                        <div v-show="!lecture.name" class="error-video">
                          请输入视频名称
                        </div>
                      </li>
                    </ul>
                    <div
                      style="color: red; position: absolute; top: 60px"
                      v-if="
                        noLecture &&
                        !formData.courseCustomChapterModels[0]
                          .courseCustomLectureModelList.length
                      "
                    >
                      请上传课程视频
                    </div>
                    <div
                      v-show="needShowUploadProcess"
                      style="
                        position: absolute;
                        top: 10px;
                        left: 120px;
                        display: flex;
                      "
                    >
                      <div style="flex: 1; width: 358px">
                        <span
                          class="upload-process"
                          :style="{
                            width: (uploadProgress / 100) * 300 + 'px',
                          }"
                        ></span>
                      </div>
                      <!-- <img @click="cancleUpload" style="widht:16px;height:16px;margin-top:3px;margin-left:8px;" src="../../../assets/image/phrase3/close.png" /> -->
                    </div>
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </div>

          <div class="other-content valid-msg" v-show="isShowOtherContent">
            <div class="tips">
              注：以下信息为非必填项，您也可以根据实际情况修改
            </div>
            <div class="basic-item-icon">
              <!-- <span class="require">*</span> -->
              <el-form-item label="课程封面：">
                <el-upload
                  v-model="formData.courseIntroImage"
                  class="bg-uploader"
                  action="#"
                  accept="image/*"
                  :show-file-list="false"
                  :before-upload="beforeUploadForCourse"
                  :disabled="disabled"
                >
                  <div class="bg-img-wrapper">
                    <img
                      v-if="formData.courseIntroImage"
                      @mouseover.stop="imgMouseOver = true"
                      :src="getOSSDomain(formData.courseIntroImage)"
                      class="bg-img"
                    />
                    <img
                      v-if="!formData.courseIntroImage"
                      class="bg-img"
                      src="../../../assets/image/small.png"
                    />
                  </div>
                </el-upload>
                <div class="limit-text">尺寸：750*420，只支持jpg、jpeg格式</div>
                <!-- <div style="color:red;position:absolute;top:104px;"  class="error">
                        课程难度课程难度
                      </div> -->
                <div
                  style="color: red; position: absolute; top: 102px"
                  v-show="needShowAuditMsg && formData.courseIntroImageCheck"
                  class="error"
                >
                  <span>{{ formData.courseIntroImageCheck }}</span>
                </div>
              </el-form-item>
              <!-- <p class="upload-message" v-if="uploadImgMessage">请选择列表图片</p> -->
            </div>

            <el-form-item label="课程难度：">
              <el-radio-group v-model="formData.difficultyLevel">
                <el-radio :label="1">初级</el-radio>
                <el-radio :label="2">中级</el-radio>
                <el-radio :label="3">高级</el-radio>
              </el-radio-group>
            </el-form-item>
            <div v-if="formData.courseCustomDoctorModels[0]">
              <el-form-item label="讲师名称：" class="valid-msg">
                <el-col :span="18">
                  <el-autocomplete
                    size="small"
                    style="width: 360px"
                    class="inline-input"
                    v-model="
                      formData.courseCustomDoctorModels[0].courseDoctorName
                    "
                    placeholder="请输入内容"
                    :fetch-suggestions="querySearch"
                    :trigger-on-focus="true"
                    @select="handleSelect"
                    >   
                  </el-autocomplete>
                  <span class="word-num"
                    >{{
                      (
                        (formData.courseCustomDoctorModels[0] &&
                          formData.courseCustomDoctorModels[0]
                            .courseDoctorName) ||
                        ''
                      ).replace(/\s+/g, '').length
                    }}/25</span
                  >
                  <div
                    v-show="
                      needShowAuditMsg &&
                      formData.courseCustomDoctorModels[0].courseDoctorNameCheck
                    "
                    class="error"
                  >
                    <span>{{
                      formData.courseCustomDoctorModels[0].courseDoctorNameCheck
                    }}</span>
                    <span
                      v-show="formData.checkStatus == 0"
                      class="cancle"
                      @click="
                        cancleAudit(
                          formData.courseCustomDoctorModels[0],
                          'courseDoctorNameCheck'
                        )
                      "
                      >X</span
                    >
                  </div>
                </el-col>
              </el-form-item>

              <div class="basic-item-icon">
                <el-form-item label="讲师头像：">
                  <el-upload
                    v-model="
                      formData.courseCustomDoctorModels[0].courseDoctorAvatarUrl
                    "
                    class="bg-uploader"
                    action="#"
                    accept="image/*"
                    :show-file-list="false"
                    :before-upload="beforeUploadForLecture"
                    :disabled="disabled"
                  >
                    <div class="bg-img-wrapper">
                      <img
                        v-if="
                          (formData.courseCustomDoctorModels &&
                            formData.courseCustomDoctorModels[0]
                              .courseDoctorAvatarUrl) ||
                          ''
                        "
                        @mouseover.stop="imgMouseOver = true"
                        :src="
                          getOSSDomain(
                            formData.courseCustomDoctorModels[0]
                              .courseDoctorAvatarUrl
                          )
                        "
                        class="bg-img-doctor"
                      />
                      <img
                        v-if="
                          !(
                            (formData.courseCustomDoctorModels &&
                              formData.courseCustomDoctorModels[0]
                                .courseDoctorAvatarUrl) ||
                            ''
                          )
                        "
                        class="bg-img-doctor"
                        src="../../../assets/image/small.png"
                      />
                    </div>
                  </el-upload>
                  <div class="limit-text" style="top: 80px">
                    尺寸：88*88，只支持jpg、jpeg格式
                  </div>
                  <!-- <div class="error" style="position:absolute;top: 94px;">
                        所属机构所属机构：所属机构：
                      </div> -->
                  <div
                    v-show="
                      needShowAuditMsg &&
                      formData.courseCustomDoctorModels[0]
                        .courseDoctorAvatarUrlCheck
                    "
                    class="error"
                    style="position: absolute; top: 98px"
                  >
                    <span>{{
                      formData.courseCustomDoctorModels[0]
                        .courseDoctorAvatarUrlCheck
                    }}</span>
                    <span
                      v-show="formData.checkStatus == 0"
                      class="cancle"
                      @click="
                        cancleAudit(
                          formData.courseCustomDoctorModels[0],
                          'courseDoctorAvatarUrlCheck'
                        )
                      "
                      >X</span
                    >
                  </div>
                </el-form-item>
                <!-- <p class="upload-message" v-if="uploadImgMessage">请选择列表图片</p> -->
              </div>
              <el-form-item label="所属机构：">
                <el-col :span="18">
                  <el-input
                    size="small"
                    v-model="
                      formData.courseCustomDoctorModels[0].courseDoctorHospital
                    "
                    placeholder="请输入所属机构"
                    style="width: 360px"
                    maxlength="25"
                    :disabled="disabled"
                  ></el-input>
                  <span class="word-num"
                    >{{
                      (
                        (formData.courseCustomDoctorModels &&
                          formData.courseCustomDoctorModels[0]
                            .courseDoctorHospital) ||
                        ''
                      ).replace(/\s+/g, '').length
                    }}/25</span
                  >
                  <!-- <div class="error">
                        所属机构所属机构：所属机构：
                      </div>                 -->
                  <div
                    v-show="
                      needShowAuditMsg &&
                      formData.courseCustomDoctorModels[0]
                        .courseDoctorHospitalCheck
                    "
                    class="error"
                  >
                    <span>{{
                      formData.courseCustomDoctorModels[0]
                        .courseDoctorHospitalCheck
                    }}</span>
                  </div>
                </el-col>
              </el-form-item>
            </div>

            <el-form-item label="课程简介：">
              <el-col :span="18">
                <el-input
                  size="small"
                  type="textarea"
                  maxlength="200"
                  :autosize="{ minRows: 5 }"
                  placeholder="请输入课程简介"
                  v-model="formData.courseIntro"
                  style="width: 90%"
                ></el-input>
                <span class="word-num"
                  >{{
                    (formData.courseIntro || '').replace(/\s+/g, '').length
                  }}/200</span
                >
                <!-- <div class="error-area">
                        所属机构所属机构：所属机构：
                      </div>                  -->
                <div
                  v-show="needShowAuditMsg && formData.courseIntroCheck"
                  class="error-area"
                >
                  <span>{{ formData.courseIntroCheck }}</span>
                </div>
              </el-col>
            </el-form-item>
          </div>

          <!-- 更多信息 -->
          <div class="separator-line">
            <span class="line-left"></span>
            <div @click="toggleOtherContent" class="center">
              <span>{{
                isShowOtherContent ? '收起更多信息' : '展开更多信息'
              }}</span>
              <img
                v-show="isShowOtherContent"
                src="../../../assets/image/phrase3/arrow-up.png"
              />
              <img
                v-show="!isShowOtherContent"
                src="../../../assets/image/phrase3/arrow-down.png"
              />
            </div>
            <span class="line-right"></span>
          </div>
        </el-form>
      </div>
      <div v-show="step == 2" class="course-content-step2">
        <img
          class="success-img"
          src="../../../assets/image/phrase3/icon-audit-success.png"
        />
        <span class="tips-1"
          >您上传的课程已成功提交，预计在3-5个工作日内完成审核</span
        >
        <span class="tips-2"
          >审核通过后，您才可以选择课程完成项目配置。如有任何疑问可联系云鹊医400-006-5252</span
        >
        <el-button
          class="back-btn"
          type="primary"
          :icon="ElIconBack"
          @click="backToOrgCourse"
          >返回机构课程</el-button
        >
      </div>
      <template v-slot:footer>
        <div v-show="step == 1" class="dialog-footer">
          <el-button @click="dialogObj.visible = true">取 消</el-button>
          <el-button type="primary" @click="submitForm('formDataRef')"
            >提交审核</el-button
          >
        </div>
      </template>
    </el-dialog>
    <!-- // fetch-suggestions 是一个返回输入建议的方法属性 -->
    <!-- //  false = >输入后匹配输入建议  true => 激活即列出输入建议 -->
    <!-- // 点击选中建议项时触发  handleSelect -->

    <DialogComponet
      :dialogObj="dialogObj"
      @hide="hideCancleTips"
      @confirm="dialogObj.visible = false"
    ></DialogComponet>
    <PreviewVideo
      :dialogVisible="isPreviewVideo"
      :videoUrl="videoUrl"
      @close="isPreviewVideo = false"
    ></PreviewVideo>
    <el-dialog
      class="dialog-title-border-old"
      title="图片裁剪"
      v-model="showCropper"
      :width="currentOption.cropDialogWidth"
      center
    >
      <template v-slot:title>
        <div style="text-align: left">
          <span style="font-weight: 700">图片裁剪</span>
        </div>
      </template>
      <div v-if="showCropper" style="margin-bottom: 20px">
        <CropperImg
          :cropOption="currentOption"
          @getCropImg="getCropImg(arguments)"
          :originImg="slide2.oriUrl"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Back as ElIconBack } from '@element-plus/icons'
import { $on, $off, $once, $emit } from '../../../../utils/gogocodeTransfer'
import PreviewVideo from '@/components/education/custom-resource/preview-video'
import DialogComponet from '@/components/education/template/dialog'
import CropperImg from '@/components/common/cropper-img.vue'
import { doUpload, getFilePath } from '@/utils/qiniu-util'
import { openLoading, closeLoading, getQiniuToken1 } from '@/utils/utils'
import { isEmptyUtils, getOSSImgUrl } from '@/utils/index'
import { mapActions } from 'vuex'
import { ossUpload, getFilePathForOSS } from '@/utils/oss/ossUtil'
let vm = null
export default {
  data() {
    return {
      slide2: {
        oriUrl: '', // 原图
      },
      showCropper: false,
      currentOption: {
        offset_x: 120,
        offset_y: 185,
        width: 750,
        height: 420,
        cvWidth: 1000,
        cvHeight: 800,
        uploadType: 1,
        cropDialogWidth: '900px',
      },
      cropOption: {
        offset_x: 120,
        offset_y: 185,
        width: 750,
        height: 420,
        cvWidth: 1000,
        cvHeight: 800,
        uploadType: 1,
        cropDialogWidth: '900px',
      },
      cropOption2: {
        offset_x: 80,
        offset_y: 60,
        width: 88,
        height: 88,
        cvWidth: 249,
        cvHeight: 200,
        uploadType: 2,
        cropDialogWidth: '500px',
      },
      isReplaceUpload: false,
      replaceLectureIndex: 0,
      step: 1,
      needCheckField: false,
      needShowAuditMsg: false,
      needShowUploadProcess: false,
      disabled: false,
      formDataBase: {
        checkStatus: 0,
        courseCustomChapterModels: [
          {
            courseCustomLectureModelList: [],
            id: null,
            name: '视频课程',
          },
        ],
        courseCustomDoctorModels: [
          {
            courseDoctorAvatarUrl: '/h5/images/cme/doctor-header.png',
            courseDoctorAvatarUrlCheck: '',
            courseDoctorHospital: '',
            courseDoctorHospitalCheck: '',
            courseDoctorName: '',
            courseDoctorNameCheck: '',
            id: null,
          },
        ],
        courseId: null,
        courseIntro: '',
        courseIntroCheck: '',
        courseIntroImage: '/h5/images/cme/project-banner.png',
        courseIntroImageCheck: '',
        courseName: '',
        courseNameCheck: '',
        deleteCustomLectureIds: [],
        difficultyLevel: 1,
        shareType: 1,
        subjectIdList: [],
      },
      formData: {
        checkStatus: 0,
        courseCustomChapterModels: [
          {
            courseCustomLectureModelList: [],
            id: null,
            name: '视频课程',
          },
        ],
        courseCustomDoctorModels: [
          {
            courseDoctorAvatarUrl: '/h5/images/cme/doctor-header.png',
            courseDoctorAvatarUrlCheck: '',
            courseDoctorHospital: '',
            courseDoctorHospitalCheck: '',
            courseDoctorName: '',
            courseDoctorNameCheck: '',
            id: null,
          },
        ],
        courseId: null,
        courseIntro: '',
        courseIntroCheck: '',
        courseIntroImage: '/h5/images/cme/project-banner.png',
        courseIntroImageCheck: '',
        courseName: '',
        courseNameCheck: '',
        deleteCustomLectureIds: [],
        difficultyLevel: 1,
        shareType: 1,
        subjectIdList: [],
      },
      // uploadImgMessage: false,
      imgMouseOver: false,
      labelOptions: [],
      isShowOtherContent: false,
      fileList: [],
      doctorNameList: [
        // { courseDoctorName: "333", show: true, seleted: false },
      ],
      isShowDoctorList: false,
      isPreviewVideo: false,
      videoUrl: '',
      orgCourseInfo: {
        defaultDoctor: {
          courseDoctorAvatarUrl: '/h5/images/cme/project-banner.png',
          courseDoctorAvatarUrlCheck: '',
          courseDoctorHospital: '',
          courseDoctorHospitalCheck: '',
          courseDoctorName: '',
          courseDoctorNameCheck: '',
          id: null,
        },
        doctorModelList: [
          {
            courseDoctorAvatarUrl: '/h5/images/cme/doctor-header.png',
            courseDoctorAvatarUrlCheck: '',
            courseDoctorHospital: '',
            courseDoctorHospitalCheck: '',
            courseDoctorName: '',
            courseDoctorNameCheck: '',
            id: null,
          },
        ],
        limitModel: {
          maxLimitOneVideoSize: 2147483648,
          maxLimitVideoCount: 100,
          maxStorageSpace: 5368709120,
          usedStorageSpace: 1021842989,
        },
      },
      uploadProgress: 0,
      dialogObj: {
        visible: false,
        title: '确定取消吗？',
        message: '取消后，将不保存该页面已填写的内容',
        tip: '',
        confirmMsg: '取 消',
        hideMsg: '确 定',
      },
      // 没有上传视频
      noLecture: true,
      // 没有课程名称
      noCouseName: true,
      // 没有选择分类
      noLabel: true,
      // 1: 封面图片; 2: 讲师头像
      currentUploadType: 1,
      ElIconBack,
    }
  },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    courseId: {
      type: String | Number,
      default: 0,
    },
  },
  computed: {},
  watch: {
    dialogVisible(isVisible) {
      this.formData = JSON.parse(JSON.stringify(this.formDataBase))
      this.isShowOtherContent = false
      if (isVisible) {
        if (this.courseId == 0) {
          this.initAdd(this.courseId)
        } else {
          this.isShowOtherContent = true
          this.initModify(this.courseId)
        }
      }
      this.isReplaceUpload = false
      this.noLecture = false
      this.noCouseName = false
      this.noLabel = false
    },
  },
  components: {
    PreviewVideo,
    DialogComponet,
    CropperImg,
  },
  created() {
    vm = this
  },
  mounted() {
    this.getLabelList()
  },
  methods: {
    ...mapActions(['setKind']),

    // 重新上传（替换视频）
    replaceLecture(index) {
      this.isReplaceUpload = true
      this.replaceLectureIndex = index
    },

    // 获取裁剪的图片数据
    getCropImg(argument) {
      this.showCropper = false
      this.cropData = argument[1]
      vm.doUploadOSS(argument[2], this.currentUploadType) //封面图片
      argument[3] && argument[3].destroy()
    },
    //
    // closeCropper() {
    //   this.showCropper = false;
    // },

    // 取消上传
    cancleUpload() {
      console.log('in cancleUpload')
      if (window.QNSubscription) {
        // console.log('QNSubscription', QNSubscription);
        // window.QNSubscription.unsubscribe();
        // window.QNSubscription = null;
      }
      // this.$refs.uploadFileCom.abort();
    },

    querySearch(queryString, cb) {
      // this.doctorNameList;
      let doctorNameList = JSON.parse(JSON.stringify(this.doctorNameList))
      if (!queryString) {
        cb(doctorNameList)
        return
      }

      let backList = []
      doctorNameList.forEach((item) => {
        if (item.courseDoctorName.indexOf(queryString) >= 0) {
          backList.push(item)
        }
      })
      cb(backList)
    },

    // 选择其中一个
    handleSelect(selDoctor) {
      this.formData.courseCustomDoctorModels[0] = selDoctor
    },

    // 创建课程页面的初始信息
    initOrgCourseInfo() {
      vm.GET('contents/course/custom/info/init', { setEntry: true }).then(
        (res) => {
          if (res.code == '000000') {
            this.orgCourseInfo = res.data
            this.formData.courseCustomDoctorModels[0] =
              this.orgCourseInfo.defaultDoctor
            this.formData.courseCustomDoctorModels[0].courseDoctorAvatarUrl =
              this.orgCourseInfo.defaultDoctor.courseDoctorAvatarUrl ||
              '/h5/images/cme/doctor-header.png'
            this.doctorNameList = this.convertDNameToSelectOpt(
              this.orgCourseInfo.doctorModelList
            )
            ;+this.courseId && this.getCourseInfoById(this.courseId)
          }
        }
      )
    },

    // 将医生名称进行处理
    convertDNameToSelectOpt(doctorModelList) {
      doctorModelList.forEach((item) => {
        item.value = item.courseDoctorName
        item.show = true
        item.seleted = false
      })
      return doctorModelList
    },

    // 添加时初始化
    initAdd() {
      this.step = 1
      this.needShowAuditMsg = false
      this.initOrgCourseInfo()
    },

    // 编辑时初始化
    initModify() {
      this.step = 1
      this.needShowAuditMsg = true
      this.initOrgCourseInfo()
    },

    // 创建课程页面的初始信息
    getCourseInfoById(courseId) {
      vm.GET(`contents/course/custom/info/${courseId}`).then((res) => {
        if (res.code == '000000') {
          this.formData = res.data
        }
      })
    },

    // 关闭当前弹框
    close() {
      $emit(this, 'close')
    },

    // 获取学科列表
    getLabelList() {
      let req = {}
      this.GET('aggregate/content/labelList', req).then((res) => {
        if (res.code == '000000') {
          this.convertLabelList(res.data)
        }
      })
    },

    // 将所有子分类中的“全部”去掉
    convertLabelList(labelList) {
      let newLabelList = []
      labelList.forEach((item) => {
        item.subList = item.subList.slice(1)
      })
      this.labelOptions = labelList
    },

    // 上传视频（mp4）
    beforeUploadVideo(file) {
      // this.$message({
      //   showClose: false,
      //   message: '您上传的文件大小已超限制，无法继续上传。如有疑问可拨打云鹊医电话咨询400-920-7788',
      //   type: 'error',
      //   duration: 10000
      // });
      // return;
      console.log(file)
      const isMP4 = file.type === 'video/mp4'
      const isGt =
        file.size > this.orgCourseInfo.limitModel.maxLimitOneVideoSize
      const isGtMaxNum =
        this.formData.courseCustomChapterModels[0].courseCustomLectureModelList
          .length >= 100
      const usedGtMaxStore =
        this.orgCourseInfo.limitModel.usedStorageSpace + file.size >
        this.orgCourseInfo.limitModel.maxStorageSpace
      if (isGtMaxNum || !isMP4) {
        this.$message.error('视频不符合规范，请根据规范上传视频')
        return
      }
      if (usedGtMaxStore || isGt) {
        this.$message({
          showClose: true,
          message:
            '您上传的文件大小已超限制，无法上传。如有疑问可拨打云鹊医电话：400-920-7788',
          type: 'error',
          duration: 10000,
        })
        return
      }
      // 直接上传
      this.needShowUploadProcess = true
      vm.uploadProgress = 0
      doUpload(
        vm,
        file,
        getFilePath(file, null),
        'preview4',
        'progress',
        ''
      ).then(function (path) {
        console.log(path)
        let cName = path.name
        cName = cName.substr(0, cName.lastIndexOf('.'))
        cName = cName.substring(0, 21)
        let uploadResourceParam = {
          formatType: path.ext,
          name: cName + path.ext, //path.name,
          qCloudUrl: path.fullPath,
          size: path.size,
          fileType: 1,
          status: 'success',
          uid: new Date().getTime(),
        }
        vm.needShowUploadProcess = false
        vm.uploadProgress = 0
        vm.insertResourceAction(uploadResourceParam)
      })
    },

    // 上传资源（视频）后，生存对应的节
    insertResourceAction(uploadResourceParam) {
      this.POST('contents/course/custom/info/insertResource', [
        uploadResourceParam,
      ]).then((res) => {
        if (res.code == '000000') {
          let cName = res.data.resourceModelList[0].name
          cName = cName.substr(0, cName.lastIndexOf('.'))
          let lectureObjId = null
          if (this.isReplaceUpload) {
            lectureObjId =
              this.formData.courseCustomChapterModels[0]
                .courseCustomLectureModelList[this.replaceLectureIndex].id
            console.log('in isReplaceUpload', lectureObjId)
          }

          let lectureObj = {
            id: lectureObjId,
            name: cName,
            nameCheck: '',
            contentCheck: '',
            resourceModel: {},
          }
          this.orgCourseInfo.limitModel = res.data.limitModel
          lectureObj.resourceModel = res.data && res.data.resourceModelList[0]
          if (this.isReplaceUpload) {
            this.formData.courseCustomChapterModels[0].courseCustomLectureModelList.splice(
              this.replaceLectureIndex,
              1,
              lectureObj
            )
          } else {
            this.formData.courseCustomChapterModels[0].courseCustomLectureModelList.push(
              lectureObj
            )
          }

          // 重置是否替换视频的参数
          this.isReplaceUpload = false
          this.replaceLectureIndex = 0
        }
      })
    },

    // 展开/收起 更多信息
    toggleOtherContent() {
      this.isShowOtherContent = !this.isShowOtherContent
    },

    // 表单校验
    submitForm(formName) {
      this.needShowAuditMsg = false
      this.noCouseName = false
      this.noLecture = false
      this.noLabel = false
      let hasLecture =
        this.formData.courseCustomChapterModels[0].courseCustomLectureModelList
          .length > 0
      let flag = false
      let lectureList =
        this.formData.courseCustomChapterModels[0].courseCustomLectureModelList
      for (let i = 0; i < lectureList.length; i++) {
        if (!lectureList[i].name) {
          flag = true
          break
        }
      }
      console.log('flag', flag)
      if (!hasLecture) {
        this.noLecture = true
      }
      if (!this.formData.courseName) {
        this.noCouseName = true
      }
      if (!this.formData.subjectIdList.length) {
        this.noLabel = true
      }
      if (this.noCouseName || this.noLabel || this.noLecture || flag) {
        return
      }

      this.insertOrUpdate()
    },

    // 添加或修改课程（kind = 3）
    insertOrUpdate() {
      let formData = JSON.parse(JSON.stringify(this.formData))
      if (!formData.courseCustomDoctorModels[0]) {
        formData.courseCustomDoctorModels = []
      } else if (
        !formData.courseCustomDoctorModels[0].courseDoctorName &&
        !formData.courseCustomDoctorModels[0].courseDoctorHospital
      ) {
        formData.courseCustomDoctorModels = []
      }
      this.POST('contents/course/custom/info/insertOrUpdate', formData).then(
        (res) => {
          if (res.code == '000000') {
            this.step = 2
          } else {
            this.$message.error(res.message)
          }
        }
      )
    },

    // 返回到课程选择页面（kind = 3）
    backToOrgCourse() {
      console.log('backToOrgCourse')
      this.close()
      this.setKind(3)
    },

    // 关闭（“取消”按钮弹出来的）弹框
    hideCancleTips() {
      this.dialogObj.visible = false
      this.close()
    },

    // 预览视频
    previewVideoAction(lecture) {
      this.videoUrl = lecture.resourceModel.filePath
      this.isPreviewVideo = true
    },

    // 删除本节视频
    deleteLecture(index) {
      let lectureId =
        this.formData.courseCustomChapterModels[0].courseCustomLectureModelList[
          index
        ].id
      if (lectureId) {
        this.formData.deleteCustomLectureIds.push(lectureId)
      }
      this.formData.courseCustomChapterModels[0].courseCustomLectureModelList.splice(
        index,
        1
      )
    },

    // 上传课程封面图片
    beforeUploadForCourse(file) {
      const isJPG = file.type === 'image/jpeg'
      if (!isJPG) {
        this.$message.error('只支持jpg、jpeg格式')
        return
      }

      vm.currentUploadType = 1
      vm.currentOption = vm.cropOption
      var _img = new FileReader()
      _img.readAsDataURL(file)
      _img.onload = function (theFile) {
        let image = new Image()
        image.src = theFile.target.result
        vm.slide2.oriUrl = theFile.target.result
        image.onload = function () {
          let _this = this
          // 图片大小不正常，则进行裁剪
          if (_this.width != 750 || _this.height != 420) {
            vm.showCropper = true
            // 图片大小正常，则直接上传
          } else {
            vm.doUploadOSS(file, 1) //封面图片
          }
        }
      }
    },

    // 上传讲师图片
    beforeUploadForLecture(file) {
      // const isLt50kb = file.size / 1024 < 50;
      const isJPG = file.type === 'image/jpeg'
      if (!isJPG) {
        this.$message.error('只支持jpg、jpeg格式')
        return
      }
      vm.currentUploadType = 2
      vm.currentOption = vm.cropOption2
      var _img = new FileReader()
      _img.readAsDataURL(file)
      _img.onload = function (theFile) {
        let image = new Image()
        image.src = theFile.target.result
        vm.slide2.oriUrl = theFile.target.result
        image.onload = function () {
          let _this = this
          if (_this.width != 88 || _this.height != 88) {
            vm.showCropper = true
            // vm.$message.info("上传图片尺寸大小不合适，请重新上传")
          } else {
            vm.doUploadOSS(file, 2) //封面图片
          }
        }
      }
    },

    getOSSDomain(url) {
      return getOSSImgUrl(url)
    },

    // （调用OSS API）开始上传
    doUploadOSS(file, index) {
      let self = this
      //上传 指定文件名
      ossUpload(self, file, getFilePathForOSS(file), null, null, null).then(
        function (path) {
          console.log(path)
          let list = [{}]
          // list[0].name = file.name;
          // list[0].url = localStorage.getItem("resource_url") + path;
          // getOSSImgUrl(path)
          if (index === 1) {
            self.formData.courseIntroImage = path
          } else if (index === 2) {
            self.formData.courseCustomDoctorModels[0].courseDoctorAvatarUrl =
              path
          }
          self.$message.success('上传成功')
        }
      )
      return false
    },
  },
  emits: ['close'],
}
</script>

<style lang="scss" scoped>
.edit-course-wrapper {
  .course-content {
    // color: red;
    .basic-item-icon {
      position: relative;
      margin-top: 20px;
      .require {
        position: absolute;
        left: 40px;
        top: 11px;
        color: #f56c6c;
      }
      .upload-message {
        position: absolute;
        left: 160px;
        top: 105px;
        font-size: 12px;
        color: #f56c6c;
      }
      .img-delete {
        position: absolute;
        left: 0px;
        top: 0px;
        width: 84px;
        height: 100px;
        background: #000;
        opacity: 0.7;
        z-index: 999;
        i {
          color: #fff;
          margin-top: 39px;
          margin-left: 0px;
        }
      }
      .upload-tips {
        width: 100%;
        position: relative;
        top: -10px;
        font-size: 12px;
        color: #979899;
        // display: inline-block;
      }
      .custom-list {
        position: relative;
        left: 0px;
        // left: -78px;
        width: 580px;
        display: flex;
        flex-direction: column;
        border-radius: 3px;
        border: 1px solid rgba(228, 231, 237, 1);
        padding: 20px;
        padding-top: 5px;
        font-size: 14px;
        & > li {
          margin: 10px 0;
        }
        .video-wrappe {
          &:nth-child(n + 2)::before {
            position: absolute;
            top: -4px;
            display: block;
            content: '';
            height: 0;
            width: 100%;
            border-top: 1px dashed #e4e7ed;
          }
          .video {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            align-items: center;
            .title {
              display: inline-block;
              width: 80px;
              text-align: right;
              margin-right: 10px;
            }
            .name {
              cursor: pointer;
              color: #5890dd;
            }
            img {
              width: 12px;
              height: 12px;
            }
            .other-action {
              width: 80px;
              display: flex;
              align-items: center;
              text-align: right;
              justify-content: flex-end;
              .replace {
                position: relative;
                top: 5px;
                margin-right: 20px;
                cursor: pointer;
                width: 16px;
                height: 16px;
              }
              .delete {
                position: relative;
                top: 2px;
                cursor: pointer;
                width: 16px;
                height: 16px;
              }
            }
          }
        }

        .video-name {
          .title {
            display: inline-block;
            width: 80px;
            text-align: right;
            margin-right: 10px;
          }
        }
      }
    }
    .word-num {
      font-size: 12px;
      color: #999;
      padding-top: 5px;
    }
    .bg-uploader {
      img {
        float: left;
      }
      .bg-img-wrapper {
        .bg-img {
          display: block;
          width: 160px;
          height: 90px;
        }
        .bg-img-doctor {
          display: block;
          width: 88px;
          height: 88px;
        }
      }
      .bg-video {
        float: left;
        width: 84px;
        height: 100px;
      }
    }
    .limit-text {
      position: absolute;
      top: 86px;
      left: 0px;
      font-size: 12px;
      color: #979899;
    }
    .separator-line {
      width: 100%;
      display: flex;
      flex-direction: row;
      align-content: center;
      align-items: center;
      justify-content: space-between;
      .center {
        cursor: pointer;
        width: 130px;
        color: #666666;
        img {
          width: 12px;
        }
      }
      .line-left {
        flex: 1;
        margin-left: 20px;
        border-bottom: 1px dashed #e4e7ed;
      }
      .line-right {
        flex: 1;
        margin-right: 6px;
        border-bottom: 1px dashed #e4e7ed;
      }
    }
    .tips {
      // margin-left: -20px;
      // width: 810px;
      // width: 100%;
      height: 32px;
      line-height: 32px;
      margin-left: 20px;
      margin-right: 5px;
      padding-left: 12px;
      background: rgba(254, 250, 245, 1);
      border-radius: 3px;
      color: #e6a23c;
    }
    .valid-msg {
      position: relative;
      .error {
        width: 370px;
        position: absolute;
        display: flex;
        justify-content: space-between;
        top: 29px;
        font-size: 13px;
        color: #ed3131;
        .text {
          flex: 1;
        }
        .cancle {
          cursor: pointer;
          width: 20px;
        }
      }
      .error-area {
        position: absolute;
        bottom: -32px;
        font-size: 13px;
        color: #ed3131;
        .cancle {
          width: 20px;
          margin-left: 20px;
          cursor: pointer;
        }
      }
      .error-video {
        position: absolute;
        top: 74px;
        left: 93px;
        font-size: 13px;
        color: #ed3131;
        .cancle {
          width: 20px;
          margin-left: 20px;
          cursor: pointer;
        }
      }
      .edit-wrapper {
        color: #449284;
        .edit-img {
          position: relative;
          top: 2px;
          width: 12px;
          margin: 0 2px 0 4px;
        }
      }
      .doctor-select-list {
        width: 200px;
        // max-height: 100px;
        position: absolute;
        z-index: 100;
        background: #fff;
        box-shadow: 0 0 6px rgba(0, 0, 0, 0.3);
        -webkit-box-shadow: 0 0 6px rgba(0, 0, 0, 0.3);

        // margin: 10px;
        li {
          padding-left: 20px;
          cursor: pointer;
          &:hover {
            background: #f4f7fd;
          }
          &.doctor-selected {
            background: #f4f7fd;
          }
        }
      }
    }
    .upload-process {
      margin: 10px 0 10px 10px;
      display: block;
      // width: 310px;
      height: 4px;
      background: #449284;
      border-radius: 2px;
    }
    .upload-video.disabled {
      .el-button--primary {
        color: #bcbec2 !important;
        background-color: #f4f4f5 !important;
        border-color: #e9e9eb !important;
        cursor: not-allowed !important;
      }
      // color: red;
    }
  }
  .course-content-step2 {
    display: flex;
    flex-direction: column;
    text-align: center;
    align-items: center;
    .success-img {
      margin-top: 80px;
      width: 60px;
      height: 60px;
    }
    .back-btn {
      margin-bottom: 70px;
    }
    .tips-1 {
      margin-top: 30px;
      font-size: 18px;
      color: #303133;
    }
    .tips-2 {
      margin-top: 4px;
      margin-bottom: 40px;
      font-size: 14px;
      color: #999999;
    }
  }
}
</style>
