<!-- eslint-disable vue/no-v-html -->
<template>
  <div class="fill-form-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="form-wrapper">
      <div class="form" :style="{ width: `${data.property.form_width}px` }">
        <div v-if="isEnable(data.property.is_enable_table_header)" class="form-header">
          <div
            v-for="{ text, mark, width } in data.option_header_list"
            :key="mark"
            :style="{
              width: `${width}%`,
              paddingLeft: isEnable(data.property.is_enable_number_column) ? '40px' : '0',
            }"
            class="header-item"
          >
            <span>{{ text }}</span>
          </div>
        </div>
        <div v-for="(item, i) in optionList" :key="i" class="form-content">
          <div
            v-for="({ mark, content_list }, j) in item"
            :key="mark"
            :style="{ width: `${data.option_header_list[j].width}%` }"
            class="form-item"
          >
            <span v-if="j === 0 && isEnable(data.property.is_enable_number_column)" class="serial-number">
              {{ i + 1 }}
            </span>
            <div v-for="(li, k) in content_list" :key="k" class="item-content">
              <span v-if="li.type === 'text'" v-html="sanitizeHTML(li.content)"></span>
              <template v-else-if="li.type === 'input_any'">
                <el-input
                  :key="k"
                  v-model="li.content"
                  :disabled="disabled"
                  :class="['fill']"
                  placeholder="请输入"
                  :style="[
                    { cursor: disabled ? 'not-allowed' : 'pointer' },
                    { width: Math.max(80, li.content.length * 16) + 'px' },
                  ]"
                />
              </template>
              <template v-else-if="li.type === 'fill'">
                <el-input
                  :key="k"
                  v-model="li.content"
                  :disabled="disabled"
                  :class="['fill', ...computedAnswerClass(mark, li.mark)]"
                  placeholder="请输入"
                  :style="[
                    { cursor: disabled ? 'not-allowed' : 'pointer' },
                    { width: Math.max(80, li.content.length * 16) + 'px' },
                  ]"
                />
                <span
                  v-show="computedAnswerText(mark, li.mark).length > 0"
                  :key="`answer-${i}-${j}-${k}`"
                  class="right-answer-content"
                >
                  {{ computedAnswerText(mark, li.mark) }}
                </span>
              </template>
              <template v-else-if="li.type === 'input'">
                <el-input
                  :key="k"
                  v-model="li.content"
                  :disabled="disabled"
                  :class="['input', ...computedAnswerClass(mark, li.mark)]"
                  :style="[
                    { cursor: disabled ? 'not-allowed' : 'pointer' },
                    { width: Math.max(80, li.content.length * 16) + 'px' },
                  ]"
                />
                <span
                  v-show="computedAnswerText(mark, li.mark).length > 0"
                  :key="`answer-${i}-${j}-${k}`"
                  class="right-answer-fill"
                >
                  {{ computedAnswerText(mark, li.mark) }}
                </span>
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import PreviewMixin from './components/PreviewMixin';

