<!-- eslint-disable vue/no-v-html -->
<template>
  <div v-if="show_preview" class="choosetone-preview">
    <div class="stem">
      <span class="question-number" :style="{ fontSize: data.property.stem_question_number_font_size }">
        {{ questionNumberEndIsBracket(data.property.question_number) }}
      </span>
      <span v-html="sanitizeHTML(data.stem)"></span>
    </div>
    <div
      v-if="isEnable(data.property.is_enable_description)"
      class="description rich-text"
      v-html="sanitizeHTML(data.description)"
    ></div>
    <div class="option-list">
      <li v-for="(item, i) in data.option_list" :key="i" :class="['option-item']">
        <span :style="{ fontSize: data.property.option_question_number_font_size }">
          {{ computeOptionMethods[data.option_number_show_mode](i) }}
        </span>
        <AudioPlay v-if="item.audio_file_id" :file-id="item.audio_file_id" :show-slider="true" />
        <div
          class="option-content"
          :class="[isJudgingRightWrong ? (con_preview[i].all_right ? 'all-right' : 'has-error') : '']"
        >
          <span v-if="item.content_hz" class="items-hz">{{ item.content_hz }}</span>
          <template v-if="data.property.answer_mode === 'select'">
            <span
              v-for="(itemc, indexc) in con_preview[i].item_con"
              :key="indexc"
              :class="[
                'item-con',
                active_index_str === i + '-' + indexc ? 'active' : '',
                isJudgingRightWrong && !con_preview[i].user_answer[indexc].is_right ? 'error' : '',
              ]"
              @click="
                con_preview[i].item_active_index = indexc;
                active_index_str = i + '-' + indexc;
              "
            >
              {{ itemc }}
            </span>
          </template>
          <template v-else>
            <span v-for="(itemc, indexc) in con_preview[i].item_con" :key="indexc" class="items-box">
              <span
                v-for="(itemi, indexi) in itemc"
                :key="indexi"
                :class="[
                  'items-con',
                  active_index_str === i + '-' + indexc + '-' + indexi ? 'active' : '',
                  isJudgingRightWrong &&
                  !con_preview[i].user_answer[indexc].is_right &&
                  con_preview[i].user_answer[indexc].select_index_submit === indexi
                    ? 'error'
                    : '',
                  isJudgingRightWrong &&
                  !con_preview[i].user_answer[indexc].is_right &&
                  con_preview[i].user_answer[indexc].right_index === indexi
                    ? 'right'
                    : '',
                ]"
                @click="handleSelectItemTone(i, indexc, indexi, con_preview[i].item_con_yuan[indexc][indexi])"
                >{{ itemi }}</span
              >
            </span>
          </template>
        </div>
        <span
          v-for="({ img, value }, j) in toneList"
          :key="j"
          :class="[
            'tone',
            data.property.answer_mode === 'select' &&
            con_preview[i].user_answer[con_preview[i].item_active_index] &&
            con_preview[i].user_answer[con_preview[i].item_active_index].select_tone === value
              ? 'active'
              : data.property.answer_mode === 'label' &&
                  con_preview[i].user_answer[con_preview[i].item_active_index] &&
                  con_preview[i].user_answer[con_preview[i].item_active_index].select_tone === value &&
                  con_preview[i].user_answer[con_preview[i].item_active_index].select_letter === active_letter &&
                  select_item_index === i
                ? 'active'
                : '',
            (isJudgingRightWrong &&
              con_preview[i].user_answer[con_preview[i].item_active_index].right_answer === value &&
              con_preview[i].user_answer[con_preview[i].item_active_index].select_index_submit !==
                con_preview[i].user_answer[con_preview[i].item_active_index].right_answer &&
              data.property.answer_mode === 'select') ||
            (isJudgingRightWrong &&
              data.property.answer_mode === 'label' &&
              con_preview[i].user_answer[con_preview[i].item_active_index].right_answer === value &&
              con_preview[i].user_answer[con_preview[i].item_active_index].right_index ===
                con_preview[i].user_answer[con_preview[i].item_active_index].select_index &&
              select_item_index === i)
              ? 'right'
              : '',
          ]"
          @click="chooseTone(con_preview[i], value, i)"
        >
          <SvgIcon :icon-class="img" />
        </span>
      </li>
    </div>
    <div class="answer-tips-box">
      <img
        v-if="show_tips && data.property.answer_mode === 'label'"
        class="answer-tips"
        src="../../../assets/select-tone-tips.png"
      />
      <img
        v-if="show_tips && data.property.answer_mode === 'select'"
        class="answer-tips"
        src="../../../assets/select-tone-tips-2.png"
      />
      <span :class="['tips-btn', show_tips ? 'tips-btn-active' : '']" @click="show_tips = !show_tips">
        <img src="../../../assets/tips-icon.png" />
      </span>
    </div>

    <div v-if="isEnable(data.property.is_enable_analysis) && isShowRightAnswer" class="analysis">
      <span class="analysis-title">解析</span>
      <div class="analysis-content" v-html="sanitizeHTML(data.analysis)"></div>
    </div>
  </div>
