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

        <RichText
          v-if="isEnable(data.property.is_enable_description)"
          v-model="data.description"
          placeholder="输入提示"
        />
      </div>

      <el-input
        v-if="isEnable(data.property.is_enable_word_select_fill)"
        v-model="data.word_select_fill"
        rows="3"
        resize="none"
        type="textarea"
        placeholder="输入词汇"
      />

      <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>
        <template v-if="data.answer.answer_list.length > 0 && isEnable(data.property.is_enable_word_select_fill)">
          <div class="subtitle">正确答案</div>
          <div class="correct-answer">
            <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>
        </template>

        <template v-if="!isEnable(data.property.is_enable_word_select_fill)">
          <div class="reference-title">参考答案：</div>
          <el-input
            v-model="data.reference_answer"
            type="textarea"
            class="reference-answer"
            resize="none"
            :autosize="{ minRows: 3 }"
            placeholder="输入参考答案"
          />
        </template>

        <div v-if="isEnable(data.property.is_enable_analysis)" class="analysis">
          <div class="analysis-title">解析：</div>
          <RichText v-model="data.analysis" :is-border="true" :font-size="14" placeholder="输入解析" />
        </div>
      </div>
    </template>

    <template #property>
      <el-form :model="data.property" label-width="72px" label-position="left">
        <el-form-item label="题号">
          <el-input v-model="data.property.question_number" />
        </el-form-item>
        <el-form-item>
          <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-select v-model="data.property.stem_question_number_font_size">
            <el-option v-for="item in fontSizeList" :key="item" :label="item" :value="item" />
          </el-select>
        </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 switchOption"
            :key="value"
            v-model="data.property.is_enable_analysis"
            :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_word_select_fill"
            :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>
          <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, handleToneValue } from '@/views/exercise_questions/data/common';
import { fillData, analysisRecognitionFillData } from '@/views/exercise_questions/data/fill';

export default {
  name: 'FillQuestion',
  mixins: [QuestionMixin],
  data() {
    return {
      data: JSON.parse(JSON.stringify(fillData)),
    };
  },
  methods: {
    /**
     * 智能识别
     * @param {String} text 识别数据
     */
    recognition(text) {
      let arr = this.recognitionCommon(text);
      let obj = analysisRecognitionFillData(arr);
      this.recognitionCommonSetObj(obj);
      this.identifyText();
    },
    // 识别文本
    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);
          if (this.isEnable(this.data.property.is_enable_word_select_fill)) {
            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;
  }

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

  .correct-answer {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;

    .el-input {
      width: 180px;

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

  .reference-title {
    margin-top: 8px;
    font-size: 14px;
    color: #000;
  }

  .reference-answer {
    margin-top: 8px;
  }
}
</style>
