<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="isLast"
        label-width="120px"
        class="form_item"
      >
        <el-switch
          v-model="dataForm.isAudition"
          active-color="#13ce66"
          :active-value="1"
          :inactive-value="0"
          active-text="是"
          inactive-text="否"
        >
        </el-switch>
      </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-form-item label="思考题" prop="questions" class="custom-chapter-height">
        <!-- <el-input v-model="dataForm.content" placeholder="内容"></el-input> -->        
        <quill-editor
          v-model="dataForm.questions"          
          ref="myQuillEditor1"
          :options="editorOption1"
          class="chapter_editor"

        >
        </quill-editor>
      </el-form-item>
      <!-- <el-form-item  prop="sort" label-width="0">         -->
        <!-- <div v-if="this.dataForm.id"> -->
          <div>
      <div 
        class="flexbox videoBox"
        v-for="(item, index) in video_audio_url"
        :key="index"
        
      >
        <div  style="width:120px">视频/音频ID：</div>
        <div style="width:250px; margin-right:10px; margin-left:10px">
          <el-input
            style=""
            v-model="item.video"
            placeholder="请输入视频/音频ID"
          ></el-input>
        </div>
        <div class="flexbox" style="align-items:center;" >
          <span style="display:inline-block; width:60px">排序：</span>
          <el-input
            style=""
            v-model="item.sort"
            placeholder="排序"
          ></el-input>
        </div>
        <div style="margin-right:10px; height:38px">
          <el-form-item label="加密类型：" prop="type" label-width="100px">
            <el-select
              v-model="item.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>
        </div>

        <el-button @click="delItem(index)" plain type="danger" size="mini">删除</el-button>
      </div>
      <!-- </el-form-item> -->      
      
    </div>
    <div style="text-align:center; padding-top:15px" >
        <el-button @click="addItem">添加一条音/视频</el-button>
      </div>
    </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: "请输入正文"
      },
      editorOption1: {
        modules: {
          history: {
            delay: 1000,
            maxStack: 50,
            userOnly: false
          },
          toolbar: false
        },
        placeholder: "请输入思考题"
      },
      visible: false,
      props: {
        dictType: "",
        dictValue: ""
      },
      typeList: [
        //类型0普通1加密
        {
          dictType: 0,
          dictValue: "普通"
        },
        {
          dictType: 1,
          dictValue: "加密"
        },
        {
          dictType: 2,
          dictValue: "mp3"
        }
      ],
      gushuList: [],
      authorList: [],
      restaurants: [],
      author: "",
      publisherList: [],
      fileList: [],
      fileListNovel: [],
      dialogImageUrl: "",
      dialogVisible: false,
      dataForm: {
        courseId: 0,
        isAudition: 0,
        catalogueId: 0,
        title: "",
        imgUrl: "",
        content: "",
        sort: 1,
        questions:''
        // video_audio_url: [
        //   {url:'454545',type:0}
        // ]
      }, 
      video_audio_url: [
      { video: "" ,type:1,id:0,sort:0}
        ], 
      obj:{ video: "" ,type:1,id:0,sort:0},   
      splitsTypeList: [],
      dataRule: {},
      chapterId:null,
    };
  },
  components: {
    quillEditor
  },
  created() {},
  mounted() {},
  methods: {
    delItem(index){
      this.video_audio_url.splice(index, 1)
      // console.log(this.video_audio_url,'删除后的')
    },
    addItem() {
      // var jj = {...this.obj}
      console.log(this.video_audio_url.length,'this.dataForm.video_audio_url--------')
      this.video_audio_url.push({'chapterId':this.chapterId, ...this.obj});
      console.log(this.video_audio_url,'this.dataForm.video_audio_url')
    },
    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;
      this.chapterId = this.dataForm.id
      if(this.dataForm.videoList && this.dataForm.videoList.length > 0){
        this.video_audio_url = [...this.dataForm.videoList]
        console.log('dedao',this.video_audio_url)
      }else{
        this.video_audio_url = []
      }
      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 => {
        console.log('this.dataForm.questions',this.dataForm.questions)
        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,
              isAudition: this.dataForm.isAudition,
              videoList:this.video_audio_url,
              questions: this.dataForm.questions ? this.dataForm.questions : ''
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              // this.video_audio_url = []
              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.video_audio_url = []
      (this.fileList = []), (this.fileListNovel = []), (this.visible = false),(this.video_audio_url = []);
    },
    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>
<style lang="less" scoped>
.flexbox {
  display: flex;
}
.videoBox { width: 100%;
  margin-bottom: 15px; align-items: center;
}
</style>
