<!--  -->
<template>
  <div
    class="NPC-ArticleView NPC-ArticleView-container"
    id="articleBoby"
    v-if="curQue && curQue.Bookanswer"
  >
    <div class="ArticleView-header">
      <a class="ArticleView-full" @click="fullScreen">黑板模式</a>
      <div>
        <div
          class="left"
          @click="submit"
          :style="{ marginLeft: '104px' }"
          v-if="
            tokenData &&
              tokenData.popedom_code_list &&
              tokenData.popedom_code_list.indexOf(2000001) != -1
          "
        >
          <img src="../../../../assets/NPC/wbfx-icon.png" alt="" />
          文本分析
        </div>
      </div>

      <div class="right">
        <template v-if="curQue.checkList.indexOf(1) > -1">
          <el-switch
            style="display: block"
            v-model="showPhrases"
            :active-color="activeColor"
            inactive-color="rgba(0,0,0,0.1)"
            active-text=""
            inactive-text="本课生词"
            @change="handleSwitchChange('showPractice', 'showWord')"
          >
          </el-switch>
        </template>
        <template v-if="curQue.checkList.indexOf(2) > -1">
          <el-switch
            style="display: block"
            v-model="showPractice"
            :active-color="activeColor"
            inactive-color="rgba(0,0,0,0.1)"
            active-text=""
            inactive-text="语音练习"
            @change="handleSwitchChange('showPhrases', 'showWord')"
          >
          </el-switch>
        </template>
        <template v-if="curQue.checkList.indexOf(3) > -1">
          <el-switch
            style="display: block"
            v-model="showWord"
            :active-color="activeColor"
            inactive-color="rgba(0,0,0,0.1)"
            active-text=""
            inactive-text="取词"
            @change="handleSwitchChange('showPhrases', 'showPractice')"
          >
          </el-switch>
        </template>
      </div>

      <!-- <div class="setting-fontsize">
        <a @click="handleFontsize('-')"
          ><img src="../../../../assets/newImage/common/btn-reduce.png"
        /></a>
        <img src="../../../../assets/newImage/common/font-size.png" />
        <a @click="handleFontsize('+')"
          ><img src="../../../../assets/newImage/common/btn-increase.png"
        /></a>
      </div> -->
    </div>
    <div class="ArticleView-body" ref="ArticleViewbody">
      <NormalModelChs
        :curQue="curQue"
        :titleFontsize="titleFontsize"
        :wordFontsize="wordFontsize"
        :bodyLeft="bodyLeft"
        :bodyWidth="bodyWidth"
        :colorBox="colorBox"
        :NNPEAnnotationList="NNPEAnnotationList"
        :themeColor="themeColor"
        :noFont="noFont"
        :config="config"
        :TaskModel="TaskModel"
        @changeConfig="changeConfig"
        v-if="!showPhrases && !showPractice && !showWord"
        :colLength="colLength"
      />
      <PhraseModel
        :curQue="curQue"
        :titleFontsize="titleFontsize"
        :wordFontsize="wordFontsize"
        :NNPENewWordList="NNPENewWordList"
        :NNPEAnnotationList="NNPEAnnotationList"
        :colorBox="colorBox"
        :themeColor="themeColor"
        :noFont="noFont"
        :currentTreeID="currentTreeID"
        :bodyLeft="bodyLeft"
        :config="config"
        :TaskModel="TaskModel"
        @changeConfig="changeConfig"
        v-if="showPhrases"
        :colLength="colLength"
        :NpcNewWordMp3="NpcNewWordMp3"
      />
      <Practice
        :curQue="curQue"
        :titleFontsize="titleFontsize"
        :wordFontsize="wordFontsize"
        :colorBox="colorBox"
        :themeColor="themeColor"
        :noFont="noFont"
        :currentTreeID="currentTreeID"
        :NNPENewWordList="NNPENewWordList"
        :config="config"
        :TaskModel="TaskModel"
        @changeConfig="changeConfig"
        v-if="showPractice"
        :colLength="colLength"
        :isFull="isFull"
        :NpcNewWordMp3="NpcNewWordMp3"
      />
      <WordModel
        :curQue="curQue"
        :titleFontsize="titleFontsize"
        :wordFontsize="wordFontsize"
        :bodyLeft="bodyLeft"
        :bodyWidth="bodyWidth"
        :NNPENewWordList="NNPENewWordList"
        :colorBox="colorBox"
        :themeColor="themeColor"
        :noFont="noFont"
        :currentTreeID="currentTreeID"
        :config="config"
        :TaskModel="TaskModel"
        @changeConfig="changeConfig"
        v-if="showWord"
        :colLength="colLength"
      />
    </div>
    <div class="voice-full-screen" :id="'screen-' + mathNum">
      <Voicefullscreen
        v-if="isFull && resObj"
        :themeColor="themeColor"
        :curQue="curQue"
        :sentList="resObj.sentList"
        :sentIndex="0"
        :mp3="
          curQue.mp3_list && curQue.mp3_list[0] ? curQue.mp3_list[0].id : ''
        "
        :noFont="noFont"
        :NNPENewWordList="NNPENewWordList"
        :currentTreeID="currentTreeID"
        :isFull="isFull"
        :config="config"
        :TaskModel="TaskModel"
        @handleWav="handleWav"
        @changePinyin="changePinyins"
        @changeEN="changeENs"
        @exitFullscreen="exitFullscreen"
        @changeIsFull="changeIsFull"
        :NpcNewWordMp3="NpcNewWordMp3"
      />
    </div>
  </div>
