<!-- eslint-disable vue/no-v-html -->
<template>
  <div class="imageText-preview" :style="[getAreaStyle(), getComponentStyle()]">
    <SerialNumberPosition v-if="isEnable(data.property.sn_display_mode)" :property="data.property" />
    <template v-if="data.mp3_list && data.mp3_list.length > 0 && mp3_url">
      <AudioLine
        ref="audioLine"
        audio-id="Audio"
        :mp3="mp3_url"
        :get-cur-time="getCurTime"
        :duration="data.mp3_list[0].media_duration"
        :mp3-source="data.mp3_list[0].source"
        :width="audio_width"
        :ed="ed"
        type="audioLine"
        :attrib="data.unified_attrib"
        @emptyEd="emptyEd"
      />
    </template>
    <div
      v-if="image_url"
      class="img-box"
      :style="{
        background: 'url(' + image_url + ') center / contain no-repeat',
        width: isMobile ? '100%' : data.image_width + 'px',
        height: data.image_height + 'px',
      }"
    >
      <div
        v-for="(itemP, indexP) in data.text_list"
        :key="'text' + indexP"
        :class="['position-item', sentIndex === indexP ? 'active' : '']"
        :style="{
          width: itemP.width,
          height: itemP.height,
          left: itemP.x,
          top: itemP.y,
        }"
        @click="handleChangePosition(indexP)"
      ></div>
      <div
        v-for="(itemP, indexP) in data.input_list"
        :key="'input' + indexP"
        :class="['position-item position-item-input', 'active', ...computedAnswerClass(indexP)]"
        :style="{
          width: itemP.width,
          height: itemP.height,
          left: itemP.x,
          top: itemP.y,
        }"
      >
        <el-input
          v-model="answer.answer_list[indexP].text"
          :disabled="disabled"
          type="textarea"
          style="height: 100%"
          :placeholder="convertText('请输入')"
        />
      </div>
    </div>
    <PreviewOperation
      v-if="data.input_list.length > 0"
      @showAnswerAnalysis="showAnswerAnalysis"
      @judgeCorrect="judgeCorrect"
      @retry="retry"
    />
    <AnswerCorrect
      :answer-correct="data?.answer_correct"
      :visible.sync="visibleAnswerCorrect"
      :is-check-correct="isCheckCorrect"
      @closeAnswerCorrect="closeAnswerCorrect"
    />
    <AnswerAnalysis
      :visible.sync="visibleAnswerAnalysis"
      :answer-list="data.answer_list"
      :analysis-list="data.analysis_list"
      @closeAnswerAnalysis="closeAnswerAnalysis"
    >
      <div slot="right-answer" class="right-answer">
        <div
          v-if="image_url"
          class="img-box"
          :style="{
            background: 'url(' + image_url + ') center / contain no-repeat',
            width: data.image_width + 'px',
            height: data.image_height + 'px',
          }"
        >
          <div
            v-for="(itemP, indexP) in data.input_list"
            :key="'input' + indexP"
            :class="['position-item position-item-input', 'active']"
            :style="{
              width: itemP.width,
              height: itemP.height,
              left: itemP.x,
              top: itemP.y,
            }"
          >
            <el-input
              v-model="itemP.text"
              :disabled="disabled"
              type="textarea"
              style="height: 100%"
              :placeholder="convertText('请输入')"
            />
          </div>
        </div>
      </div>
    </AnswerAnalysis>

    <el-dialog
      v-if="mageazineDetailShow"
      :visible.sync="mageazineDetailShow"
      :show-close="false"
      :close-on-click-modal="false"
      :width="isMobile ? '100%' : '80%'"
      class="login-dialog magazine-detail-dialog"
      :class="[isMobile ? 'magazine-detail-dialog-phone' : '']"
      :modal="false"
    >
      <magazine-sentence
        :font-size="fontSize"
        :sentence-theme="sentenceTheme"
        :data="data.word_time"
        :text-list="data.text_list"
        :active-index="sentIndex"
        :mp3-url="mp3_url"
        :multilingual-text-list="showLang && multilingualTextList[getLang()] ? multilingualTextList[getLang()] : []"
        :property="data.property"
        :attrib="data.unified_attrib"
        @closeWord="closeMagazineSentence"
        @changeTheme="changeTheme"
      />
    </el-dialog>
  </div>
