<template>
  <div>
    <div class="exersices-content">
      <span class="add-underline"><Button type="primary" @click="addOption()">添加填空横线</Button></span>
      <IconText :text="'题目'" :color="'#2d8cf0'" :icon="'ios-create'" style="margin-bottom:15px;"></IconText>
      <div>
        <div ref="completionEditor" style="text-align:left"></div>
      </div>
    </div>
    <div class="exersices-option">
      <IconText :text="'填空选项'" :color="'#FF871C'" :icon="'md-reorder'"></IconText>
      <div v-for="(item,index) in optionsIndexArr" :class="['editor-wrap-'+item,'editor-wrap']" style="margin-top:10px;display:flex">
        <span class="fl-center option-order">{{'空0'+(index+1)}}</span>
        <div :ref="'editor'+index" style="text-align:left" class="option-editor" @click="optionClick(index)"></div>
        <span :class="['fl-center', 'option-setting']" style="display:none;background:transparent;cursor:auto"></span>
        <span class="fl-center option-delete" @click="deleteOption(index)"><Icon type="ios-close-circle" /></span>
      </div>
      <!--<p class="option-add"><span @click="addOption()">+ 添加选项 </span></p>-->
    </div>
  </div>
</template>
<script>
  import E from 'wangeditor'
  import IconText from '@/components/evaluation/IconText.vue'
  export default {
    components: {
      IconText
    },
    props: ['editInfo'],
    data() {
      return {
        completionEditor:"",
        options: [...new Array(0).keys()],
        optionsContent:[],
        initFlag: true,
        trueIndex: 0,
        stemContent: "",
        stemEditor:null,
        answerContent: [],
        linesIndexArr: [],
        optionsIndexArr:[],
        defaultConfig: {
          uploadImgServer: '/api/file/uploadWangEditor', //图片上传地址
          showLinkImg: false, //是否展示网络图片链接上传
          uploadFileName: 'files', //上传图片后台获取的文件名
        }
      }
    },
    created() {
      //编辑状态下回显
      if (Object.keys(this.editInfo).length) {
        let that = this;
        this.optionsIndexArr = this.editInfo.answer;
        this.optionsIndexArr.forEach((item, index) => {
          this.optionsContent.push({ code: index, value: item }); //填空答案回显
          this.$nextTick(() => {
              let editor = new E(that.$refs['editor' + index][0]);
              editor.customConfig = this.defaultConfig;
                //每个填空选项 数据变化
              editor.customConfig.onchange = (html) => {
                let codeArr = this.optionsContent.map(item => item.code);
                //如果已经编辑过则 修改选项内容
                if (codeArr.indexOf(index) != -1) {
                  this.optionsContent[codeArr.indexOf(index)].value = html;
                } else { //否则创建新选项
                  let option = {
                    code: index,
                    value: html
                  }
                  this.optionsContent.push(option);
                }
              },
              editor.customConfig.onblur = function () {
                let allToolbars = document.getElementsByClassName('option-editor');
                for (let j = 0; j < allToolbars.length; j++) {
                  if (allToolbars[j].children.length) {
                    allToolbars[j].children[0].style.visibility = "hidden"
                  }
                }
              },
              editor.create();
              editor.txt.html(item); //填空答案回显内容
          })
        })

      }
    },
    methods: {
      //设置正确答案
      settingAnswer(index) {
        this.trueIndex = index;
      },
      //下划线点击事件
      lineClick(e) {
        console.log(e);
      },
      //删除选项
      deleteOption(index) {
        //if (this.options.length > 2) {
        //  this.options.splice(index, 1);
        //  this.linesNum -= 1;
        //} else {
        //  this.$Message.warning("至少保留两个选项！");
        //}
        this.$Message.warning("请在题目编辑框内删除对应横线即可");
      },
      //选项输入框点击事件
      optionClick(index) {
        let allToolbars = document.getElementsByClassName('option-editor');
        let that = this;
        for (let i = 0; i < allToolbars.length; i++) {
          allToolbars[i].children[0].style.visibility = "hidden"
        }
        setTimeout(function () {
          let currentToolBar = that.$refs['editor' + index][0].children[0];
          currentToolBar.style.visibility = "visible";
        }, 100)
      },

      //添加选项
      addOption() {
        let that = this;
        let newIndex = this.linesIndexArr.length ? parseInt(this.linesIndexArr[this.linesIndexArr.length - 1]) + 1 : 0; //不能重复
        let newLineIndex = this.linesIndexArr.length; //长度即标记

        //插入下划线
        let addHtml = "&nbsp;<span class='complete-line' data-index=" + newIndex + " data-answer=" + newIndex + " contenteditable='false'>&#93" + ( newLineIndex + 12 ) + "</span>&nbsp;"
        this.completionEditor.cmd.do('insertHTML', addHtml)
        this.stemContent = this.stemContent + addHtml;
        this.linesIndexArr.push(newIndex); //题干中下划线集合
        this.optionsIndexArr.push(newIndex); //选项集合
          this.$nextTick(() => {
            let editor = new E(that.$refs['editor' + newIndex][0]);
            editor.customConfig = this.defaultConfig;
              //每个填空选项 数据变化
            editor.customConfig.onchange = (html) => {
              let codeArr = this.optionsContent.map(item => item.code);
              //如果已经编辑过则 修改选项内容
              if (codeArr.indexOf(newIndex) != -1) {
                this.optionsContent[codeArr.indexOf(newIndex)].value = html;
              } else { //否则创建新选项
                let option = {
                  code: newIndex,
                  value: html
                }
                this.optionsContent.push(option);
              }
              console.log(this.optionsContent);
            },
            editor.customConfig.onblur = function () {
              let allToolbars = document.getElementsByClassName('option-editor');
              for (let j = 0; j < allToolbars.length; j++) {
                if (allToolbars[j].children.length) {
                  allToolbars[j].children[0].style.visibility = "hidden"
                }
              }
            },

            editor.create();
          })
      },


    },

    mounted() {
      let completionEditor = new E(this.$refs.completionEditor);
      this.completionEditor = completionEditor;
      completionEditor.customConfig = this.defaultConfig;

      //当填空题型 题干部分插入下划线以及删除下划线监听
      completionEditor.customConfig.onchange = (html) => {
        this.stemContent = html;

        //获取修改后的下划线列表与之前的内容进行对比
        let linesArr = Array.prototype.slice.call(document.getElementsByClassName('complete-line'));
        let dataSetArr = linesArr.map((item,index) => index);
        this.linesIndexArr = JSON.parse(JSON.stringify(this.linesIndexArr));

        //如果是删除了下划线则删除对应选项输入框
        if (this.linesIndexArr.length > dataSetArr.length) {
          Array.prototype.diff = function(a) {
              return this.filter(function(i) {return a.indexOf(i) < 0;});
          };
          let deleteIndexArr = this.linesIndexArr.diff(dataSetArr); //获取要删除的选项下标
          let optionsArr = Array.prototype.slice.call(document.getElementsByClassName('editor-wrap')); //获取到所有的选项DOM

          //对指定选项进行删除操作
          this.$nextTick(() => {
            deleteIndexArr.forEach(item => {
              let deleteDom = document.getElementsByClassName('editor-wrap')[item-1];
              this.optionsIndexArr.splice(this.optionsIndexArr.indexOf(deleteDom), 1);
              this.optionsContent.splice(item, 1);
              optionsArr.splice(item, 1);
            });
          })
        }
        this.linesIndexArr = [...dataSetArr];
        //重新渲染下划线的下标
        linesArr.forEach((item,index) => {
          let numCircle = "&#93" + (parseInt(index) + 12) + "";
          item.innerHTML = numCircle;
          item.setAttribute('data-index', index);
        })
      },
        completionEditor.create();

        this.stemEditor = completionEditor;

         //判断是否为编辑状态
        if (Object.keys(this.editInfo).length > 0) {
          this.stemEditor.txt.html(this.editInfo.question);
          this.stemContent = this.editInfo.question;
          
        }

    }


  }
</script>