</template>

<script>
import { computeOptionMethods } from '@/views/exercise_questions/data/common';
import PreviewMixin from './components/PreviewMixin';

export default {
  name: 'ChooseTonePreview',
  mixins: [PreviewMixin],
  data() {
    return {
      computeOptionMethods,
      toneList: [
        { value: '1', label: '一声', img: 'first-tone' },
        { value: '2', label: '二声', img: 'second-tone' },
        { value: '3', label: '三声', img: 'third-tone' },
        { value: '4', label: '四声', img: 'fourth-tone' },
        // { value: '0', label: '轻声', img: 'neutral-tone' },
      ],
      con_preview: [],
      tone_data: [
        ['ā', 'á', 'ǎ', 'à', 'a'],
        ['ō', 'ó', 'ǒ', 'ò', 'o'],
        ['ē', 'é', 'ě', 'è', 'e'],
        ['ī', 'í', 'ǐ', 'ì', 'i'],
        ['ū', 'ú', 'ǔ', 'ù', 'u'],
        ['ǖ', 'ǘ', 'ǚ', 'ǜ', 'ü'],
        ['ǖ', 'ǘ', 'ǚ', 'ǜ', 'ü'],
        ['Ā', 'Á', 'Â', 'À', 'A'],
        ['Ō', 'Ó', 'Ô', 'Ò', 'O'],
        ['Ē', 'É', 'Ê', 'È', 'E'],
        ['Ī', 'Í', 'Î', 'Ì', 'I'],
        ['Ū', 'Ú', 'Û', 'Ù', 'U'],
      ],
      final_con: '',
      active_index_str: '', // 高亮索引的字符串
      active_letter: '', // 选中字母的值
      active_letter_index: 0, // 选择字母索引
      select_item_index: 0, // 小题索引
      show_tips: false, // 是否显示答题提示
      show_preview: false,
    };
  },
  watch: {
    data: {
      handler(val) {
        if (!val || this.data.type !== 'choose_tone') return;
        this.handleData();
      },
      deep: true,
      immediate: true,
    },
    isJudgingRightWrong: {
      handler(val) {
        if (!val) return;
        this.judgeRight();
      },
      immediate: true,
    },
  },
  created() {
    // this.handleData();
  },
  methods: {
    chooseTone(item, value, i) {
      if (this.disabled) return;
      if ((!this.active_letter || this.select_item_index !== i) && this.data.property.answer_mode === 'label') return;
      item.user_answer[item.item_active_index].select_tone = value;
      if (this.data.property.answer_mode === 'label') {
        item.user_answer[item.item_active_index].select_letter = this.active_letter;
        this.active_index_str = `${i}-${item.item_active_index}-${this.active_letter_index}`;
        this.handleReplaceTone(this.active_letter + value);
        setTimeout(() => {
          let new_con = item.item_con_yuan[item.item_active_index].split(this.active_letter);
          item.item_con[item.item_active_index] = new_con[0] + this.final_con + new_con[1];
          this.$forceUpdate();
          this.answer.answer_list[i].value[item.item_active_index] =
            new_con[0] + this.active_letter + value + new_con[1];
        }, 100);
      } else {
        this.active_index_str = `${i}-${item.item_active_index}`;
        this.handleReplaceTone(item.item_con_yuan[item.item_active_index] + value);
        setTimeout(() => {
          item.item_con[item.item_active_index] = this.final_con;
          this.$forceUpdate();
        }, 100);
        this.answer.answer_list[i].value[item.item_active_index] = value;
      }
    },
    // 处理数据
    handleData() {
      this.con_preview = [];
      this.show_preview = false;
      if (!this.isJudgingRightWrong) {
        this.answer.answer_list = [];
      }
      this.data.option_list.forEach((item) => {
        let con_arr = JSON.parse(JSON.stringify(item.content_view));
        let user_answer = [];
        let user_submit = []; // 用户提交答案
        con_arr.forEach((items) => {
          user_answer.push({
            select_tone: null,
            select_letter: '',
            select_index: '',
          });
          user_submit.push(this.data.property.answer_mode === 'label' ? items : '');
        });
        let obj = {
          item_con: con_arr,
          item_con_yuan: JSON.parse(JSON.stringify(con_arr)),
          mark: item.mark,
          user_answer,
          item_active_index: 0,
          active_letter: '',
        };
        if (!this.isJudgingRightWrong) {
          let obj = {
            mark: item.mark,
            value: user_submit,
          };
          this.answer.answer_list.push(obj);
        }
        this.con_preview.push(obj);
      });
      this.show_preview = true;
    },
    handleReplaceTone(e, arr, index, resArr) {
      this.$nextTick(() => {
        let value = e;
        this.resArr = [];
        if (value) {
          let reg = /\s+/g;
          let valueArr = value.split(reg);
          valueArr.forEach((item) => {
            this.handleValue(item, resArr);
          });
          let str = '';
          setTimeout(() => {
            if (resArr) {
              resArr.forEach((item) => {
                str += ' ';
                item.forEach((sItem) => {
                  if (sItem.number && sItem.con) {
                    let number = Number(sItem.number);
                    let con = sItem.con;
                    let word = this.addTone(number, con);
                    str += word;
                  } else if (sItem.number) {
                    str += sItem.number;
                  } else if (sItem.con) {
                    str += ` ${sItem.con} `;
                  }
                });
              });
              if (this.data.property.answer_mode === 'label') {
                let number_index = e.search(/0|1|2|3|4/) + 1;
                arr[index] = str.trim() + (number_index === 0 ? '' : e.substring(number_index));
              } else {
                arr[index] = str.trim();
              }
            } else {
              this.resArr.forEach((item) => {
                str += ' ';
                item.forEach((sItem) => {
                  if (sItem.number && sItem.con) {
                    let number = Number(sItem.number);
                    let con = sItem.con;
                    let word = this.addTone(number, con);
                    str += word;
                  } else if (sItem.number) {
                    str += sItem.number;
                  } else if (sItem.con) {
                    str += ` ${sItem.con} `;
                  }
                });
              });
              this.final_con = str.trim();
            }
          }, 10);
        }
      });
    },
    handleValue(valItem, resArr) {
      let reg = /\d/;
      let reg2 = /[A-Za-zü]+\d/g;
      let numList = [];
      let valArr = valItem.split('');
      if (reg2.test(valItem)) {
        for (let i = 0; i < valArr.length; i++) {
          let item = valItem[i];
          if (reg.test(item)) {
            let numIndex = numList.length === 0 ? 0 : numList[numList.length - 1].index;
            let con = valItem.substring(numIndex, i);
            con = con.replace(/\d/g, '');
            let obj = {
              index: i,
              number: item,
              con,
              isTran: true,
            };
            numList.push(obj);
          }
        }
      } else {
        numList = [];
      }
      if (resArr) {
        if (numList.length === 0) {
          resArr.push([{ con: valItem }]);
        } else {
          resArr.push(numList);
        }
      } else if (numList.length === 0) {
        this.resArr.push([{ con: valItem }]);
      } else {
        this.resArr.push(numList);
      }
    },
    addTone(number, con) {
      let zmList = ['a', 'o', 'e', 'i', 'u', 'v', 'ü', 'A', 'O', 'E', 'I', 'U'];
      let cons = con;
      if (number) {
        for (let i = 0; i < zmList.length; i++) {
          let zm = zmList[i];
          if (con.indexOf(zm) > -1) {
            let zm2 = this.tone_data[i][number - 1];
            if (con.indexOf('iu') > -1) {
              zm2 = this.tone_data[4][number - 1];
              cons = con.replace('u', zm2);
            } else if (con.indexOf('ui') > -1) {
              zm2 = this.tone_data[3][number - 1];
              cons = con.replace('i', zm2);
            } else if (
              con.indexOf('yv') > -1 ||
              con.indexOf('jv') > -1 ||
              con.indexOf('qv') > -1 ||
              con.indexOf('xv') > -1
            ) {
              zm2 = this.tone_data[4][number - 1];
              cons = con.replace('v', zm2);
            } else {
              cons = con.replace(zm, zm2);
            }

            break;
          }
        }
      }
      return cons;
    },
    handleSelectItemTone(i, indexc, indexi, itemi) {
      this.con_preview[i].item_active_index = indexc;
      this.con_preview[i].user_answer[indexc].select_index = indexi;
      this.active_index_str = `${i}-${indexc}-${indexi}`;
      this.active_letter = itemi;
      this.active_letter_index = indexi;
      this.select_item_index = i;
    },
    // 判断对错
    judgeRight() {
      this.con_preview = [];
      this.show_preview = false;
      this.data.option_list.forEach((item, index) => {
        let con_arr = JSON.parse(JSON.stringify(item.content_view));
        let user_answer = [];
        let user_select = [];
        let user_res_arr = [];
        con_arr.forEach((items, indexs) => {
          user_answer.push({
            select_tone: this.answer.answer_list[index].value[indexs],
            select_letter: '',
            select_index: '',
            is_right:
              this.answer.answer_list[index].value[indexs] === this.data.answer.answer_list[index].value[indexs],
            right_answer: this.data.answer.answer_list[index].value[indexs],
          });
          user_res_arr.push([]);
          user_select.push('');
          if (this.data.property.answer_mode === 'label') {
            this.handleReplaceTone(
              this.answer.answer_list[index].value[indexs],
              user_select,
              indexs,
              user_res_arr[indexs],
            );
            if (
              this.answer.answer_list[index].value[indexs].match(/\d+/g) &&
              this.answer.answer_list[index].value[indexs].match(/\d+/g).length > 0
            ) {
              user_answer[indexs].select_tone = this.answer.answer_list[index].value[indexs].match(/\d+/g)[0];
              let letter_number = this.answer.answer_list[index].value[indexs].match(/\d+/g)[0];
              let letter_index = this.answer.answer_list[index].value[indexs].indexOf(letter_number) - 1;
              user_answer[indexs].select_letter = this.answer.answer_list[index].value[indexs].substring(
                letter_index,
                letter_index + 1,
              );
              user_answer[indexs].select_index_submit = letter_index;
            } else {
              user_select[indexs] = items;
            }
            user_answer[indexs].right_answer = this.data.answer.answer_list[index].value[indexs].match(/0|1|2|3|4/)
              ? this.data.answer.answer_list[index].value[indexs].match(/0|1|2|3|4/)[0]
              : '';
            user_answer[indexs].right_index = this.data.answer.answer_list[index].value[indexs].search(/0|1|2|3|4/) - 1;
          } else {
            this.handleReplaceTone(
              items + this.answer.answer_list[index].value[indexs],
              user_select,
              indexs,
              user_res_arr[indexs],
            );
          }
        });
        let obj = {
          item_con: user_select,
          item_con_yuan: JSON.parse(JSON.stringify(con_arr)),
          mark: item.mark,
          user_answer,
          item_active_index: 0,
          active_letter: '',
          user_res_arr,
          all_right:
            JSON.stringify(this.answer.answer_list[index].value) ===
            JSON.stringify(this.data.answer.answer_list[index].value),
        };
        this.con_preview.push(obj);
      });
      setTimeout(() => {
        this.show_preview = true;
      }, 100);
    },
  },
};
</script>

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

