<template>
  <div class="ev-container">
    <span class="ev-title"><Icon type="ios-paper"/>{{isEdit?'编辑习题':'新建习题'}}</span>
    <Divider />
    <div class="exersices-attr display-flex">
      <div class="exersices-attr-type my-radio-style">
        <IconText :text="'选择题型'" :color="'green'" :icon="'md-apps'"></IconText>
        <RadioGroup v-model="exersicesType" type="button" @on-change="typeChange">
          <Radio label="Single" :disabled="isEdit">单选</Radio>
          <Radio label="Multiple" :disabled="isEdit">多选</Radio>
          <Radio label="Judge" :disabled="isEdit">判断</Radio>
          <Radio label="Complete" :disabled="isEdit">填空</Radio>
          <Radio label="Subjective" :disabled="isEdit">问答</Radio>
          <Radio label="Compose" :disabled="isEdit">综合</Radio>
        </RadioGroup>
      </div>
      <div class="exersices-attr-diff my-radio-style">
        <IconText :text="'题目难度'" :color="'red'" :icon="'md-pulse'"></IconText>
        <RadioGroup v-model="exersicesDiff" type="button">
          <Radio label="0" @click.native="diffChange($event,'0')">容易</Radio>
          <Radio label="1" @click.native="diffChange($event,'1')">较易</Radio>
          <Radio label="2" @click.native="diffChange($event,'2')">一般</Radio>
          <Radio label="3" @click.native="diffChange($event,'3')">较难</Radio>
          <Radio label="4" @click.native="diffChange($event,'4')">困难</Radio>
        </RadioGroup>
      </div>
    </div>

    <BaseSingle v-if="exersicesType=='Single'" ref="single" :editInfo="editInfo"></BaseSingle>
    <BaseMultiple v-else-if="exersicesType=='Multiple'" ref="multiple" :editInfo="editInfo"></BaseMultiple>
    <BaseJudge v-else-if="exersicesType=='Judge'" ref="judge" :editInfo="editInfo"></BaseJudge>
    <BaseCompletion v-else-if="exersicesType=='Complete'" ref="complete" :editInfo="editInfo"></BaseCompletion>
    <BaseSubjective v-else-if="exersicesType=='Subjective'" ref="subjective" :editInfo="editInfo"></BaseSubjective>

    <div class="exersices-analysis">
      <IconText :text="'解析'" :color="'#2892DD'" :icon="'md-list'" style="margin-bottom:15px;"></IconText>
      <Upload action="/api/file/uploadWangEditor" name="files" :show-upload-list="false" :on-success="handleSuccess">
        <Button icon="ios-cloud-upload-outline" class="btn-upload" type="info">上传文件</Button>
      </Upload>
      <div>
        <div ref="analysisEditor" style="text-align:left"></div>
      </div>
    </div>
    <div class="save-wrap display-flex">
      <Button type="success" @click="getContent(exersicesType)">保存</Button>
      <Button type="success" @click="reloadCreate" style="margin-left:10px" v-show="isEdit">新增习题</Button>
      <Button type="success" @click="resetEditor" style="margin-left:10px">题库</Button>
    </div>
  </div>
