<!-- eslint-disable vue/no-v-html -->
<template>
  <div class="newWord-preview" :style="getAreaStyle()">
    <SerialNumberPosition v-if="isEnable(data.property.sn_display_mode)" :property="data.property" />

    <div v-if="data" class="main">
      <div class="NPC-zhedie">
        <div class="topTitle">
          <div class="NPC-top-left">
            <span class="NPC-topTitle-text" v-html="data.title_con"></span>
          </div>
          <div class="NPC-top-right" @click="handleChangeTab">
            <span class="NPC-top-right-text">{{ wordShow ? '收起' : '展开' }}</span>
            <img v-if="wordShow" src="@/assets/down.png" alt="" />
            <img v-else class="rotate" src="@/assets/down.png" alt="" />
          </div>
        </div>
        <el-collapse-transition>
          <div v-if="data.option && data.option.length > 0" v-show="wordShow" class="NPC-word-list">
            <div v-if="data.audio_data.file_id" class="aduioLine-box">
              <AudioLine
                ref="audioLine"
                :audio-id="'newWordAudio' + indexStr"
                :mp3="data.audio_data.url"
                :get-cur-time="getCurTime"
                :ed="ed"
                type="audioLine"
                @handleListenRead="handleListenRead"
              />
            </div>
            <ul class="NPC-word-table" cellspacing="0" border="0" cellpadding="0">
              <li v-for="(item, index) in data.option_list" :key="'curQue.option' + index" class="NPC-word-tr">
                <div
                  v-for="(sItem, sIndex) in item"
                  :key="'curQue.option.child' + sIndex"
                  :class="[
                    'NPC-word-row',
                    playClass && mp3_index == sItem.sIndex ? 'active' : '',
                    curTime >= sItem.bg && curTime < sItem.ed && stopAudioS ? 'active' : '',
                  ]"
                >
                  <template v-if="sItem.bg || sItem.ed">
                    <a
                      :class="['play-btn', curTime >= sItem.bg && curTime < sItem.ed && stopAudioS ? 'active' : '']"
                      @click="handleChangeTime(sItem.bg, sItem.ed)"
                    ></a>
                  </template>
                  <template v-else-if="sItem.mp3_list">
                    <span
                      :class="['play-btn', playClass && mp3_index === sItem.sIndex ? 'active' : '']"
                      @click="palyAudio(sItem.mp3_list_url, sItem.sIndex)"
                    ></span>
                    <audio :id="'word' + indexStr + sItem.sIndex" :src="sItem.mp3_list_url"></audio>
                  </template>

                  <template v-else>
                    <span style="width: 16px; height: 16px"></span>
                  </template>
                  <div class="tabNum-box">
                    <template v-if="sItem.mIndex == 0">
                      <b class="tabNum">{{ index + 1 }}</b>
                    </template>
                    <div v-else style="width: 16px; height: 16px; margin-left: 8px"></div>
                  </div>
                  <template v-if="sItem.pinyin_site && (sItem.pinyin_site == 'top' || sItem.pinyin_site == 'bottom')">
                    <div class="NPC-word-tab-box">
                      <span
                        v-if="sItem.pinyin_site == 'top'"
                        class="NPC-word-tab-common NPC-word-tab-pinyin"
                        v-html="sItem.pinyin"
                      >
                      </span>
                      <span class="NPC-word-tab-common NPC-word-tab-word" v-html="sItem.new_word"> </span>
                      <span
                        v-if="sItem.pinyin_site == 'bottom'"
                        class="NPC-word-tab-common NPC-word-tab-pinyin"
                        v-html="sItem.pinyin"
                      >
                      </span>
                    </div>
                    <span
                      class="NPC-word-tab-common NPC-word-tab-cixing"
                      :class="[/[\u4E00-\u9FA5\uF900-\uFA2D]/.test(sItem.cixing) ? 'hasCn' : '']"
                      v-html="sItem.cixing"
                    ></span>
                    <span class="NPC-word-tab-common NPC-word-tab-def" v-html="sItem.def_str"></span>
                  </template>
                  <template v-else>
                    <span
                      v-if="!sItem.pinyin_site || sItem.pinyin_site == 'first'"
                      class="NPC-word-tab-common NPC-word-tab-pinyin"
                      v-html="sItem.pinyin"
                    >
                    </span>
                    <span class="NPC-word-tab-common NPC-word-tab-word" v-html="sItem.new_word"> </span>
                    <span
                      v-if="sItem.pinyin_site == 'last'"
                      class="NPC-word-tab-common NPC-word-tab-pinyin"
                      v-html="sItem.pinyin"
                    >
                    </span>
                    <span
                      class="NPC-word-tab-common NPC-word-tab-cixing"
                      :class="[/[\u4E00-\u9FA5\uF900-\uFA2D]/.test(sItem.cixing) ? 'hasCn' : '']"
                      v-html="sItem.cixing"
                    ></span>
                    <span class="NPC-word-tab-common NPC-word-tab-def" v-html="sItem.def_str"></span>
                  </template>
                  <span>
                    <!-- :answerRecordList="data.answer.answer_list[index][sIndex].recordList" -->
                    <SoundRecord
                      :tm-index="index"
                      :tms-index="sIndex"
                      :task-model="isJudgingRightWrong ? 'ANSWER' : ''"
                      :answer-record-list="[]"
                      type="mini"
                      class="luyin-box-wordphrase"
                      :style="{ marginLeft: '8px' }"
                      @handleWav="handleWav"
                    />
                  </span>
                  <span v-if="isEnable(data.property.is_has_infor)">
                    <img src="@/assets/detail-icon.png" class="detail-icon" @click="showDetail(sItem)" />
                  </span>
                  <div v-if="sItem.collocation" class="collocation">
                    <span>搭配：</span><b v-html="sItem.collocation"></b>
                  </div>
                  <div v-if="sItem.liju_list" class="collocation">
                    <span>例句：</span>
                    <div>
                      <b v-html="sItem.liju_list"></b>
                    </div>
                  </div>
                </div>
              </li>
            </ul>
          </div>
        </el-collapse-transition>
        <div class="practiceBox" v-if="detailShow">
          <WordPhraseDetail
            :data="dataWord"
            :changeDetailIndex="changeDetailIndex"
            :closeWord="closeWordShow"
            :detailIndex="detailIndex"
            :optionRes="optionRes"
            :themeColor="'red'"
            :currentTreeID="courseware_id"
            :bg="dataWord && dataWord.bg ? dataWord.bg : null"
            :ed="dataWord && dataWord.ed ? dataWord.ed : null"
            type="newWordDetail"
          />
        </div>
        <audio ref="newwordAudio"></audio>
      </div>
    </div>
  </div>