</template>

<script>
import PreviewMixin from '../common/PreviewMixin';
import AudioLine from '../voice_matrix/components/AudioLine.vue';
import { getImageTextData } from '@/views/book/courseware/data/imageText';
import MagazineSentence from './components/MagazineSentence.vue';
export default {
  name: 'ImageTextPreview',
  components: { AudioLine, MagazineSentence },
  mixins: [PreviewMixin],
  props: {
    isMobile: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      data: getImageTextData(),
      curTime: 0,
      paraIndex: -1, // 段落索引
      sentIndex: -1, // 句子索引
      ed: undefined,
      mp3_url: '',
      image_url: '',
      audio_width: 0,
      mageazineDetailIndex: null, // 当前高亮第几个
      mageazineDetailShow: false,
      inputIndex: null,
      fontSize: 20,
      sentenceTheme: 0,
      multilingualTextList: {},
    };
  },
  watch: {
    'data.image_list': {
      handler() {
        this.initData();
      },
    },
  },
  created() {
    this.initData();
  },
  mounted() {
    this.audio_width = document.getElementsByClassName('imageText-preview')[0].clientWidth - 150;
  },
  methods: {
    initData() {
      if (!this.isJudgingRightWrong) {
        this.answer.answer_list = [];
        this.data.input_list.forEach((item) => {
          let obj = {
            text: '',
            answer: item.text,
            id: item.id,
          };
          this.answer.answer_list.push(obj);
        });
      }
      this.data.multilingual.forEach((item) => {
        let trans_arr = item.translation.split('\n');
        this.$set(this.multilingualTextList, item.type, trans_arr);
      });

      this.data.image_list.forEach((item) => {
        this.image_url = item.file_url;
        // GetFileURLMap({ file_id_list: [item.file_id] }).then(({ url_map }) => {
        //   this.image_url = url_map[item.file_id];
        // });
      });
      this.data.mp3_list.forEach((item) => {
        this.mp3_url = item.temporary_url;
        // GetFileURLMap({ file_id_list: [item.file_id] }).then(({ url_map }) => {
        //   this.mp3_url = url_map[item.file_id];
        // });
      });
      if (this.isMobile) {
        setTimeout(() => {
          let totalWidth = document.querySelector('.imageText-preview').offsetWidth;
          let rate = totalWidth / this.data.image_width;
          this.data.image_height *= rate;
          this.data.input_list.forEach((item) => {
            item.width = `${item.width.replace('px', '') * rate}px`;
            item.height = `${item.height.replace('px', '') * rate}px`;
            item.x = `${item.x.replace('px', '') * rate}px`;
            item.y = `${item.y.replace('px', '') * rate}px`;
          });
          this.data.text_list.forEach((item) => {
            item.width = `${item.width.replace('px', '') * rate}px`;
            item.height = `${item.height.replace('px', '') * rate}px`;
            item.x = `${item.x.replace('px', '') * rate}px`;
            item.y = `${item.y.replace('px', '') * rate}px`;
          });
        }, 50);
      }
    },
    /**
     * 计算答题对错选项字体颜色
     * @param {string} mark 选项标识
     */
    computedAnswerClass(i) {
      if (!this.isJudgingRightWrong && !this.isShowRightAnswer) {
        return '';
      }
      let answerOption = this.data.input_list[i] ? this.data.input_list[i].text : '';
      let selectValue = this.answer.answer_list[i].text ? this.answer.answer_list[i].text.trim() : '';
      let classList = [];
      let isRight = answerOption && answerOption === selectValue;
      if (this.isJudgingRightWrong && answerOption) {
        isRight ? classList.push('right') : classList.push('wrong');
      }

      if (this.isShowRightAnswer && !isRight) {
        classList.push('show-right-answer');
      }
      return classList;
    },
    getCurTime(curTime) {
      this.curTime = curTime * 1000;
      this.getSentIndex(this.curTime);
    },
    getSentIndex(curTime) {
      for (let i = 0; i < this.data.word_time.length; i++) {
        let bg = this.data.word_time[i].bg;
        let ed = this.data.word_time[i].ed;
        if (curTime >= bg && curTime <= ed) {
          this.sentIndex = i;
          break;
        }
      }
    },
    emptyEd() {
      this.ed = undefined;
    },
    // 切换画刊里面的卡片
    handleChangePosition(index) {
      if (this.$refs.audioLine && this.$refs.audioLine.audio.playing) {
        this.$refs.audioLine.PlayAudio();
      }
      this.sentIndex = index;
      this.mageazineDetailShow = true;
    },
    // 关闭画刊卡片
    closeMagazineSentence() {
      this.mageazineDetailShow = false;
    },
    // 切换主题色和文字大小
    changeTheme(theme, size) {
      if (theme !== '') this.sentenceTheme = theme;
      if (size) this.fontSize = size;
    },
    // 重做
    retry() {
      this.isJudgingRightWrong = false;
      this.isShowRightAnswer = false;
      this.initData();
    },
    /**
     * 获取无文本内容的数据结构，用于保存为个人模板时的样式模板
     */
    getNoTextContentData() {
      let noTextContentData = JSON.parse(JSON.stringify(this.data));
      const resetFieldMap = {
        mp3_list: [], // 音频列表
        detail: [],
        image_list: [], // 图片列表
        image_info_list: [],
        image_id_list: [], // 文件 id
        image_width: 500, // 图片宽度px
        image_height: 500, // 图片高度px
        text_list: [], // 文字框列表
        input_list: [], // 输入框列表
        file_id_list: [], // 文件 id
        word_time: [], // 时间字幕
        answer_list: [], // 答案列表
        analysis_list: [], // 解析列表
      };

      Object.assign(noTextContentData, resetFieldMap);

      if (noTextContentData.answer) {
        noTextContentData.answer.answer_list = [];
        noTextContentData.answer.reference_answer = '';
      }

      return noTextContentData;
    },
  },
};
</script>

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