</template>

<script>
import PhraseModel from "./PhraseModelChs.vue";
import NormalModelChs from "./NormalModelChs.vue";
import Practice from "./Practicechs.vue"; // 语音练习模式
import WordModel from "./WordModelChs.vue"; // 语音练习模式
import Voicefullscreen from "../Voicefullscreen.vue";
import { analysSubmit, getContentFile } from "@/api/ajax";
import { getToken } from "@/utils/auth";
export default {
  name: "DialogueArticleViewChs",
  props: [
    "curQue",
    "NNPENewWordList",
    "NNPEAnnotationList",
    "colorBox",
    "themeColor",
    "currentTreeID",
    "TaskModel",
    "colLength",
    "NpcNewWordMp3"
  ],
  components: {
    NormalModelChs,
    Practice,
    WordModel,
    PhraseModel,
    Voicefullscreen
  },
  data() {
    return {
      showPreview: true, // 全文预览
      showPhrases: false, // 显示单词和短语
      showPractice: false, // 语音练习

      showWord: false, // 取词
      titleFontsize: 20, // 标题字号初始值
      wordFontsize: 16, // 文章内容字号初始值
      bodyLeft: 0,
      bodyWidth: 0,
      resColorArr: [],
      noFont: ["~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "/"],
      config: {
        isShowEN: false,
        isHasEN: false,
        isShowPY: false,
        isHasPY: false
      },
      userAnswer: {
        normalModel: {
          recordList: []
        },
        writeModel: {}, //生词/取词模式
        practiceModel: {}, //练习模式
        wordModel: {
          recordList: []
        }
      },
      tokenData: null,
      mathNum: Math.random()
        .toString(36)
        .substr(2),
      isFull: false,
      resObj: null,
      chsFhList: ["，", "。", "”", "：", "》", "？", "！", "；"],
      highWords: null,
      highWordsArr: [],
      highIndex: 0,
      newWordList: []
    };
  },
  computed: {
    activeColor: function() {
      let color = "";
      if (this.themeColor == "red") {
        color = "#DE4444";
      } else if (this.themeColor == "green") {
        color = "#24B99E";
      } else if (this.themeColor == "brown") {
        color = "#BD8865";
      }

      return color;
    }
  },
  watch: {},
  //方法集合
  methods: {
    submit() {
      let loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      analysSubmit({
        app_user_id: "",
        text: this.curQue.article
      })
        .then(res => {
          window.open(
            window.location.origin +
              `/GCLS-TC/#/textanalysis/Result?id=${res.record.id}&type=文本分析`
          );
          loading.close();
        })
        .catch(res => {
          loading.close();
        });
    },
    goFullscreen() {
      var element = document.getElementById("articleBoby");
      if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen();
      } else if (element.webkitRequestFullScreen) {
        element.webkitRequestFullScreen();
      }
    },
    //拼音的显示和隐藏
    changePinyins() {
      if (this.config.isHasPY) {
        this.changeConfig("isShowPY");
      }
    },
    // 英文的显示和隐藏
    changeENs() {
      if (this.config.isHasEN) {
        this.changeConfig("isShowEN");
      }
    },
    changeConfig(obj) {
      this.config[obj] = !this.config[obj];
    },
    // 英文的显示和隐藏
    changeEN() {
      this.isShowEN = !this.isShowEN;
    },
    changePY() {
      this.isShowPY = !this.isShowPY;
    },
    changeIsFull() {
      this.isFull = false;
    },
    // 处理字体大小
    handleFontsize(symbol) {
      if (symbol == "+") {
        if (this.wordFontsize < 24) {
          this.titleFontsize = this.titleFontsize + 2;
          this.wordFontsize = this.wordFontsize + 2;
        }
      } else if (symbol == "-") {
        if (this.wordFontsize > 12) {
          this.titleFontsize = this.titleFontsize - 2;
          this.wordFontsize = this.wordFontsize - 2;
        }
      }
    },
    // 切换开关
    handleSwitchChange(obj1, obj2) {
      this[obj1] = false;
      this[obj2] = false;
      this.showPreview = false;
    },
    articleFullScreen() {},
    handleObj(list) {
      let pinyin = "";
      list.forEach(item => {
        item.forEach(items => {
          if (items.pinyin) pinyin += items.pinyin;
        });
      });
      return pinyin;
    },
    getmp3List() {
      let obj = {
        file_id: this.curQue.mp3_list[0].file_id,
        time_space_list: []
      };
      this.curQue.wordTime.forEach(item => {
        obj.time_space_list.push({
          begin_time: item.bg,
          end_time: item.ed
        });
      });
      let Mname = "tool-AudioFileSplit";
      getContentFile(Mname, obj)
        .then(res => {
          this.curQue.time_space_list = res.time_space_list;
        })
        .catch(res => {});
    },
    //语音全屏
    fullScreen() {
      this.pauseAudio();
      this.pauseVideo();
      this.isFull = true;
      this.goFullscreen();
    },
    pauseAudio() {
      let audio = document.getElementsByTagName("audio");
      if (
        audio &&
        audio.length > 0 &&
        window.location.href.indexOf("GCLS-Learn") == -1
      ) {
        audio.forEach(item => {
          item.pause();
        });
      }
    },
    pauseVideo() {
      let video = document.getElementsByTagName("video");
      if (
        video &&
        video.length > 0 &&
        window.location.href.indexOf("GCLS-Learn") == -1
      ) {
        video.forEach(item => {
          item.pause();
        });
      }
    },
    goFullscreen() {
      let id = "screen-" + this.mathNum;
      var element = document.getElementById(id);
      if (element.requestFullscreen) {
        element.requestFullscreen();
      } else if (element.msRequestFullscreen) {
        element.msRequestFullscreen();
      } else if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen();
      } else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullscreen();
      }
    },
    exitFullscreen() {
      this.isFull = false;
      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
      }
    },
    handleData() {
      let resArr = [],
        sentArrTotal = [],
        timeArr = [];
      let curQue = JSON.parse(JSON.stringify(this.curQue));
      let wordTimeList = curQue.wordTime;
      let dhaspinyin = false; // 每段是否有拼音
      let dhaspinyinArr = [];
      curQue.detail.forEach((dItem, dIndex) => {
        dhaspinyin = false;
        dItem.wordsList.forEach((sItem, sIndex) => {
          let sentArr = [];
          let sentence = dItem.sentences[sIndex];
          sItem.forEach((wItem, wIndex) => {
            let startIndex =
              wIndex == 0
                ? 0
                : sentArr[wIndex - 1].startIndex +
                  sentArr[wIndex - 1].chs.length;
            let endIndex =
              wIndex == 0
                ? wItem.chs.length
                : sentArr[wIndex - 1].endIndex + wItem.chs.length;
            // this.judgePad(sItem, wItem, wIndex);
            this.mergeWordSymbol(wItem);
            let words = "";
            if (this.newWordList.length > 0) {
              if (!this.highWords) {
                this.findLightWord(wItem, wIndex, sentence, sItem);
                words = this.highWords ? this.highWords.words : "";
              } else {
                if (wIndex > this.highWords.endIndex - 1) {
                  this.highWords = null;
                  this.findLightWord(wItem, wIndex, sentence, sItem);
                  words = this.highWords ? this.highWords.words : "";
                } else {
                  words = this.highWords ? this.highWords.words : "";
                }
              }
            }
            let obj = {
              paraIndex: dIndex, //段落索引
              sentIndex: sIndex, //在段落中句子索引
              wordIndex: wIndex, //单词的索引
              pinyin: wItem.pinyin,
              chs: wItem.chs,
              padding: true,
              className: wItem.className,
              isShow: wItem.isShow,
              startIndex: startIndex,
              endIndex: endIndex,
              leg: wItem.chs.length,
              timeList: [],
              words: words
            };
            sentArr.push(obj);
            if (wItem.pinyin) dhaspinyin = true;
          });
          let objs = {
            sentArr: sentArr,
            enwords:
              dItem.sentencesEn &&
              dItem.sentencesEn[sIndex] &&
              dItem.sentencesEn[sIndex].replace(/\'/g, "’")
          };
          sentArrTotal.push(sentArr);
          resArr.push(objs);
        });
        timeArr.push(dItem.timeList);
        dhaspinyinArr.push(dhaspinyin);
      });
      if (wordTimeList && wordTimeList.length > 0) {
        this.mergeWordTime(sentArrTotal, wordTimeList);
      }
      let timeList = [];
      timeArr.forEach(item => {
        item.forEach(aItem => {
          if (timeList.indexOf(aItem) < 0) {
            timeList.push(aItem);
          }
        });
      });
      this.resObj = {
        sentList: resArr,
        timeList: timeList,
        dhaspinyinArr: dhaspinyinArr
      };
    },
    mergeWordTime(resArr, wordTimeList) {
      resArr.forEach((item, index) => {
        let wordsResultList = wordTimeList[index].wordsResultList;
        item.forEach(wItem => {
          let startIndex = wItem.startIndex;
          let endIndex = wItem.endIndex;
          wItem.timeList = wordsResultList.slice(startIndex, endIndex);
        });
      });
    },
    findLightWord(wItem, startIndex, sentence, sItem) {
      let words = "",
        endIndex = 0;
      this.newWordList.forEach(item => {
        if (item.length == 1) {
          if (item == wItem.chs && !wItem.banLight) {
            words = wItem.chs;
            endIndex = startIndex + 1;
          }
        } else {
          if (item[0] == wItem.chs && sentence.indexOf(item) > -1) {
            let index = null;
            let chsStr = "";
            for (let i = startIndex; i < sItem.length + 1; i++) {
              index = i;
              if (chsStr.length == item.length) {
                break;
              } else {
                chsStr += sItem[i] ? sItem[i].chs : "";
              }
            }
            if (chsStr == item && !wItem.banLight) {
              words = item;
              endIndex = index;
            }
          } else if (
            wItem.new_word &&
            wItem.new_word == item &&
            !wItem.banLight
          ) {
            words = item;
            endIndex = startIndex + 1;
          }
        }
      });
      if (words) {
        this.highWords = { words: words, endIndex: endIndex };
      } else {
        this.highWords = null;
      }
    },
    //词和标点合一起
    mergeWordSymbol(wItem) {
      if (this.chsFhList.indexOf(wItem.chs) > -1) {
        wItem.isShow = false;
      } else {
        wItem.isShow = true;
      }
    },
    handleWav(list, tmIndex) {
      tmIndex = tmIndex ? tmIndex : 0;
      this.curQue.Bookanswer.practiceModel[tmIndex] = {
        recordList: []
      };
      this.$set(
        this.curQue.Bookanswer.practiceModel[tmIndex],
        "recordList",
        list
      );
    },
    handleNewword() {
      let NewWordList = [];
      this.NNPENewWordList.forEach(item => {
        item.forEach(wItem => {
          if (wItem.new_word) {
            NewWordList.push(wItem.new_word);
          } else if (wItem.detail && wItem.detail.sentence) {
            NewWordList.push(wItem.detail.sentence);
          }
        });
      });
      this.newWordList = JSON.parse(JSON.stringify(NewWordList));
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    let data = getToken() ? JSON.parse(getToken()) : null;
    this.tokenData = data;
    if (this.NNPENewWordList && this.NNPENewWordList.length > 0) {
      this.handleNewword();
    }
    if (this.curQue) {
      this.handleData();
    }
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    let _this = this;
    // _this.getmp3List();
    if (!_this.curQue.Bookanswer) {
      let userAnswer = JSON.parse(JSON.stringify(_this.userAnswer));
      _this.$set(this.curQue, "Bookanswer", userAnswer);
    }
    if (_this.curQue) {
      _this.$nextTick(() => {
        _this.bodyLeft = _this.$refs.ArticleViewbody.getBoundingClientRect().left;
      });
      for (let i = 0; i < _this.curQue.detail.length; i++) {
        let enStr = this.curQue.detail[i].sentencesEn.join("");
        if (enStr) {
          this.config.isShowEN = true;
          this.config.isHasEN = true;
        }
        let pinyin = this.handleObj(this.curQue.detail[i].wordsList);
        if (pinyin) {
          this.config.isShowPY = true;
          this.config.isHasPY = true;
        }
        if (enStr && pinyin) {
          break;
        }
      }
    }
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang="scss" scoped>
//@import url(); 引入公共css类
.NPC-ArticleView {
  width: 100%;
  &:-webkit-full-screen {
    width: 100%;
    height: 100%;
  }

  &:-moz-full-screen {
    width: 100%;
    height: 100%;
  }
  .ArticleView-full {
    position: absolute;
    top: 0px;
    background: url("../../../../assets/NPC/full-screen-red.png") left center
      no-repeat;
    background-size: 20px 20px;
    padding-left: 24px;
    color: #000000;
    font-size: 16px;
    line-height: 24px;
    font-weight: bold;
    left: 0;
    z-index: 1;
  }
  .ArticleView-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    position: relative;
    .left {
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      font-size: 16px;
      line-height: 24px;
      font-weight: bold;
      img {
        width: 20px;
        height: 20px;
        margin-right: 4px;
      }
    }
    .right {
      display: flex;
    }
    .setting-fontsize {
      display: flex;
      margin-left: 24px;
      a {
        border: 1px solid rgba(0, 0, 0, 0.1);
        box-sizing: border-box;
        border-radius: 4px;
        display: block;
        height: 24px;
        width: 24px;
      }
      img {
        width: 100%;
      }
      > img {
        margin: 0 8px;
        width: 24px;
      }
    }
  }
  .ArticleView-body {
    border: 1px solid rgba(0, 0, 0, 0.1);
    box-sizing: border-box;
    border-radius: 8px;
    background: #fff;
    box-sizing: border-box;
    .aduioLine-box {
      border-bottom: 1px solid rgba(0, 0, 0, 0.1);
      width: 100%;
    }
  }
}
</style>
<style lang="scss">
.NNPE-tableList-item-noMargin {
  .NPC-ArticleView {
    background: #fff;
  }
}
.NPC-ArticleView {
  &.NPC-ArticleView-container {
    margin-bottom: 24px;
  }
  .notice {
    font-weight: normal;
    font-size: 14px;
    line-height: 150%;
    margin-bottom: 24px;
    color: #000000;
    padding: 0 24px 8px;
    margin: 0;
    word-break: break-word;
    &.hasRemark {
      width: 553px;
      box-sizing: border-box;
      border-right: 1px rgba(0, 0, 0, 0.1) solid;
    }
  }
  .ArticleView-header {
    .el-switch {
      margin-left: 24px;
    }
    .el-switch__core {
      width: 44px !important;
      height: 24px;
      border-radius: 20px;
    }
    .el-switch__core:after {
      top: 3px;
      left: 3px;
    }
    .el-switch.is-checked .el-switch__core::after {
      left: 100%;
      margin-left: -19px;
    }
    .el-switch__label {
      color: #000000;
    }
    .el-switch__label.is-active {
      color: rgba($color: #000000, $alpha: 0.3);
    }
    .el-switch__label--left {
      margin-right: 8px;
    }
  }
}
</style>
