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

    <div class="main">
      <div
        class="table-box"
        :style="{
          width: data.property.width + 'px',
          height: data.property.height + 'px',
        }"
      >
        <table
          :style="{
            width: 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 ? '5px ' : '0',
                  background:
                    i === 0 && data.property.first_line_color
                      ? data.property.first_line_color
                      : j === 0
                        ? data.property.first_column_color
                        : '',
                }"
              >
                <div :style="[tdStyle]" class="cell-wrap">
                  <template v-if="isEnable(data.property.view_pinyin)">
                    <p
                      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'">
                        <el-input
                          :key="index"
                          v-model="item.value"
                          :disabled="disabled"
                          :style="[{ width: Math.max(80, item.value.length * 21.3) + 'px' }]"
                        />
                        <span v-if="data.property.pinyin_position === 'bottom'" class="pinyin">&nbsp;</span>
                        <!-- <span v-show="computedAnswerText(li.mark).length > 0" :key="`answer-${indexs}`" class="right-answer">
                {{ computedAnswerText(li.mark) }}
              </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>
                    </p>
                  </template>
                  <template v-else>
                    <p v-for="(item, index) in col.model_essay" :key="index">
                      <span v-if="item.type === 'text'" :key="index" v-html="sanitizeHTML(item.value)"></span>
                      <template v-if="item.type === 'input'">
                        <el-input
                          :key="index"
                          v-model="item.value"
                          :disabled="disabled"
                          :style="[{ width: Math.max(80, item.value.length * 21.3) + 'px' }]"
                        />
                        <!-- <span v-show="computedAnswerText(li.mark).length > 0" :key="`answer-${indexs}`" class="right-answer">
                {{ computedAnswerText(li.mark) }}
              </span> -->
                      </template>
                    </p>
                  </template>
                </div>
                <span class="multilingual" v-if="showLang">
                  {{
                    multilingualTextList[getLang()] &&
                    multilingualTextList[getLang()][i] &&
                    multilingualTextList[getLang()][i][j]
                      ? multilingualTextList[getLang()][i][j]
                      : ''
                  }}
                </span>
              </td>
            </template>
          </tr>
        </table>
      </div>
    </div>
  </div>
</template>

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

import PreviewMixin from '../common/PreviewMixin';
import { isEnable } from '../../../data/common';

export default {
  name: 'TablePreview',
  components: {},
  mixins: [PreviewMixin],
  data() {
    return {
      data: getTableData(),
      table_width: 0,
      multilingualTextList: {}, // 多语言对应的切割后的翻译
    };
  },
  computed: {
    tdStyle() {
      let obj = {};
      if (this.data.mode === 'short') {
        let styles = this.data.styles;
        obj = {
          fontFamily: styles.fontFamily,
          fontSize: styles.fontSize,
          fontColor: styles.fontColor,
          backgroundColor: styles.bgColor,
          textDecoration: styles.isUnderline ? 'underline' : styles.isStrikethrough ? 'line-through' : '',
          fontWeight: styles.isBold ? 'bold' : '',
          fontStyle: styles.isItalic ? 'italic' : '',
          justifyContent: styles.textAlign,
        };
      }
      return obj;
    },
  },
  watch: {
    'data.col_width': {
      handler(val) {
        this.handleData();
      },
    },
  },
  created() {
    this.handleData();
  },
  mounted() {},
  beforeDestroy() {},
  methods: {
    handleData() {
      this.table_width = 0;
      this.data.col_width.forEach((item) => {
        this.table_width += Number(item.value);
      });
      if (this.showLang) {
        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);
        });
      }
      console.log(this.data);
    },
    computedAnswerText(mark) {
      if (!this.isShowRightAnswer) return '';
      let selectOption = this.answer.answer_list.find((item) => item.mark === mark);
      let answerOption = this.data.answer.answer_list.find((item) => item.mark === mark);
      if (!selectOption) return '';
      let selectValue = selectOption.value;
      let answerValue = answerOption.value;
      let isRight = selectValue === answerValue;
      if (isRight) return '';
      return `（${answerValue}）`;
    },
  },
};
</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 {
      overflow: auto;
    }

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

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

      p {
        margin: 0;
      }

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

        &.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;
        }
      }
    }

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

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

      span {
        text-align: center;
      }

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

      &-left {
        span {
          text-align: left;
        }
      }
    }
  }
}
</style>
