// 题目混入
import QuestionBase from './QuestionBase.vue';
import RichText from '@/components/common/RichText.vue';
import AudioPlay from '@/views/exercise_questions/create/components/common/AudioPlay.vue';

import { GetQuestionInfo, SaveQuestion } from '@/api/exercise';
import {
  stemTypeList,
  scoreTypeList,
  switchOption,
  isEnable,
  questionNumberTypeList,
  computedQuestionNumber,
  fontSizeList,
} from '@/views/exercise_questions/data/common';

const mixin = {
  data() {
    return {
      fontSizeList,
      stemTypeList,
      scoreTypeList,
      switchOption,
      isEnable,
      questionNumberTypeList,
      computedQuestionNumber,
      isGetInfo: false, // 是否获取题目信息
    };
  },
  provide: ['refreshPreviewData'],
  inject: ['updateLoading'],
  props: {
    questionId: {
      type: String,
      default: '',
    },
    isChild: {
      type: Boolean,
      default: false,
    },
    isChange: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    QuestionBase,
    RichText,
    AudioPlay,
  },
  created() {
    if (this.isChild) {
      if (this.isChange) {
        this.$emit('update:isChange', false);
        this.isGetInfo = true;
        return;
      }
      GetQuestionInfo({ question_id: this.questionId })
        .then(({ question }) => {
          if (!question.content) return;
          this.data = JSON.parse(question.content);
          this.$emit('loaded');
          this.isGetInfo = true;
          this.refreshPreviewData();
        })
        .catch(() => {});
    }
  },
  watch: {
    'data.property.score'(val) {
      if (val === undefined) return;
      this.data.answer.score = val;
    },
    'data.property.score_type'(val) {
      if (val === undefined) return;
      this.data.answer.score_type = val;
    },
    data: {
      handler() {
        if (!this.isChild) return;
        this.$emit('updatePreviewData', this.data);
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    saveChildQuestion() {
      if (!this.isGetInfo) return;
      SaveQuestion({
        question_id: this.questionId,
        type: this.data.type,
        additional_type: this.data.property.select_type || '',
        content: JSON.stringify(this.data),
      }).catch(() => {});
    },
    upload(file_id) {
      this.data.file_id_list.push(file_id);
    },
    deleteFile(file_id) {
      let index = this.data.file_id_list.indexOf(file_id);
      if (index !== -1) {
        this.data.file_id_list.splice(index, 1);
      }
    },
    /**
     * 设置题目内容
     * @param {object} content 题目内容
     */
    setQuestion(content) {
      this.data = content;
      if (!this.isChild) {
        this.updateLoading(false);
      }
    },
    /**
     * 单独设置题号
     * @param {string} question_number 题号
     */
    setQuestionNumber(question_number) {
      this.data.property.question_number = question_number;
    },
    /**
     * 删除选项
     * @param {number} i 索引
     */
    deleteOption(i) {
      this.data.option_list.splice(i, 1);
    },
    /**
     * 智能识别公用方法
     * @param {string} text 文本
     * @param {boolean} isEnableReferenceAnswer 是否启用参考答案
     */
    recognitionCommon(text, isEnableReferenceAnswer = false) {
      let arr = text
        .split(/[\r\n]/)
        .map((item) => item.trim())
        .filter((item) => item);

      if (arr.length === 0) return [];

      let sliceLength = 0;
      const stemReg = /^题干[:：]/;
      if (stemReg.test(arr[0])) {
        this.data.stem = arr[0].replace(stemReg, '');
        sliceLength += 1;
      }

      const desReg = /^提示[:：]/;
      if (desReg.test(arr[sliceLength])) {
        this.data.description = arr[sliceLength].replace(desReg, '');
        this.data.property.is_enable_description = 'true';
        sliceLength += 1;
      } else {
        this.data.description = '';
        this.data.property.is_enable_description = 'false';
      }

      if (isEnableReferenceAnswer) {
        let referenceReg = /^参考答案[:：]/;
        let index = arr.findIndex((item) => referenceReg.test(item));
        if (index === -1) {
          this.data.reference_answer = '';
          this.data.property.is_enable_reference_answer = 'false';
        } else {
          this.data.reference_answer = arr[index].replace(referenceReg, '');
          this.data.property.is_enable_reference_answer = 'true';
          arr.splice(index, 1);
        }
      }
      return arr.slice(sliceLength);
    },
    /**
     * 智能识别公用设置属性
     * @param {object} obj 对象
     */
    recognitionCommonSetObj(obj) {
      Object.keys(obj).forEach((key) => {
        key.split('.').reduce((prev, cur, index, arr) => {
          if (index === arr.length - 1) {
            prev[cur] = obj[key];
          } else {
            return prev[cur];
          }
        }, this);
      });
    },
  },
};

export default mixin;