export default {
  name: 'TableFillPreview',
  mixins: [PreviewMixin],
  data() {
    return {
      optionList: [],
    };
  },
  watch: {
    'data.option_list': {
      handler(val) {
        this.optionList = JSON.parse(JSON.stringify(val));
      },
      immediate: true,
      deep: true,
    },
    optionList: {
      handler(val) {
        val.forEach((item) => {
          item.forEach(({ mark, content_list }) => {
            let value_list = [];
            let answerIndex = this.answer.answer_list.findIndex((item) => item.mark === mark);
            content_list.forEach((li) => {
              if (['fill', 'input', 'input_any'].includes(li.type) && li.content.length > 0) {
                value_list.push({
                  mark: li.mark,
                  value: li.content,
                });
              }
            });
            if (answerIndex === -1 && value_list.length <= 0) return;
            if (answerIndex !== -1 && value_list.length <= 0) {
              this.answer.answer_list.splice(answerIndex, 1);
              return;
            }
            if (answerIndex !== -1) {
              this.answer.answer_list[answerIndex].value_list = value_list;
              return;
            }
            this.answer.answer_list.push({
              mark,
              value_list,
            });
          });
        });
      },
      deep: true,
    },
    isJudgingRightWrong(val) {
      if (!val) return;
      this.answer.answer_list.forEach(({ mark, value_list }) => {
        this.optionList
          .find((item) => item.find((li) => li.mark === mark))
          .forEach((item) => {
            item.content_list.forEach((li) => {
              if (['fill', 'input', 'input_any'].includes(li.type)) {
                let answer = value_list.find((item) => item.mark === li.mark);
                if (!answer) return;
                li.content = answer.value;
              }
            });
          });
      });
    },
  },
  methods: {
    /**
     * 计算答题对错选项字体颜色
     * @param {string} mark 选项标识
     * @param {string} liMark 选项子标识
     */
    computedAnswerClass(mark, liMark) {
      if (!this.isJudgingRightWrong && !this.isShowRightAnswer) {
        return '';
      }
      let selectOption = this.answer.answer_list
        .find((item) => item.mark === mark)
        ?.value_list.find((item) => item.mark === liMark);
      let answerOption = this.data.answer.answer_list
        .find((item) => item.mark === mark)
        ?.value_list.find((item) => item.mark === liMark);
      if (!selectOption) return '';
      let selectValue = selectOption.value;
      let answerValue = answerOption.value;
      let classList = [];
      let isRight = selectValue === answerValue;

      if (this.isJudgingRightWrong) {
        isRight ? classList.push('right') : classList.push('wrong');
      }

      if (this.isShowRightAnswer && !isRight) {
        classList.push('show-right-answer');
      }
      return classList;
    },
    /**
     * 计算正确答案
     * @param {string} mark 选项标识
     * @param {string} liMark 选项子标识
     */
    computedAnswerText(mark, liMark) {
      if (!this.isShowRightAnswer) return '';
      // mark 对应答题选项
      let selectOption = this.answer.answer_list
        .find((item) => item.mark === mark)
        ?.value_list.find((item) => item.mark === liMark);
      // mark 对应正确答案选项
      let answerOption = this.data.answer.answer_list
        .find((item) => item.mark === mark)
        ?.value_list.find((item) => item.mark === liMark);
      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 *;

$table-border: 1px solid #ebebeb;

.fill-form-preview {
  @include preview;

  .form-wrapper {
    overflow: auto;

    .form {
      &-header {
        display: flex;
        font-weight: bold;
        color: $main-color;
        background-color: #eaeffb;

        .header-item {
          display: flex;
          align-items: center;
          min-height: 40px;
          padding: 8px 12px;
          border-left: $table-border;
        }
      }

      .form-content:first-child {
        .form-item {
          border-top: $table-border;
        }
      }

      &-content {
        display: flex;

        .form-item {
          display: flex;
          align-items: center;
          min-height: 48px;
          border-bottom: $table-border;
          border-left: $table-border;

          .item-content {
            padding: 8px 12px;
          }

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

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

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

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

            & + .right-answer-content {
              position: relative;
              left: -4px;
              display: inline-block;
              height: 32px;
              line-height: 28px;
              vertical-align: bottom;
            }

            :deep input.el-input__inner {
              padding: 0;
              font-size: 16px;
              color: $font-color;
              text-align: left;
              background-color: #fff;
              border-width: 0;
              border-radius: 0;
            }
          }

          .input {
            @extend %input;

            :deep input.el-input__inner {
              text-align: center;
              border-bottom: 1px solid $font-color;
            }
          }
        }

        .form-item:last-child {
          border-right: $table-border;
        }
      }

      .serial-number {
        display: flex;
        align-items: center;
        height: 100%;
        padding: 8px 12px;
        border-right: $table-border;
      }
    }
  }
}
</style>
