<!-- eslint-disable vue/no-v-html -->
<template>
  <div class="fill-preview">
    <div class="stem">
      <span class="question-number">{{ data.property.question_number }}.</span>
      <span v-html="sanitizeHTML(data.stem)"></span>
    </div>
    <div v-if="isEnable(data.property.is_enable_description)" class="description">{{ data.description }}</div>

    <AudioPlay
      v-if="isEnable(data.property.is_enable_listening) && data.file_id_list.length > 0"
      :file-id="data.file_id_list[0]"
    />

    <div class="fill-wrapper">
      <p v-for="(item, i) in data.model_essay" :key="i">
        <template v-for="(li, j) in item">
          <span v-if="li.type === 'text'" :key="j" v-html="sanitizeHTML(li.content)"></span>
          <el-input v-if="li.type === 'input'" :key="j" v-model="li.content" @blur="handleTone(li.content, i, j)" />
        </template>
      </p>
    </div>
  </div>
</template>

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

import { addTone } from '@/views/exercise_questions/data/common';
import { handleToneValue } from '@/views/exercise_questions/data/fill';

export default {
  name: 'FillPreview',
  mixins: [PreviewMixin],
  data() {
    return {};
  },
  watch: {
    'data.model_essay': {
      handler(val) {
        if (!val) return;
        this.answer.answer_list = val
          .map((item) => {
            return item
              .map(({ type, content, mark }) => {
                if (type === 'input') {
                  return {
                    value: content,
                    mark,
                  };
                }
              })
              .filter((item) => item);
          })
          .flat();
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    handleTone(value, i, j) {
      if (!/^[a-zA-Z0-9\s]+$/.test(value)) return;
      this.data.model_essay[i][j].content = value
        .trim()
        .split(/\s+/)
        .map((item) => {
          return handleToneValue(item);
        })
        .map((item) =>
          item.map(({ number, con }) => (number && con ? addTone(Number(number), con) : number || con || '')),
        )
        .filter((item) => item.length > 0)
        .join(' ');
    },
  },
};
</script>

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

.fill-preview {
  @include preview;

  .fill-wrapper {
    .el-input {
      width: 120px;
      margin: 0 2px;

      :deep input.el-input__inner {
        padding: 0;
        font-size: 16px;
        color: $font-color;
        text-align: center;
        background-color: #fff;
        border-width: 0;
        border-bottom: 1px solid $font-color;
        border-radius: 0;
      }
    }
  }
}
</style>