.imageText-preview {
  max-width: 100%;
  overflow: auto;
}

.position-item {
  position: absolute;
  z-index: 1;
  font-size: 0;
  cursor: pointer;
  border: 3px solid transparent;

  &.active {
    border-color: #ff1616;
  }

  &:hover {
    border-color: #ff1616;
  }

  &.position-item-input {
    border-color: #f90;

    &.right {
      border-color: $right-color;

      :deep .el-textarea__inner {
        color: $right-color;
      }
    }

    &.wrong {
      border-color: $error-color;

      :deep .el-textarea__inner {
        color: $error-color;
      }
    }
  }

  :deep .el-textarea__inner {
    height: 100%;
    padding: 5px;
    font-family: 'League', '楷体';
    line-height: 1;
    text-align: center;
    resize: none;
    background: transparent;
    border: none;
  }
}

.img-box {
  position: relative;
  margin: 20px auto;
}

.right-answer {
  .title {
    margin: 24px 0;
  }
}

:deep .el-slider {
  flex: 1;
  width: auto !important;
}
</style>
<style lang="scss">
.magazine-detail-dialog {
  .el-dialog__header,
  .el-dialog__body {
    padding: 0;
  }

  .el-dialog {
    position: absolute;
    bottom: 50px;
    left: 50%;
    margin-left: -40%;
    border: none;
    border-radius: 16px;
    box-shadow:
      0 6px 30px 5px rgba(0, 0, 0, 5%),
      0 16px 24px 2px rgba(0, 0, 0, 4%),
      0 8px 10px -5px rgba(0, 0, 0, 8%);
  }

  &-phone {
    .el-dialog {
      margin-left: -50%;
    }
  }
}
</style>
