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

    <div class="main">
      <div
        class="table-box"
        :style="{
          width: isMobile ? '100%' : data.property.width + 'px',

          height: data.property.height + 'px',
        }"
      >
        <table
          :style="{
            width: isMobile ? '100%' : table_width + 'px',

            height: data.property.height + 'px',
          }"
        >
          <colgroup>
            <col v-for="(item, i) in data.col_width" :key="`col-${i}`" :style="{ width: `${item.value}px` }" />
          </colgroup>
          <tr v-for="(row, i) in data.option_list" :key="`tr-${i}`">
            <template v-for="(col, j) in row">
              <td
                :key="col.mark"
                :style="{
                  borderTop: i === 0 ? '1px solid ' + data.property.border_color : '',
                  borderBottom: '1px solid ' + data.property.border_color,
                  borderLeft:
                    i === 0 && data.property.first_line_color
                      ? '1px solid ' + data.property.border_color
                      : j === 0
                        ? '2px solid ' + data.property.decoration_color
                        : '1px dotted ' + data.property.border_color,
                  borderRight:
                    i === 0 && data.property.first_line_color
                      ? '1px solid ' + data.property.border_color
                      : j === row.length - 1
                        ? '2px solid ' + data.property.decoration_color
                        : '1px dotted ' + data.property.border_color,
                  borderRadius: i === 0 && data.property.first_line_color ? '4px ' : '0',
                  background:
                    i === 0 && data.property.first_line_color
                      ? data.property.first_line_color
                      : j === 0
                        ? data.property.first_column_color
                        : data.mode === 'short' && data.styles.bgColor
                          ? data.styles.bgColor
                          : '',
                }"
              >
                <div :style="[tdStyle, computedRichStyle(col.content)]" class="cell-wrap">
                  <template v-if="isEnable(data.property.view_pinyin)">
                    <div
                      v-for="(item, index) in col.model_pinyin"
                      :key="index"
                      class="pinyin-text"
                      :class="[index === 0 ? 'pinyin-text-left' : '']"
                    >
                      <template v-if="item.type === 'input'">
                        <template v-if="data.property.fill_type === fillTypeList[0].value">
                          <el-input
                            :key="index"
                            v-model="item.value"
                            :disabled="disabled"
                            :class="[...computedAnswerClass(item, i, j)]"
                            :style="[{ width: Math.max(40, item.value.length * 21.3) + 'px' }]"
                          />
                        </template>
                        <template v-else-if="data.property.fill_type === fillTypeList[1].value">
                          <el-popover :key="index" placement="top" trigger="click">
                            <div class="word-list">
                              <span
                                v-for="{ content, mark } in data.word_list"
                                :key="mark"
                                class="word-item"
                                @click="handleSelectWord(content, mark, item)"
                              >
                                {{ content }}
                              </span>
                            </div>

                            <el-input
                              slot="reference"
                              v-model="item.value"
                              :readonly="true"
                              :class="[...computedAnswerClass(item, i, j)]"
                              :style="[{ width: Math.max(40, item.value.length * 21.3) + 'px' }]"
                            />
                          </el-popover>
                        </template>

                        <template v-else-if="data.property.fill_type === fillTypeList[2].value">
                          <span :key="j" class="write-click" @click="handleWriteClick(item)">
                            <img
                              v-show="item.write_base64"
                              style="background-color: #f4f4f4"
                              :src="item.write_base64"
                              alt="write-show"
                            />
                          </span>
                        </template>

                        <template v-else-if="data.property.fill_type === fillTypeList[3].value">
                          <SoundRecordBox
                            ref="record"
                            :key="j"
                            type="mini"
                            :many-times="false"
                            class="record-box"
                            :answer-record-list="data.audio_answer_list"
                            :task-model="isJudgingRightWrong ? 'ANSWER' : ''"
                            :attrib="data.unified_attrib"
                            @handleWav="handleMiniWav($event, item)"
                          />
                        </template>
                        <span v-if="data.property.pinyin_position === 'bottom'" class="pinyin">&nbsp;</span>
                      </template>
                      <template v-else>
                        <span v-if="data.property.pinyin_position === 'top'" class="pinyin">
                          {{ item.pinyin.replace(/\s+/g, '') }}
                        </span>
                        <span :style="{ ...item.activeTextStyle }">
                          {{ item.text }}
                        </span>
                        <span v-if="data.property.pinyin_position === 'bottom'" class="pinyin">{{
                          item.pinyin.replace(/\s+/g, '')
                        }}</span>
                      </template>
                    </div>
                  </template>
                  <template v-else>
                    <div v-for="(item, index) in col.model_essay" :key="index" :style="[tdStyle]">
                      <span
                        v-if="item.type === 'text'"
                        :key="index"
                        :style="{
                          fontSize:
                            data.unified_attrib && data.unified_attrib.font_size ? data.unified_attrib.font_size : '',
                          fontFamily: data.unified_attrib && data.unified_attrib.font ? data.unified_attrib.font : '',
                        }"
                        v-html="sanitizeHTML(item.value)"
                      ></span>
                      <template v-if="item.type === 'input'">
                        <template v-if="data.property.fill_type === fillTypeList[0].value">
                          <el-input
                            :key="index"
                            v-model="item.value"
                            :disabled="disabled"
                            :class="[...computedAnswerClass(item, i, j)]"
                            :style="[{ width: Math.max(40, item.value.length * 21.3) + 'px' }]"
                          />
                        </template>
                        <template v-else-if="data.property.fill_type === fillTypeList[1].value">
                          <el-popover :key="index" placement="top" trigger="click">
                            <div class="word-list">
                              <span
                                v-for="{ content, mark } in data.word_list"
                                :key="mark"
                                class="word-item"
                                @click="handleSelectWord(content, mark, item)"
                              >
                                {{ content }}
                              </span>
                            </div>

                            <el-input
                              slot="reference"
                              v-model="item.value"
                              :readonly="true"
                              :class="[...computedAnswerClass(item, i, j)]"
                              :style="[{ width: Math.max(40, item.value.length * 21.3) + 'px' }]"
                            />
                          </el-popover>
                        </template>

                        <template v-else-if="data.property.fill_type === fillTypeList[2].value">
                          <span :key="j" class="write-click" @click="handleWriteClick(item)">
                            <img
                              v-show="item.write_base64"
                              style="background-color: #f4f4f4"
                              :src="item.write_base64"
                              alt="write-show"
                            />
                          </span>
                        </template>

                        <template v-else-if="data.property.fill_type === fillTypeList[3].value">
                          <SoundRecordBox
                            ref="record"
                            :key="j"
                            type="mini"
                            :many-times="false"
                            class="record-box"
                            :answer-record-list="data.audio_answer_list"
                            :task-model="isJudgingRightWrong ? 'ANSWER' : ''"
                            :attrib="data.unified_attrib"
                            @handleWav="handleMiniWav($event, item)"
                          />
                        </template>
                        <span
                          v-show="computedAnswerText(item, i, j).length > 0"
                          :key="`answer-${j}`"
                          class="right-answer"
                        >
                          {{ computedAnswerText(item, i, j) }}
                        </span>
                      </template>
                    </div>
                  </template>
                </div>
                <span v-if="showLang" class="multilingual" :style="[tdStyle, computedRichStyle(col.content)]">
                  {{
                    multilingualTextList[getLang()] &&
                    multilingualTextList[getLang()][i] &&
                    multilingualTextList[getLang()][i][j]
                      ? multilingualTextList[getLang()][i][j]
                      : ''
                  }}
                </span>
              </td>
            </template>
          </tr>
        </table>
      </div>
    </div>
    <WriteDialog :visible.sync="writeVisible" @confirm="handleWriteConfirm" />
  </div>