</template>

<script>
import { getNewWordData, isEnable } from '@/views/book/courseware/data/newWord';

import PreviewMixin from '../common/PreviewMixin';
import SoundRecord from '../../common/SoundRecord.vue';
import AudioLine from '../voice_matrix/components/AudioLine.vue';
import { GetFileURLMap } from '@/api/app';
import WordPhraseDetail from './components/WordPhraseDetail.vue';

export default {
  name: 'NewWordPreview',
  components: {
    SoundRecord,
    AudioLine,
    WordPhraseDetail,
  },
  mixins: [PreviewMixin],
  inject: ['courseware_id'],
  data() {
    return {
      data: getNewWordData(),
      wordShow: false,
      dataWord: null,
      detailShow: false,
      detailIndex: 0,
      audio: new Audio(),
      playClass: '',
      mp3_index: -1,
      playWord: null,
      optionRes: [],
      isSuccess: false,
      loading: false,
      mp3: '',
      curTime: 0,
      stopAudioS: false,
      ed: null,
      indexStr: Math.random().toString(36).substring(2, 10),
      is_change: false,
    };
  },
  watch: {
    data: {
      handler(val) {
        if (val) {
          if (this.is_change) return;
          if (val.option[0].new_word) {
            this.wordShow = isEnable(this.data.property.is_word_show);
            this.initData();
          }
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    palyAudio(url, sIndex) {
      this.stopAudio();
      let mp3 = url;
      let node = document.getElementById(`word${this.indexStr}${sIndex}`);
      let audio = document.getElementsByTagName('audio');
      if (audio && audio.length > 0 && audio.forEach && window.location.href.indexOf('GCLS-Learn') === -1) {
        audio.forEach((item) => {
          if (item.src !== mp3) {
            item.pause();
          }
        });
      }
      this.playWord = node;
      if (node) {
        this.mp3_index = sIndex;
        node.play();
      }
      this.handleListenPlay(sIndex);
    },
    handleListenPlay(sIndex) {
      let _this = this;
      if (this.playWord) {
        this.playWord.addEventListener('play', function () {
          _this.playClass = 'nn';
        });
        this.playWord.addEventListener('pause', function () {
          _this.mp3_index = -1;
          _this.playClass = '';
        });
        this.playWord.addEventListener('ended', function () {
          _this.mp3_index = -1;
          _this.playClass = '';
        });
      }
    },
    // 打开单词详情
    showDetail(item) {
      this.dataWord = null;
      this.dataWord = item;
      this.detailShow = true;
      this.detailIndex = item.sIndex;
    },

    // 关闭单词详情
    closeWordShow(val) {
      this.detailShow = val;
    },
    changeDetailIndex(val) {
      if (val === 'last') {
        this.detailIndex -= 1;
      } else {
        this.detailIndex += 1;
      }
      this.dataWord = null;
      this.dataWord = this.optionRes[this.detailIndex];
      // this.getWordLiju(this.data.new_word);
    },
    handlePlayVoice3(mp3) {
      let audio = document.getElementsByTagName('audio');
      if (audio && audio.length > 0 && window.location.href.indexOf('GCLS-Learn') == -1) {
        audio.forEach((item) => {
          if (item.src !== mp3) {
            item.pause();
          }
        });
      }
      if (!mp3) {
        return;
      }
      if (!this.audio.paused) {
        this.audio.pause();
      } else {
        this.audio.pause();
        this.audio.load();
        this.audio.src = mp3;
        this.audio.loop = false;
        this.audio.play();
      }
    },
    handlePlayVoice(mp3) {
      let audio = document.getElementsByTagName('audio');
      if (audio && audio.length > 0 && window.location.href.indexOf('GCLS-Learn') == -1) {
        audio.forEach((item) => {
          if (item.src !== mp3) {
            item.pause();
          }
        });
      }
      if (!mp3) {
        return;
      }
      // setTimeout(() => {
      // this.$refs.newwordAudio.pause();
      this.$refs.newwordAudio.src = mp3;
      // this.$refs.newwordAudio.load();
      this.$refs.newwordAudio.play();
      // }, 1000);
    },
    stopAudio() {
      this.$refs.newwordAudio.pause();
    },
    initData() {
      this.is_change = true;
      let resIndex = 0;
      let optionRes = [];
      let itemNumber = 0;
      let Bookanswer = [];
      let option_list = [];
      if (this.data.audio_data.file_id) {
        GetFileURLMap({ file_id_list: [this.data.audio_data.file_id] }).then(({ url_map }) => {
          this.data.audio_data.url = url_map[this.data.audio_data.file_id];
        });
      }
      this.data.option.forEach((item) => {
        if (item.number) {
          option_list.push([item]);
        } else if (option_list[option_list.length - 1]) {
          option_list[option_list.length - 1].push(item);
        } else {
          option_list.push([item]);
        }
        if (item.mp3_list) {
          GetFileURLMap({ file_id_list: [item.mp3_list] }).then(({ url_map }) => {
            this.$set(item, 'mp3_list_url', url_map[item.mp3_list]);
          });
        }
      });
      option_list.forEach((item, index) => {
        optionRes = optionRes.concat(item);
        Bookanswer.push([]);
        item.forEach((sItem, sIndex) => {
          sItem.mIndex = sIndex;
          sItem.sIndex = resIndex;
          resIndex++;
          sItem.def_str = sItem.definition_list;
          if (this.data.lrc_arr && this.data.lrc_arr[itemNumber]) {
            sItem.bg = this.data.lrc_arr[itemNumber].bg;
            sItem.ed = this.data.lrc_arr[itemNumber].ed;
          }
          itemNumber++;
          Bookanswer[index].push({
            recordList: [],
          });
        });
      });
      this.optionRes = JSON.parse(JSON.stringify(optionRes));
      this.$set(this.data, 'option_list', option_list);
      if (!this.isJudgingRightWrong) {
        this.data.answer.answer_list = Bookanswer;
      }
    },
    handleChangeTab() {
      this.wordShow = !this.wordShow;
    },
    getCurTime(curTime) {
      this.curTime = curTime * 1000;
    },
    // 点击播放某个句子
    handleChangeTime(time, edTime) {
      this.curTime = time;
      this.stopAudioS = true;
      this.$refs.audioLine.onTimeupdateTime(time / 1000, true);
      this.ed = edTime;
    },
    handleListenRead(playFlag) {
      this.stopAudioS = playFlag;
    },
    emptyEd() {
      this.ed = null;
    },
    handleWav(list, tmIndex, tmsIndex) {
      tmIndex = tmIndex || 0;
      tmsIndex = tmsIndex || 0;
      this.$set(this.data.answer.answer_list[tmIndex][tmsIndex], 'recordList', list);
    },
  },
};
</script>

<style lang="scss" scoped>
@use '@/styles/mixin.scss' as *;

.newWord-preview {
  @include preview-base;

  .NPC-zhedie {
    width: 780px;
    margin-bottom: 24px;

    .aduioLine-box {
      margin-bottom: 8px;
    }

    .practiceBox {
      position: fixed;
      top: 0;
      left: 0;
      z-index: 999;
      box-sizing: border-box;
      width: 100%;
      height: 100vh;
      overflow: hidden;
      overflow-y: auto;
      background: rgba(0, 0, 0, 19%);
    }

    .NPC-word-list {
      background: #f7f7f7;
    }

    .NPC-word-table {
      width: 100%;

      :deep p {
        margin: 0;
      }

      > .NPC-word-tr {
        margin-bottom: 8px;
        background: #fff;
        border-radius: 8px;

        .NPC-word-row {
          display: flex;
          flex-flow: wrap;
          justify-content: flex-start;
          padding: 8px 13px 8px 12px;
          cursor: pointer;
          border-radius: 8px;

          &.active {
            background: linear-gradient(0deg, rgba(0, 0, 0, 8%), rgba(0, 0, 0, 8%)), #fff;
          }

          > span {
            font-size: 16px;
            line-height: 150%;
            color: #000;
          }
        }

        .tabNum-box {
          position: relative;

          .star-label {
            position: absolute;
            top: 1px;
            right: -6px;
            width: 6px;
            height: 6px;
          }
        }

        .play-btn {
          display: block;
          width: 16px;
          height: 16px;
          margin-top: 4px;
          background: url('@/assets/fill/voice-pause-red.png') no-repeat left top;
          background-size: 100% 100%;

          &.active {
            background: url('@/assets/fill/voice-play-red.png') no-repeat left top;
            background-size: 100% 100%;
          }
        }

        .tabNum {
          display: block;
          width: 16px;
          height: 16px;
          margin-top: 4px;
          margin-left: 8px;
          font-family: 'robot', 'alabo';
          font-size: 12px;
          line-height: 16px;
          color: #fff;
          text-align: center;
          background: #de4444;
          border-radius: 50%;
        }

        .NPC-word-tab-box {
          width: 240px;

          span {
            display: block;
            width: 100%;
            margin: 2px 0;
            color: #000;
          }
        }

        .NPC-word-tab-common {
          box-sizing: border-box;
          width: 125px;
          padding-left: 8px;
        }

        .NPC-word-tab-pinyin {
          font-family: 'League';

          // white-space: nowrap;
          font-size: 12px;
          word-break: break-word;

          &.NPC-word-tab-pinyin-red {
            color: #e35454;
          }

          &.NPC-word-tab-pinyin-green {
            color: #24b99e;
          }

          &.NPC-word-tab-pinyin-brown {
            color: #bd8865;
          }
        }

        .NPC-word-tab-word {
          font-family: '楷体';
          font-size: 16px;
          white-space: nowrap;

          &.NPC-word-tab-word-red {
            color: #e35454;
          }

          &.NPC-word-tab-word-green {
            color: #24b99e;
          }

          &.NPC-word-tab-word-brown {
            color: #bd8865;
          }

          &-break {
            word-break: break-word;
            white-space: normal;
          }
        }

        .NPC-word-tab-cixing {
          box-sizing: border-box;

          // width: 48px;
          width: 60px;
          font-family: 'robot', 'alabo';
          text-align: left;
          word-break: break-word;

          // font-style: italic;  // 要求改为正体
          &.NPC-word-tab-cixing-red {
            color: #e35454;
          }

          &.NPC-word-tab-cixing-green {
            color: #24b99e;
          }

          &.NPC-word-tab-cixing-brown {
            color: #bd8865;
          }

          &.hasCn {
            font-size: 13px;
          }
        }

        .NPC-word-tab-def {
          box-sizing: border-box;
          flex: 1;
          font-family: 'robot', 'alabo';
          word-break: break-word;
          white-space: pre-wrap;

          &.NPC-word-tab-def-red {
            color: #e35454;
          }

          &.NPC-word-tab-def-green {
            color: #24b99e;
          }

          &.NPC-word-tab-def-brown {
            color: #bd8865;
          }
        }

        .collocation {
          display: flex;
          width: 100%;
          padding-top: 8px;

          > span {
            flex-shrink: 0;
            font-size: 16px;
            font-weight: 400;
            line-height: 24px;
            color: #000;
          }

          > div b {
            display: block;
          }

          > b,
          > div b {
            flex: 1;
            font-family: 'robot', '楷体', 'alabo';
            font-size: 16px;
            font-weight: 400;
            line-height: 24px;
            color: rgba(0, 0, 0, 65%);
          }
        }
      }
    }

    .NPC-word-list {
      padding: 20px 24px;
      border: 1px solid rgba(0, 0, 0, 10%);
      border-top: none;
      border-radius: 0 0 8px 8px;
    }

    .detail-icon {
      display: block;
      width: 24px;
      height: 24px;
      cursor: pointer;
      opacity: 0.5;
    }
  }

  @keyframes firstrotate {
    0% {
      transform: rotateZ(0deg);
    }

    100% {
      transform: rotateZ(180deg);
    }
  }

  @keyframes huifuRotate {
    0% {
      transform: rotateZ(180deg);
    }

    100% {
      transform: rotateZ(0deg);
    }
  }

  .luyin-box-wordphrase {
    height: 24px;
  }
}
</style>
<style lang="scss">
.NPC-zhedie {
  .topTitle {
    display: flex;
    justify-content: space-between;
    width: 100%;
    height: 48px;
    padding-right: 16px;
    padding-left: 24px;
    overflow: hidden;
    background: #e35454;
    border: 1px solid rgba(0, 0, 0, 10%);
    border-radius: 8px 8px 0 0;

    .NPC-top-left {
      display: flex;
      align-items: center;
      justify-content: flex-start;

      .NPC-topTitle-text {
        margin-right: 8px;
        font-family: 'sourceR';
        font-size: 16px;
        font-weight: bold;
        color: #fff;
        white-space: pre;
      }
    }

    .NPC-top-right {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      cursor: pointer;

      &-text {
        font-size: 14px;
        font-weight: normal;
        line-height: 16px;
        color: #fff;
      }

      img {
        width: 16px;
        height: 16px;
        margin-left: 4px;
      }
    }

    img {
      width: 24px;
      height: 24px;
    }

    .rotate {
      animation-name: firstrotate;
      animation-timing-function: linear;
      animation-direction: 2s;
      animation-fill-mode: both;
    }
  }

  .topTitleWhite {
    display: flex;
    justify-content: space-between;
    width: 100%;
    height: 48px;
    padding-right: 16px;
    padding-left: 24px;
    overflow: hidden;
    background: #fff;
    border: 1px solid rgba(0, 0, 0, 10%);
    border-radius: 8px 8px 0 0;

    .NPC-top-left {
      display: flex;
      align-items: center;
      justify-content: flex-start;

      .NPC-topTitle-text {
        margin-right: 8px;
        font-family: 'sourceR';
        font-size: 16px;
        font-weight: bold;
        color: #000;
      }
    }

    .NPC-top-right {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      cursor: pointer;

      &-text {
        font-size: 14px;
        font-weight: normal;
        line-height: 16px;
        color: #000;
      }

      img {
        width: 16px;
        height: 16px;
        margin-left: 4px;
      }
    }

    img {
      width: 24px;
      height: 24px;
    }

    .rotate {
      animation-name: firstrotate;
      animation-timing-function: linear;
      animation-direction: 2s;
      animation-fill-mode: both;
    }
  }

  .el-collapse-item__content {
    padding-bottom: 0;
  }

  .el-slider__button {
    width: 8px;
    height: 8px;
  }

  .el-slider__runway {
    padding: 0;
    margin: 0;
  }

  .el-slider {
    position: relative;

    // top: -3px;
  }

  .el-collapse {
    box-sizing: border-box;
    background: #f7f7f7;
    border-radius: 8px;
  }

  .el-collapse-item__wrap {
    background: #f7f7f7;
    border: 1px solid rgba(0, 0, 0, 10%);
    border-top: 0;
    border-radius: 0 0 8px 8px;
  }

  .el-collapse-item__arrow {
    display: none;
  }

  .el-table__row {
    padding: 4px 0;
  }
}
</style>
