<template>
  <QuestionBase>
    <template #content>
      <div class="stem">
        <RichText v-model="data.stem" :font-size="18" placeholder="输入题干" />

        <el-input
          v-if="isEnable(data.property.is_enable_description)"
          v-model="data.description"
          rows="3"
          resize="none"
          type="textarea"
          placeholder="输入填空内容"
        />
      </div>

      <div class="content">
        <RichText
          ref="modelEssay"
          v-model="data.article"
          :is-fill="true"
          :toolbar="false"
          :wordlimit-num="false"
          placeholder="输入文段"
        />

        <el-button @click="identifyText">识别</el-button>
        <div v-if="data.answer.answer_list.length > 0" class="correct-answer">
          <div class="subtitle">正确答案</div>
          <el-input
            v-for="(item, i) in data.answer.answer_list.filter(({ type }) => type === 'any_one')"
            :key="item.mark"
            v-model="item.value"
            @blur="handleTone(item.value, i)"
          >
            <span slot="prefix">{{ i + 1 }}.</span>
          </el-input>
        </div>
      </div>
    </template>

    <template #property>
      <el-form :model="data.property">
        <el-form-item label="题号">
          <el-input v-model="data.property.question_number" />
        </el-form-item>
        <el-form-item label-width="45px">
          <el-radio
            v-for="{ value, label } in questionNumberTypeList"
            :key="value"
            v-model="data.other.question_number_type"
            :label="value"
          >
            {{ label }}
          </el-radio>
        </el-form-item>
        <el-form-item label="描述">
          <el-radio
            v-for="{ value, label } in switchOption"
            :key="value"
            v-model="data.property.is_enable_description"
            :label="value"
          >
            {{ label }}
          </el-radio>
        </el-form-item>
        <el-form-item label="分值">
          <el-radio
            v-for="{ value, label } in scoreTypeList"
            :key="value"
            v-model="data.property.score_type"
            :label="value"
          >
            {{ label }}
          </el-radio>
        </el-form-item>
        <el-form-item label-width="45px">
          <el-input-number
            v-model="data.property.score"
            :min="0"
            :step="data.property.score_type === scoreTypeList[0].value ? 1 : 0.1"
          />
        </el-form-item>
      </el-form>
    </template>
  </QuestionBase>
</template>

<script>
import QuestionMixin from '../common/QuestionMixin.js';

import { getRandomNumber } from '@/utils';
import { addTone } from '@/views/exercise_questions/data/common';
import { fillData, handleToneValue } from '@/views/exercise_questions/data/fill';

export default {
  name: 'FillQuestion',
  mixins: [QuestionMixin],
  data() {
    return {
      data: JSON.parse(JSON.stringify(fillData)),
    };
  },
  methods: {
    // 识别文本
    identifyText() {
      this.data.model_essay = [];
      this.data.answer.answer_list = [];
      this.data.article
        .split(/<p .*?>(.*?)<\/p>/gi)
        .filter((item) => item)
        .forEach((item) => {
          if (item.charCodeAt() === 10) return;
          let str = item
            // 去除所有的 font-size 样式
            .replace(/font-size:\s*\d+(\.\d+)?px;/gi, '')
            // 匹配 class 名为 rich-fill 的 span 标签和三个以上的_，并将它们组成数组
            .replace(/<span class="rich-fill".*?>(.*?)<\/span>|([_]{3,})/gi, '###$1$2###');
          this.data.model_essay.push(this.splitRichText(str));
        });
    },
    // 分割富文本
    splitRichText(str) {
      let _str = str;
      let start = 0;
      let index = 0;
      let arr = [];
      let matchNum = 0;
      while (index !== -1) {
        index = _str.indexOf('###', start);
        if (index === -1) break;
        matchNum += 1;
        arr.push({ content: _str.slice(start, index), type: 'text' });
        if (matchNum % 2 === 0 && arr.length > 0) {
          arr[arr.length - 1].type = 'input';
          let mark = getRandomNumber();
          arr[arr.length - 1].mark = mark;
          let content = arr[arr.length - 1].content;
          // 设置答案数组
          let isUnderline = /^_{3,}$/.test(content);
          this.data.answer.answer_list.push({
            value: isUnderline ? '' : content,
            mark,
            type: isUnderline ? 'any_one' : 'only_one',
          });
          // 将 content 设置为空，为预览准备
          arr[arr.length - 1].content = '';
        }
        start = index + 3;
      }
      let last = _str.slice(start);
      if (last) {
        arr.push({ content: last, type: 'text' });
      }
      return arr;
    },
    handleTone(value, i) {
      if (!/^[a-zA-Z0-9\s]+$/.test(value)) return;
      this.data.answer.answer_list[i].value = 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>
.content {
  position: relative;

  .el-button {
    margin-top: 8px;
  }

  .correct-answer {
    .subtitle {
      margin: 8px 0;
      font-size: 14px;
      color: #4e5969;
    }

    .el-input {
      width: 180px;

      :deep &__prefix {
        display: flex;
        align-items: center;
        color: $text-color;
      }

      + .el-input {
        margin-left: 8px;
      }
    }
  }
}
</style>