</template>

<script>
import { getTableData, fillTypeList } from '@/views/book/courseware/data/table';

import PreviewMixin from '../common/PreviewMixin';
import WriteDialog from '../fill/components/WriteDialog.vue';
import SoundRecordBox from '@/views/book/courseware/preview/components/record_input/SoundRecord.vue';

export default {
  name: 'TablePreview',
  components: { SoundRecordBox, WriteDialog },
  mixins: [PreviewMixin],
  props: {
    isMobile: {
      type: Boolean,
      default: false,
    },
  },

  data() {
    return {
      data: getTableData(),
      table_width: 0,
      multilingualTextList: {}, // 多语言对应的切割后的翻译
      fillTypeList,
      selectedWordList: [], // 用于存储选中的词汇
      writeVisible: false,
      writeMark: '',
    };
  },
  computed: {
    tdStyle() {
      let obj = {};
      if (this.data.mode === 'short') {
        let styles = this.data.styles;
        obj = {
          fontFamily: styles.fontFamily,
          fontSize: styles.fontSize,
          color: styles.fontColor,
          textDecoration: styles.isUnderline ? 'underline' : styles.isStrikethrough ? 'line-through' : '',
          fontWeight: styles.isBold ? 'bold' : '',
          fontStyle: styles.isItalic ? 'italic' : '',
          justifyContent: styles.textAlign,
          textAlign: styles.textAlign,
        };
      } else {
        obj = {
          width: '100%',
        };
      }
      return obj;
    },
  },
  watch: {
    'data.col_width': {
      handler(val) {
        this.handleData();
      },
    },
    isJudgingRightWrong(val) {
      if (!val) return;
      this.data.answer_list = this.answer.answer_list;
      // this.answer.answer_list.forEach(({ mark, value }) => {
      //   this.modelEssay.forEach((item) => {
      //     item.forEach((li) => {
      //       if (li.mark === mark) {
      //         li.content = value;
      //       }
      //     });
      //   });
      // });
    },
  },
  created() {
    this.handleData();
  },
  methods: {
    handleData() {
      this.table_width = 0;
      this.data.col_width.forEach((item) => {
        this.table_width += Number(item.value);
      });
      this.data.multilingual.forEach((item) => {
        let trans_arr = item.translation.split('\n');
        let chunkSize = this.data.property.column_count;
        let chunkedArr = trans_arr.reduce((acc, curr, index) => {
          // 当索引是chunkSize的倍数时，开始一个新的子数组
          if (index % chunkSize === 0) {
            acc.push([curr]); // 开始新的子数组并添加当前元素
          } else {
            acc[acc.length - 1].push(curr); // 将当前元素添加到最后一个子数组中
          }
          return acc;
        }, []);
        this.$set(this.multilingualTextList, item.type, chunkedArr);
      });
      if (!this.isJudgingRightWrong) {
        this.answer.answer_list = this.data.answer_list;
      }
    },
    computedAnswerText(item, i, j) {
      if (!this.isShowRightAnswer) return '';
      let answerOption =
        this.data.answer_list[i] && this.data.answer_list[i][j] ? this.data.answer_list[i][j].answer : '';
      let answerOptionList = answerOption.split('\n');
      if (!item) return '';
      let selectValue = item.value ? item.value.trim() : '';
      let answerValue = answerOptionList[item.inputIndex] ? answerOptionList[item.inputIndex].split('/') : '';
      let isRight = answerValue && answerValue.includes(selectValue);
      if (isRight || !answerValue) return '';
      return `（${answerValue.join('/')}）`;
    },
    /**
     * 计算答题对错选项字体颜色
     * @param {string} mark 选项标识
     */
    computedAnswerClass(item, i, j) {
      if (!this.isJudgingRightWrong && !this.isShowRightAnswer) {
        return '';
      }
      let answerOption =
        this.data.answer_list[i] && this.data.answer_list[i][j] ? this.data.answer_list[i][j].answer : '';
      let answerOptionList = answerOption.split('\n');
      if (!item) return '';
      let selectValue = item.value ? item.value.trim() : '';
      let answerValue = answerOptionList[item.inputIndex] ? answerOptionList[item.inputIndex].split('/') : '';
      let classList = [];
      let isRight = answerValue && answerValue.includes(selectValue);
      if (this.isJudgingRightWrong && answerValue) {
        isRight ? classList.push('right') : classList.push('wrong');
      }

      if (this.isShowRightAnswer && !isRight) {
        classList.push('show-right-answer');
      }
      return classList;
    },
    /**
     * 处理小音频录音
     * @param {Object} data 音频数据
     * @param {String} mark 选项标识
     */
    handleMiniWav(data, mark) {
      if (!data || !mark) return;
      this.$set(mark, 'audio_answer_list', data);
    },
    /**
     * 处理选中词汇
     * @param {String} content 选中的词汇内容
     * @param {String} mark 选项标识
     * @param {Object} li 当前输入框对象
     */
    handleSelectWord(content, mark, li) {
      if (!content || !mark || !li || this.disabled) return;

      li.value = content;
      this.selectedWordList.push(mark);
    },
    /**
     * 处理书写区确认
     * @param {String} data 书写区数据
     */
    handleWriteConfirm(data) {
      if (!data) return;
      this.$set(this.writeMark, 'write_base64', data);
    },
    handleWriteClick(mark) {
      this.writeVisible = true;
      this.writeMark = mark;
    },
    computedRichStyle(content) {
      if (this.data.mode === 'short') return {};
      if (!content) return {};
      // 提取首个标签的 style 样式属性
      let styleMatch = content.match(/<\w+\s+[^>]*style=["']([^"']*)["'][^>]*>/i);
      if (styleMatch && styleMatch[1]) {
        let styleString = styleMatch[1];
        let styleArray = styleString.split(';').filter((s) => s.trim() !== '');
        let styleObject = {};
        styleArray.forEach((style) => {
          let [key, value] = style.split(':');
          if (key && value) {
            styleObject[key.trim()] = value.trim();
          }
        });
        return styleObject;
      }
      return {};
    },
  },
};
</script>

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

