<template>
  <div class="review-access-wrap">
    <bread-crumb :curmbFirst="curmbFirst" :curmbSecond="curmbSecond"></bread-crumb>
    <div class="edit-course-wrapper dialog-title-border">
      <div class="course-content">
        <el-form
          ref="formDataRef"
          :model="formData"
          :rules="rules"
          label-width="120px"
          class="basic-form"
        >
          <el-form-item label="课程名称：" prop="courseName" 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 class="edit-wrapper"><img class="edit-img" src="../../assets/image/phrase3/icon-pin.png">修改信息</span>
              </span>
              <div class="error"><span>错误信息错误信息错误信息错误信息错误信息错误信息息</span><span class="cancle">X</span></div>
            </el-col>
          </el-form-item>

          <el-form-item label="学科分类：" prop="subjectIdList" class="valid-msg">
            <el-col :span="18">
              <!-- :props="{ expandTrigger: 'hover' }" -->
              <el-cascader
                style="width: 360px"
                v-model="formData.subjectIdList"
                :options="labelOptions"
                :props="{ value: 'id', label: 'name', children: 'subList'}"
                @change="handleChange">
                <!-- <template slot-scope="{ node, data }">
                  <span>{{ data.name }}</span>
                </template>                 -->
              </el-cascader>
            </el-col>
          </el-form-item>


          <el-form-item label="开放范围：" prop="shareType" class="valid-msg">
            <el-radio-group v-model="formData.shareType">
              <el-radio :label="1">机构共享</el-radio>
            </el-radio-group>
          </el-form-item>

          <div class="basic-item-icon">
            <span class="require">*</span>
            <el-form-item label="课程视频：" prop="range">
              <!-- action="https://jsonplaceholder.typicode.com/posts/" -->
                <!-- multiple -->
                <!-- :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove" -->
              <el-upload
                class="upload-demo"
                action="#"
                :before-upload="beforeUploadListPic"
                :limit="3"
                :on-exceed="handleExceed"
                :show-file-list="false"
                >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  <span >只支持MP4格式，课程视频最多上传100个，单文件最大2G</span>
                  <ul class="custom-list">
                    <li v-for="(file, index) in fileList" :key="index">
                      <span>{{file.name}}</span>
                    </li>
                  </ul>                    
                </div>
              </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.courseHeaderImage"
                  class="bg-uploader"
                  action="#"
                  :show-file-list="false"
                  :before-upload="beforeUploadListPic"
                  :disabled="disabled"
                >
                  <div class="bg-img-wrapper">
                    <img v-if="formData.courseHeaderImage" @mouseover.stop="imgMouseOver=true" :src="formData.courseHeaderImage" class="bg-img">
                    <img v-if="!formData.courseHeaderImage" class="bg-img" src="../../assets/image/small.png">
                  </div>                
                </el-upload>
                <div class="limit-text">
                  尺寸：750*420，只支持jpeg格式
                </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>
            <el-form-item label="讲师名称：" class="valid-msg">
              <el-col :span="18">
                <el-input
                  size="small"
                  v-model="formData.courseCustomDocterModel[0].courseDoctorName"
                  placeholder="请输入讲师名称"
                  style="width: 360px"
                  maxlength="25"
                  @focus="isShowDoctorList=true"
                  @input="filterDoctorName"
                  @blur="doctorNameInputBlur"
                  :disabled="disabled"
                ></el-input>
                <ul v-show="isShowDoctorList" class="doctor-select-list">
                  <li 
                    v-for="item in doctorNameList" 
                    :key="item.value" 
                    @click="selectDoctor(item.value)"
                    :class="{'doctor-selected': item.seleted}"
                    >
                    <span v-show="item.show">{{item.value}}</span>
                  </li>
                </ul>
                <span class="word-num">{{(formData.courseCustomDocterModel[0].courseDoctorName).replace(/\s+/g,"").length}}/25</span>
              </el-col>
            </el-form-item>

            <div class="basic-item-icon">
              <el-form-item label="讲师头像：">
                <el-upload
                  v-model="formData.courseCustomDocterModel[0].courseDoctorAvatarUrl"
                  class="bg-uploader"
                  action="#"
                  :show-file-list="false"
                  :before-upload="beforeUploadListPic"
                  :disabled="disabled"
                >
                  <div class="bg-img-wrapper">
                    <img v-if="formData.courseCustomDocterModel[0].courseDoctorAvatarUrl" @mouseover.stop="imgMouseOver=true" :src="formData.courseCustomDocterModel[0].courseDoctorAvatarUrl" class="bg-img-doctor">
                    <img v-if="!formData.courseCustomDocterModel[0].courseDoctorAvatarUrl" class="bg-img-doctor" src="../../assets/image/small.png">
                  </div>                
                </el-upload>
                <div class="limit-text">
                  尺寸：88*88，只支持jpeg格式
                </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.courseCustomDocterModel[0].courseDoctorHospital"
                  placeholder="请输入所属机构"
                  style="width: 360px"
                  maxlength="25"
                  :disabled="disabled"
                ></el-input>
                <span class="word-num">{{(formData.courseCustomDocterModel[0].courseDoctorHospital).replace(/\s+/g,"").length}}/25</span>
              </el-col>
            </el-form-item>            
            <el-form-item label="课程简介：">
              <el-col :span="22">
                <el-input
                  size="small"
                  type="textarea"
                  :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>
              </el-col>
            </el-form-item>
          </div>

          <!-- 更多信息 -->
          <div class="separator-line">
            <span class="line-left"></span>
            <div @click="toggleOtherContent" class="center">
              <span>展开更多信息</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 slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="submitForm('formDataRef')">确 定</el-button>
      </div>
      <!-- <PreviewVideo :dialogVisible="isPreviewVideo" :videoUrl="videoUrl" @close="closeVideo"></PreviewVideo> -->
      <!-- <button @click="previewVideoAction">test video</button> -->
    </div>
  </div>
