<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible"
    @close="handlereset">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">
      <el-form-item label="章节名" prop="title">
        <el-input v-model="dataForm.title" placeholder="章节名"></el-input>
      </el-form-item>

      <!-- <el-row>
        <el-col :span="12">
          <el-form-item label="类型" prop="type">
            <el-select v-model="dataForm.type" filterable
              placeholder="请选择类型">
              <el-option v-for="item in typeList" :key="item.dictType" :label="item.dictValue" :value="item.dictType">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if='!this.dataForm.id'>
          <el-form-item label="是否同步创建商品" prop="needCreate"  label-width="140px">
            <el-select v-model="dataForm.needCreate" filterable
              placeholder="请选择是否">
              <el-option v-for="item in needCreateList" :key="item.dictType" :label="item.dictValue" :value="item.dictType">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row> -->
      <el-form-item label="插图" prop="imgUrl">
        <el-upload :action="baseUrl + '/oss/fileoss'" list-type="picture-card" :on-preview="handlePictureCardPreview"
          :file-list="fileList" :on-success="handlePicSuccess" :on-remove="handleRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" :append-to-body="true">
          <img width="100%" :src="dataForm.imgUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="dataForm.sort" placeholder="排序"></el-input>
      </el-form-item>
      <el-form-item label="内容" prop="content" class="custom-chapter-height">
        <!-- <el-input v-model="dataForm.content" placeholder="内容"></el-input> -->
        <el-upload class="chapter-avatar-uploader" :action="baseUrl + '/oss/fileoss'" accept=".jpeg,.jpg,.gif,.png" :show-file-list="false" :on-success="contentUploadSuccess" >
        </el-upload>
        <quill-editor v-model="dataForm.content" ref="myQuillEditor" :options="editorOption"
          @blur="onEditorBlur($event)" @focus="onEditorFocus($event)" 
          @ready="onEditorReady($event)" class="chapter_editor">
        </quill-editor>
      </el-form-item>

      <!-- <el-row>
        <el-col :span="12">
          <el-form-item label="作者" prop="authorId">
        <el-select
          v-model="dataForm.authorId"
          multiple
          filterable
          allow-create
          size="small"
          default-first-option
          placeholder="请输入作者姓名">
          <el-option
            v-for="item in authorList"
            :key="item.value + ''"
            :label="item.value"
            :value="item.id + ''">
          </el-option>
        </el-select>
      </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出版社" prop="publisherId">
            <el-select v-model="dataForm.publisherId" multiple filterable allow-create default-first-option
              placeholder="请输入出版社名称">
              <el-option v-for="item in publisherList" :key="item.value + ''" :label="item.value" :value="item.id + ''">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="序言" prop="title">
        <el-input v-model="dataForm.title" placeholder="序言" :rows="3" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="拆分类型" prop="splits">
        <el-radio-group v-model="dataForm.splits">
          <el-radio v-for="item in splitsTypeList" :key="item.dictType" :label="item.dictType"
            :value="item.dictType">{{item.dictValue}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="目录" prop="content">
        <el-input v-model="dataForm.content" placeholder="目录" :rows="5" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="简介" prop="description">
        <el-input v-model="dataForm.description" placeholder="简介" :rows="5" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="图书分类" prop="bookType">
       <el-radio-group v-model="dataForm.bookType">
         <el-radio :label="0">普通</el-radio>
         <el-radio :label="1">中医经典</el-radio>
         <el-radio :label="2">国学经典</el-radio>
       </el-radio-group>
      </el-form-item>
      <el-form-item label="相关古书" prop="relationId">
        <el-select v-model="dataForm.relationId" filterable allow-create default-first-option
          placeholder="请选择古书">
          <el-option :key="0" label="无" :value="0"></el-option>
          <el-option v-for="item in gushuList" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-row>
        <el-form-item label="图书类型" prop="medicaldesBookType">
          <el-checkbox-group v-model="dataForm.medicaldesBookType">
            <el-checkbox v-for="item in medicaldesBookTypeList" :key="item.dictType" :label="item.dictType"
              :value="item.dictType">{{item.dictValue}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-col :span="12">
          <el-form-item label="是否可听">
            <el-switch style="display: block" v-model="dataForm.canListen" active-color="#13ce66"
              inactive-color="#ff4949" active-text="可听" inactive-text="不可听">
            </el-switch>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="是否参与打卡" prop="clockIn" label-width="250">
        <el-radio-group v-model="dataForm.clockIn">
          <el-radio :label="1">参与打卡</el-radio>
          <el-radio :label="2">不参与打卡</el-radio>

        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否参与讲书" prop="teachIn" label-width="250">
        <el-radio-group v-model="dataForm.teachIn">
          <el-radio :label="1">参与</el-radio>
          <el-radio :label="0">不参与</el-radio>

        </el-radio-group>
      </el-form-item>
      <el-form-item label="付费类型" prop="isVip">
        <el-radio-group v-model="dataForm.isVip">
          <el-radio :label="2">付费</el-radio>
          <el-radio :label="1">会免</el-radio>
          <el-radio :label="0">免费</el-radio>

        </el-radio-group>
      </el-form-item>
      <el-form-item label="免费章节数" prop="freeChapterCount" label-width="250">
        <el-input-number v-model="dataForm.freeChapterCount" :min="0" :max="10" label="免费章节数"></el-input-number>
      </el-form-item>
      <el-form-item label="文件上传" prop="novel">
        <el-upload class="upload-demo" :action="baseUrl + '/oss/fileoss'" :on-preview="handlePreview"
          :on-remove="handleRemoveNovel" :before-remove="beforeRemove" :on-success="handleNovelSuccess" multiple
          :limit="3" :on-exceed="handleExceed" :file-list="fileListNovel">
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item> -->
      <!-- <el-form-item label="排序" prop="sort">
        <el-input v-model="dataForm.sort" placeholder="排序"></el-input>
      </el-form-item> -->
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handlereset">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>



<script>
  import global from '../../common/common.vue' //引入共用组间
  import {
      quillEditor
    } from 'vue-quill-editor'
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'
  const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'],        // 加粗，斜体，下划线，删除线
    ['blockquote', 'code-block'],                      //引用，代码块
    [{ 'header': 1 }, { 'header': 2 }],               // 几级标题
    [{ 'list': 'ordered' }, { 'list': 'bullet' }],     // 有序列表，无序列表
    [{ 'script': 'sub' }, { 'script': 'super' }],      // 下角标，上角标
    [{ 'indent': '-1' }, { 'indent': '+1' }],          // 缩进
    [{ 'direction': 'rtl' }],                         // 文字输入方向
    [{ 'size': ['small', false, 'large', 'huge'] }],  // 字体大小
    [{ 'header': [1, 2, 3, 4, 5, 6, false] }],// 标题
    [{ 'color': [] }, { 'background': [] }],          // 颜色选择
    [{ 'font': ['SimSun', 'SimHei', 'Microsoft-YaHei', 'KaiTi', 'FangSong', 'Arial'] }],// 字体
    [{ 'align': [] }], // 居中
    ['clean'],                                       // 清除样式,
    ['link', 'image'],  // 上传图片、上传视频
  ]
  export default {
    data() {
      return {
        baseUrl: global.baseUrl,
        // 富文本编辑器配置
        editorOption: {
          modules: {
            history: {
              delay: 1000,
              maxStack: 50,
              userOnly: false
            },
            toolbar: {
              container: toolbarOptions,
              handlers: {
                image: function (value) {
                  if (value) {
                    // 调用element的图片上传组件
                    document.querySelector('.chapter-avatar-uploader input').click()
                  } else {
                    this.quill.format('image', false)
                  }
                }
              }
            },
          },
          placeholder: '请输入正文',
        },
        visible: false,
        props: {
          dictType: '',
          dictValue: ''
        },
        gushuList:[],
        authorList: [],
        restaurants: [],
        author: '',
        publisherList: [],
        fileList: [],
        fileListNovel: [],
        dialogImageUrl: '',
        dialogVisible: false,
        dataForm: {
          "courseId": 0,
          "catalogueId": 0,
          "title": "",
          "imgUrl": "",
          "content": "",
          "sort": 1,
        },
        splitsTypeList: [],
        dataRule: {


        }
      }
    },
    components: {
      quillEditor
    },
    created() {
    },
    mounted() {
    },
    methods: {
      contentUploadSuccess(res, file) { 
        // console.log(res)
        let quill = this.$refs.myQuillEditor.quill
        // 如果上传成功
        if (res) {
          // 获取光标所在位置
          let length = quill.getSelection().index;
          // 插入图片，res为服务器返回的图片链接地址
          quill.insertEmbed(length, 'image', res.url)
          // 调整光标到最后
          quill.setSelection(length + 1)
        } else {
          // 提示信息，需引入Message
          this.$message.error('图片插入失败！')
        }

      },
      // 失去焦点事件
      onEditorBlur(quill) {
      //  console.log('editor blur!', quill)       
      },
      // 获得焦点事件
      onEditorFocus(quill) {
        //console.log('editor focus!', quill)
      },
      // 准备富文本编辑器
      onEditorReady(quill) {
       // console.log('editor ready!', quill)
      },
      init(row, catalogue_id, courseid) {
        console.log('row21', row)
        this.dataForm =row? JSON.parse(JSON.stringify(row)): {}
        this.dataForm.courseId = courseid?courseid : ''
        this.dataForm.catalogueId = catalogue_id?catalogue_id : ''
        this.visible = true
        if (this.dataForm.imgUrl && this.dataForm.imgUrl != "") {
          var img = {
            name: '',
            url: this.dataForm.imgUrl
          }
          var attr = []
          attr.push(img)
          this.fileList = attr
        }else{
          this.fileList = []
        }
      
      },
      // 表单提交
      dataFormSubmit() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`${!this.dataForm.id ? '/master/course/addCourseCatalogueChapter' : '/master/course/editCourseCatalogueChapter'}`),
              method: 'post',
              data: this.$http.adornData({
                "id": this.dataForm.id || undefined,
                'courseId': this.dataForm.courseId || undefined,
                'catalogueId': this.dataForm.catalogueId || undefined,
                'title': this.dataForm.title,
                "imgUrl": this.dataForm.imgUrl,
                "content": this.dataForm.content, 
                "sort": this.dataForm.sort,
              })
            }).then(({
              data
            }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      handlePicSuccess(res, file) {
        if (res.msg == "success") {
          this.dataForm.imgUrl = res.url;
          this.$message.success("上传成功");
        } else {
          this.$message.error("上传失败");
        }
      },
      handleRemove(file) {
        this.dataForm.imgUrl = '';
      },
      handlePictureCardPreview(file) {
        this.dataForm.imgUrl = file.url;
        this.dialogVisible = true;
      },
      handleDownload(file) {
        console.log(file)
      },
      handlereset() {
        this.fileList = [],
          this.fileListNovel = [],
          this.visible = false
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      handleRemoveNovel(file) {
        this.dataForm.novel = '';
      },
      handleNovelSuccess(file) {
        this.dataForm.novel = file.url
      },
      // querySearch(queryString, cb) {
      //     var restaurants = this.restaurants;
      //     var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      //     // 调用 callback 返回建议列表的数据
      //     console.log(results)
      //     cb(results);
      // },
      // createFilter(queryString) {
      //     return (restaurant) => {
      //       return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      //     };
      // },
      // handleSelect(item) {
      //   this.dataForm.authorId = item.id
      //     console.log(item);
      //   }
    }

  }
</script>