$select-color: #1890ff;
$border-color: #e6e6e6;

.table-preview {
  @include preview-base;

  .main {
    color: #262626;

    .table-box {
      margin: 0 auto;
      overflow: auto;
    }

    table {
      // border-spacing: 3px;
      border-collapse: separate;
    }

    .cell-wrap {
      display: flex;
      flex-flow: wrap;
      grid-area: fill;
      align-items: end;

      p {
        flex-grow: 1; // 为了常规模式时设置居中显示撑满整个单元格
        max-width: 100%;
        margin: 0;
      }

      .record-box {
        display: inline-flex;
        align-items: center;
        background-color: #fff;
        border-bottom: 1px solid $font-color;
      }

      .write-click {
        display: inline-block;
        width: 104px;
        height: 32px;
        padding: 0 4px;
        vertical-align: bottom;
        cursor: pointer;
        border-bottom: 1px solid $font-color;

        img {
          width: 100%;
          height: 100%;
        }
      }

      .el-input {
        display: inline-flex;
        align-items: center;
        width: 120px;
        margin: 0 2px;
        font-size: 16px;

        &.pinyin :deep input.el-input__inner {
          font-family: 'PINYIN-B', sans-serif;
        }

        &.chinese :deep input.el-input__inner {
          font-family: 'arial', sans-serif;
        }

        &.english :deep input.el-input__inner {
          font-family: 'arial', sans-serif;
        }

        &.right {
          :deep input.el-input__inner {
            color: $right-color;
          }
        }

        &.wrong {
          :deep input.el-input__inner {
            color: $error-color;
          }
        }

        & + .right-answer {
          position: relative;
          left: -4px;
          display: inline-block;
          height: 32px;
          line-height: 28px;
          vertical-align: bottom;
          border-bottom: 1px solid $font-color;
        }

        :deep input.el-input__inner {
          padding: 0;

          // font-size: 16pt;
          color: $font-color;
          text-align: center;
          background-color: #fff;
          border-width: 0;
          border-bottom: 1px solid $font-color;
          border-radius: 0;
        }
      }

      &-normal {
        p {
          width: 100%; // 为了解决换行问题
        }
      }
    }

    .multilingual {
      display: block;
      word-break: break-word;
    }

    .pinyin-text {
      display: flex;
      flex-direction: column;
      padding: 0 1px;
      font-size: 16px;

      span {
        text-align: center;
      }

      .pinyin {
        height: 18px;
        font-family: 'League';
        font-size: 12px;
      }

      &-left {
        span {
          // text-align: left;
        }
      }
    }
  }
}

.word-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;

  .word-item {
    cursor: pointer;
  }
}
</style>