</template>
<script>
import PreviewVideo from "@/components/education/custom-resource/preview-video";
import PreviewProtocol from "@/components/education/custom-resource/preview-protocol";
import PreviewEditCourse from "@/components/education/custom-resource/edit-course-dialog";
import BreadCrumb from "../../components/breadcrumb.vue";
import { doUpload, getFilePath } from "@/utils/qiniu-util";
import { openLoading, closeLoading, getQiniuToken1 } from "@/utils/utils";
  import * as commonUtil from "../../utils/utils";
let vm = null;
export default {
  data() {
    let checkCourseName = (rule, value, callback) => {
      // 如果有审核的信息，则直接报错
      // if(this.needShowAuditMsg && this.auditMsgMap.name.desc) {
      //   callback(new Error(this.auditMsgMap.name.desc));
      //   return;
      // }
      // if(!this.needShowAuditMsg && !value) {
      //   callback(new Error('请输入课程名称'));
      // } else {
      //   callback();
      // }
    };
    return {
      curmbFirst: "CME",
      curmbSecond: "外部资源管理",      
      needShowAuditMsg: true,
      auditMsgMap: {
        name: {
          desc: '填写的课程名称不对'
        }
      },
      disabled: false,
      formData: {
        checkStatus: 0,
        courseCustomChapterModel: [{
          courseCustomLectureModelList: [
            {
              contentCheck: '',
              id: 0,
              name: '',
              nameCheck: '',
              resourceModel: {
                createdId: 0,
                createdTime: '',
                deleteFlag: 0,
                filePath: '',
                fileType: 0,
                formatType: 0,
                hospitalId: 0,
                id: 0,
                idType: 0,
                lectureId: 0,
                modifiedId: 0,
                modifiedTime: '',
                name: '',
                operateKey: '',
                page: 0,
                resolutionRatio: '',
                size: 0,
                status: 0,
                totalTime: 0,
                type: 0,
                videoType: 0
              }
            }
          ],
          id: 0,
          name: ''
        }],
        courseCustomDocterModel: [
          {
            courseDoctorAvatarUrl: 'https://file.yunqueyi.com/h5/images/cme/doctor-header.png',
            courseDoctorHospital: '',
            courseDoctorHospitalCheck: '',
            courseDoctorName: '',
            courseDoctorNameCheck: '',
            id: 0
          }
        ],
        courseHeaderImage: 'https://file.yunqueyi.com/h5/images/cme/project-banner.png',
        courseId: 0,
        courseIntro: '',
        courseIntroCheck: '',
        courseName: '',
        courseNameCheck: '',
        difficultyLevel: 1,
        shareType: 1,
        subjectIdList: [410, 423]
      },
      uploadImgMessage: false,
      imgMouseOver: false,
      rules: {
        courseName: [
          { required: true, message: "请输入课程名称"},
          { validator: checkCourseName }
        ], 
        subjectIdList: [
          { required: true, message: "请输入课程名称", trigger: "blur"},
        ],
        shareType: [
          { required: true, message: "请选择开放范围", trigger: "blur"},
        ], 
      },
      labelOptions: [],
      isShowOtherContent: false,
      fileList: [
        {name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, 
        {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}
      ],
      projectBanner: 'https://file.yunqueyi.com/h5/images/cme/project-banner.png',
      doctorHeader: 'https://file.yunqueyi.com/h5/images/cme/doctor-header.png',
      doctorNameList: [
        {value: '333', show: true, seleted: false},
        {value: '334', show: true, seleted: false},
        {value: '335', show: true, seleted: false},
        {value: '336', show: true, seleted: false},
      ],
      isShowDoctorList: false,

      isPreviewVideo: false,
      videoUrl: '',

    };
  },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    addOrUpdate: {
      type: String,
      default: 'add'
    }
  },
  computed: {

  },
  watch: {
    dialogVisible(isVisible) {
      if(isVisible) {
        if(this.addOrUpdate == 'add') {
          this.initAdd();
        } else {
          this.initModify();
        }
      }
    }
  },
  components: {
    PreviewVideo,
    PreviewEditCourse,
    BreadCrumb
  },
  created() {
    vm = this;
    this.initAdd();
  },
  mounted() {
    commonUtil.resizeHeight();
    this.getLabelList();
    // setTimeout(() => {
    //   console.log(this.$refs.formDataRef);
    //   this.$refs['formDataRef'].validateField("name");
    // }, 2000);
  },
  methods: {

    // 添加时初始化
    initAdd() {
      console.log('in initAdd');
    },

    initModify() {
      console.log('in initModify');
    },

    // 过滤医生信息
    filterDoctorName(value) {
      this.doctorNameList.forEach( item => {
        if(value) {
          if((item.value + '').indexOf(value) == -1) {
            item.show = false;
          } else {
            item.show = true;
          }
          if(item.value == value) {
            item.seleted = true;
          } else {
            item.seleted = false;
          }
        } else {
          item.show = true;
        }
      })
    },
    
    // 当选择医生的焦点失去时，要反选医生信息
    doctorNameInputBlur() {
      setTimeout(() => {
        this.isShowDoctorList = false;
        this.selectDoctorByName(this.formData.courseCustomDocterModel[0].courseDoctorName);
      }, 200);
    },

    // 根据姓名反选医生信息
    // TODO
    selectDoctorByName(name) {
      
    },

    // 选择其中一个
    selectDoctor(name) {
      console.log(name)
      this.formData.courseCustomDocterModel[0].courseDoctorName = name;
      this.selectDoctorByName(name);
    },

    close() {
      this.$emit('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;
    },

    //上传列表图片
    beforeUploadListPic(file) {
      let fileLimit = {
        width: 230,
        height: 172,
        size: 0.5,
        sizeText: "500K",
        key: "attachmentUrl",
        more: "attachmentMore1",
        show: "uploadImgMessage"
      };
      vm.beforeAvatarUpload(file, fileLimit);
    },

    //上传图片校验
    beforeAvatarUpload(file, fileLimit) {
      console.log();
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < fileLimit.size;
      console.log('isJPG', isJPG, 'isPNG', isPNG, 'isLt2M', isLt2M);
      // if (!isJPG && !isPNG) {
      //   vm.$message.error("图片不符合规范，请根据规范上传图片");
      //   return;
      // }
      // if (!isLt2M) {
      //   vm.$message.error("图片不符合规范，请根据规范上传图片 ");
      //   return;
      // }
      let _img = new FileReader();
      _img.readAsDataURL(file);
      _img.onload = function(theFile) {
        let image = new Image();
        image.src = theFile.target.result;
        image.onload = function() {
          let _vm = this;
          if (
            false
            // true ||
            // _vm.width != fileLimit.width ||
            // _vm.height != fileLimit.height
          ) {
            vm.$message.error("图片不符合规范，请根据规范上传图片");
          } else {
            openLoading(vm);
            doUpload(
              vm,
              file,
              getFilePath(file, null),
              "preview4",
              "progress1",
              1
            ).then(function(path) {
              closeLoading(vm);
              console.log(path);
              if (fileLimit.show == "uploadImgMessage") {
                vm.uploadImgMessage = false;
              } 
              // else if (fileLimit.show == "uploadImgMessage2") {
              //   vm.uploadImgMessage2 = false;
              // }
              vm.formData[fileLimit.key] = path.fullPath;
              vm.formData[fileLimit.more] = {
                attachmentName: path.name,
                attachmentExt: path.ext,
                attachmentSize: path.size
              };
              vm.$message.success("上传成功");
            });
          }
        };
      };
      return isJPG && isLt2M;
    },

    toggleOtherContent() {
      this.isShowOtherContent = !this.isShowOtherContent;
    },

    // 上传文件相关
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 100 个文件，您已经共选择了 ${files.length + fileList.length} 个文件！`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },

    //表单校验
    submitForm(formName) {
      console.log('this.formData', this.formData);
      this.needShowAuditMsg = false;
      let flag = null;
      this.$refs[formName].validate(valid => {
        if (valid) {
          //console.log("success");
          flag = true;
        } else {
          console.log("error submit!!");
          flag = false;
        }
      });
      return flag;
    },
    handleChange(value) {
      console.log(value);
    },
  }
};
</script>
<style scoped lang="scss">
  .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;
          }
        }
      }
      .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, .line-right {
          // display: inline-block;
          // width: 100%;
          flex: 1;
          border-bottom: 1px dashed #E4E7ED;
        }
      }
      .tips {
        width: 100%;
        height:32px;
        line-height: 32px;
        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;
          }
        }
        .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;
            }
          }
        }
      }
    }
  }
</style>