.choosetone-preview {
  @include preview;

  position: relative;
  min-height: 450px;

  .option-list {
    .option-item {
      display: flex;
      column-gap: 16px;
      align-items: center;
      width: 100%;
      margin-bottom: 16px;

      .option-content {
        padding: 10px 22px;
        color: #706f78;
        background-color: $content-color;
        border: 1px solid $content-color;
        border-radius: 40px;

        &.all-right {
          background-color: $right-bc-color;
          border-color: $right-bc-color;
        }

        &.has-error {
          border-color: $error-color;
        }
      }

      .items-hz {
        margin-right: 4px;
        font-size: 16px;
        font-weight: 500;
        line-height: 24px;
        color: #000;
      }

      .item-con,
      .items-con {
        font-family: 'League';
        font-weight: 500;
        color: #000;
        cursor: pointer;

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

        &.error {
          color: $error-color;
        }

        &.active {
          color: #2f6fec;
        }
      }

      .items-box {
        margin-right: 3px;
      }

      .tone {
        width: 32px;
        height: 32px;
        padding: 8px;
        font-size: 0;
        color: #9f9f9f;
        text-align: center;
        cursor: pointer;

        &.right {
          color: $right-color;
          background-color: $right-bc-color;
          border-radius: 16px;
        }

        &.active {
          color: #2f6fec;
          background: #dfe9fd;
          border-radius: 16px;
        }
      }
    }
  }

  .answer-tips-box {
    position: absolute;
    top: 24px;
    right: 24px;
    display: flex;

    .answer-tips {
      width: 307px;
      margin-top: 32px;
    }

    .tips-btn {
      width: 34px;
      height: 34px;
      padding: 5px;
      font-size: 0;
      background: #fff5e3;
      border: 1px solid rgba(0, 0, 0, 8%);
      border-radius: 8px;

      &-active {
        background: #e3d5b3;
      }

      img {
        width: 22px;
        height: 22px;
        cursor: pointer;
      }
    }
  }
}
</style>