</template>
<script>
  import "videojs-contrib-hls.js/src/videojs.hlsjs"
  import IconText from '@/components/evaluation/IconText.vue'
  import BaseSingle from '@/view/evaluation/types/BaseSingle.vue'
  import BaseMultiple from '@/view/evaluation/types/BaseMultiple.vue'
  import BaseCompletion from '@/view/evaluation/types/BaseCompletion.vue'
  import BaseJudge from '@/view/evaluation/types/BaseJudge.vue'
  import BaseSubjective from '@/view/evaluation/types/BaseSubjective.vue'
  import E from 'wangeditor'
  //默认创建题目模板
  const defaultExercise = {
    question: "",
    options: [],
    difficulty: "",
    answer: [],
    explain: "",
    type: ""
  }
  export default {
    components: {
      IconText, BaseSingle, BaseJudge, BaseMultiple, BaseCompletion, BaseSubjective
    },
    data() {
      return {
        isEdit: false,
        editInfo: {},
        exersicesType: 'Single',
        exersicesDiff: "0",
        analysisContent: "",
        stemContent: "",
        analysisEditor: null,
        videoHtml: "",
        playerOptions: {
          playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
          autoplay: false, //如果true,浏览器准备好时开始回放。
          controls: true, //控制条
          preload: 'auto', //视频预加载
          muted: false, //默认情况下将会消除任何音频。
          loop: false, //导致视频一结束就重新开始。
          language: 'zh-CN',
          aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
          fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
          sources: [{
            //type: 'application/x-mpegURL',
            src: "https://teammodelstorage.blob.core.chinacloudapi.cn/teammodelcontest/20190517/history/history.m3u8"
          }],
          //poster: "http://static.smartisanos.cn/pr/img/video/video_03_cc87ce5bdb.jpg", //你的封面地址
          width: document.documentElement.clientWidth,
          notSupportedMessage: '此视频暂无法播放，请稍后再试' //允许覆盖Video.js无法播放媒体源时显示的默认信息。
        },
      }
    },
    created() {
      let editItem = this.$route.params.item; //编辑题目
      if (editItem) {
        this.editInfo = editItem;
        console.log(editItem);
      }
    },
    methods: {
      getContent: function (type) {
        let exerciseItem = Object.assign({}, defaultExercise);
        switch (type) {
          case "Single":
            exerciseItem.question = this.$refs.single._data.stemContent;
            exerciseItem.option = this.$refs.single._data.optionsContent.length == this.$refs.single._data.options.length ? this.$refs.single._data.optionsContent : null;
            exerciseItem.type = this.exersicesType;
            exerciseItem.difficulty = this.exersicesDiff;
            exerciseItem.explain = this.analysisContent;
            exerciseItem.answer = [String.fromCharCode(64 + parseInt(this.$refs.single._data.trueIndex + 1))];
            break;
          case "Multiple":
            exerciseItem.question = this.$refs.multiple._data.stemContent;
            exerciseItem.option = this.$refs.multiple._data.optionsContent.length == this.$refs.multiple._data.options.length ? this.$refs.multiple._data.optionsContent : null;
            exerciseItem.type = this.exersicesType;
            exerciseItem.difficulty = this.exersicesDiff;
            exerciseItem.explain = this.analysisContent;
            exerciseItem.answer = this.$refs.multiple._data.transferArr;
            break;
          case "Judge":
            exerciseItem.question = this.$refs.judge._data.stemContent;
            exerciseItem.option = [];
            exerciseItem.type = this.exersicesType;
            exerciseItem.difficulty = this.exersicesDiff;
            exerciseItem.explain = this.analysisContent;
            exerciseItem.answer = this.$refs.judge._data.trueAnswer;
            break;
          case "Complete":
            exerciseItem.question = this.$refs.complete._data.stemContent;
            exerciseItem.option = [];
            exerciseItem.type = this.exersicesType;
            exerciseItem.difficulty = this.exersicesDiff;
            exerciseItem.explain = this.analysisContent;
            exerciseItem.answer = this.$refs.complete._data.optionsContent.map(item => item.value);
            break;
          case "Subjective":
            exerciseItem.question = this.$refs.subjective._data.stemContent;
            exerciseItem.option = [];
            exerciseItem.type = this.exersicesType;
            exerciseItem.difficulty = this.exersicesDiff;
            exerciseItem.explain = this.analysisContent;
            exerciseItem.answer = this.$refs.subjective._data.answerContent;
            break;
        }

        //判断获取的数据是否有空数据以及是否为空字符串
        if (this.checkContent(exerciseItem) && this.getSimpleText(exerciseItem.question) && this.getSimpleText(exerciseItem.explain)) {
          this.$router.push({
            name: 'exercisesList',
            params: {
              exerciseItem: exerciseItem,
            }
          })
        } else {
          this.$Message.warning("请将题目填写完整！");
        }

        console.log(exerciseItem);

      },

      //题目类型转换
      typeChange(val) {
        if (this.isEdit) {
          this.$Message.warning("暂不支持更换题型！");
        } else if (val == 'Compose') {
          this.$router.push({
            name: 'createCompose'
          })
        } else {
          this.exersicesType = val;
          this.analysisEditor.txt.clear();
        }
      },

      //难度与背景颜色切换
      diffChange(e, type) {
        this.exersicesDiff = type;
        e.preventDefault();
        let colorArr = ['#32CF74', '#E8BE15', '#F19300', '#EB5E00', '#D30000'];
        let ac = document.getElementsByClassName('exersices-attr-diff')[0].children[1].children;
        for (let i = 0; i < ac.length; i++) {
          ac[i].style.background = "#fff";
          ac[i].style.color = "#515a6e";
        }
        e.target.style.background = colorArr[type];
        e.target.style.color = "#fff";
      },

      //提取富文本内容中的文本
      getSimpleText(html) {
        var msg = html.replace(/<(?!img|video).*?>/g, '');//执行替换成空字符
        return msg.replace(/&nbsp;/ig, "");
      },
      //排除对象空属性
      checkContent(Obj) {
        let flag = true;
        for (let key in Obj) {
          if (!Obj[key]) {
            flag = false;
          }
        }
        return flag;
      },

      //重置编辑器
      resetEditor() {
        this.$router.push({
            name: 'exercisesList'
          })
      },

      reloadCreate() {
        location.reload()
      },

      //文件上传成功回调
      handleSuccess(res, file) {
        this.videoHtml = "<br><iframe src='https://teammodelstorage.blob.core.chinacloudapi.cn/wechatfilescontainer/wechatfilescontainer/HilearningMobile_function_10.mp4' frameborder='0' allowfullscreen='true'></iframe><br>";
        this.analysisContent = this.analysisContent + this.videoHtml;
        this.analysisEditor.txt.append(this.videoHtml);
        console.log(this.analysisContent);
      },

    },
    mounted() {
      let analysisEditor = new E(this.$refs.analysisEditor)
      analysisEditor.customConfig.onchange = (html) => {
        this.analysisContent = html
      },
      analysisEditor.customConfig.uploadImgServer = '/api/file/uploadWangEditor'
      analysisEditor.customConfig.showLinkImg = false;
      analysisEditor.customConfig.uploadFileName = 'files'
      analysisEditor.create();
      this.analysisEditor = analysisEditor;

      let editItem = this.$route.params.item; //编辑题目
      if (editItem) {
        this.isEdit = true;
        this.editInfo = editItem;
        this.exersicesDiff = editItem.difficulty || 0;
        this.exersicesType = editItem.type;
        this.stemContent = editItem.question;
        this.optionsContent = editItem.options;
        this.analysisContent = editItem.explain;
        this.analysisEditor.txt.html(editItem.explain);
        //重新渲染题目难度
        let diffDom = document.getElementsByClassName('exersices-attr-diff')[0].getElementsByClassName('ivu-radio-wrapper')[editItem.difficulty];
        let colorArr = ['#32CF74', '#E8BE15', '#F19300', '#EB5E00', '#D30000'];
        diffDom.style.background = colorArr[editItem.difficulty];
        diffDom.style.color = "#fff";
      }

    }
  }
</script>
<style src="../index/CreateExercises.css" scoped>
  /*@import"../index/CreateExercises.css";*/
</style>
