<template>
  <div>
    <div class="exersices-content">
      <IconText :text="'题目'" :color="'#2d8cf0'" :icon="'ios-create'" style="margin-bottom:15px;"></IconText>
      <div>
        <div ref="singleEditor" 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 options" :class="'editor-wrap-'+item" style="margin-top:10px;display:flex">
        <span class="fl-center option-order">{{String.fromCharCode(64 + parseInt(index+1))}}</span>
        <div :ref="'singleOption'+item" style="text-align:left" class="option-editor" @click="optionClick(item)"></div>
        <span :class="['fl-center', 'option-setting', trueIndex == index ? 'option-true':'']" @click="settingAnswer(index)">{{ trueIndex == index ? '正确答案' :'设为答案' }}</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><span style="color:rgb(60,196,82);margin-left:15px;font-weight:bold">正确答案 ：{{String.fromCharCode(64 + parseInt(trueIndex+1))}}</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 {
        options: [...new Array(4).keys()], //默认四个选项
        existOptions: [...new Array(4).keys()],
        initFlag: true,
        trueIndex: 0,
        stemEditor:null,
        stemContent: "",
        optionsContent: [],
        defaultConfig: {
          uploadImgServer: '/api/file/uploadWangEditor', //图片上传地址
          showLinkImg: false, //是否展示网络图片链接上传
          uploadFileName: 'files', //上传图片后台获取的文件名
        }
      }
    },
    created() {
      if (Object.keys(this.editInfo).length > 0) {
        this.options = [...new Array(this.editInfo.options.length).keys()];
      }
    },
    methods: {
      initEditors() {
        //Editor默认配置
        if (this.options.length > 0) {
          this.options.forEach((item, i) => {
            let that = this;
            let editor = new E(that.$refs['singleOption' + i][0]);
            editor.customConfig = this.defaultConfig;

            //选项编辑器失焦隐藏工具栏
            editor.customConfig.onblur = function () {
              let allToolbars = document.getElementsByClassName('option-editor');
              for (let i = 0; i < allToolbars.length; i++) {
                if (allToolbars[i].children.length) {
                  allToolbars[i].children[0].style.visibility = "hidden"
                }
              }
            }

            //选项编辑器内容发生变化时
            editor.customConfig.onchange = (html) => {
              let key = String.fromCharCode(64 + parseInt(i + 1));
              let codeArr = this.optionsContent.map(item => item.code);
              //如果已经编辑过则 修改选项内容
              if (codeArr.indexOf(key) != -1) {
                this.optionsContent[codeArr.indexOf(key)].value = html;
              } else { //否则创建新选项
                  let option = {
                    code: key,
                    value:html
                  }
                  this.optionsContent.push(option);
              }
            }
            editor.create();

            //如果是编辑状态 则将选项内容回显
            if (Object.keys(this.editInfo).length > 0) {
              editor.txt.html(this.editInfo.options[i].value);
            }

          })
        }
      },
      //设置正确答案
      settingAnswer(index) {
        this.trueIndex = index;
      },
      //添加选项
      addOption() {
        let that = this;
        let newIndex = parseInt(this.options[this.options.length - 1]) + 1;
        let optionsLength = this.options.length;
        if (optionsLength < 8) {
          this.options.push(newIndex);
          this.$nextTick(() => {
            let editor = new E(that.$refs['singleOption' + newIndex][0]);
            editor.customConfig = this.defaultConfig;

            editor.customConfig.onchange = (html) => {
              let key = String.fromCharCode(64 + parseInt(newIndex + 1));
              let codeArr = this.optionsContent.map(item => item.code);
              //如果已经编辑过则 修改选项内容
              if (codeArr.indexOf(key) != -1) {
                this.optionsContent[codeArr.indexOf(key)].value = html;
                console.log(this.optionsContent.map(item => item.code))
                console.log(this.optionsContent.map(item => item.value))
              } else { //否则创建新选项
                  let option = {
                    code: key,
                    value:html
                  }
                this.optionsContent.push(option);
                console.log(this.optionsContent.map(item => item.code))
                console.log(this.optionsContent.map(item => item.value))
              }
            }
            editor.create();
          })
        } else {
          this.$Message.warning("最多只有8个选项！");
        }
      },
      //删除选项
      deleteOption(index) {
        if (this.options.length > 2) {
          this.options.splice(index, 1);
          this.optionsContent.splice(index, 1);
          //如果删除了已有选项 后面的code要降1
          for (let i in this.optionsContent) {
            if (i >= index) {
              this.optionsContent[i].code = String.fromCharCode(64 + parseInt(parseInt(i) + 1));
            }
          }
          if (index < this.trueIndex) {
            this.trueIndex = this.trueIndex - 1;
          }

        } else {
          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['singleOption' + index][0].children[0];
          currentToolBar.style.visibility = "visible";
        }, 100)
      },
    },
    mounted() {
      let stemEditor = new E(this.$refs.singleEditor);
      stemEditor.customConfig = this.defaultConfig;
      stemEditor.customConfig.onchange = (html) => {
        this.stemContent = html;
      }
      stemEditor.create();
      this.stemEditor = stemEditor;

      //判断是否为编辑状态
      if (Object.keys(this.editInfo).length > 0) {
        this.stemEditor.txt.html(this.editInfo.question);
        this.stemContent = this.editInfo.question;
        this.optionsContent = this.editInfo.options;
        this.trueIndex = this.editInfo.answer[0].charCodeAt() - 65;
        this.options = this.editInfo.options.map((item,index) => index);
      }

      this.initEditors();
    }
  }
</script>
<style scoped>
  @import"../index/CreateExercises.css";
</style>
