import { analysisRecognitionSelectData, getSelectData } from './select';
import { analysisRecognitionJudgeData, getJudgeData } from './judge';
import { analysisRecognitionFillData, fillData } from './fill';
import { analysisRecognitionSortData, getSortDataTemplate } from './sort';
import { analysisRecognitionMatchingData, getMatchingDataTemplate } from './matching';
import { ChooseToneData, analysisRecognitionChooseToneData } from './chooseTone';
import { essayQuestionData } from './essayQuestion';
import { analysisRecognitionReadAloudData, readAloudData } from './readAloud';
import { analysisRecognitionRepeatData, repeatData } from './repeat';
import { talkPictrueData } from './talkPicture';
import { analysisRecognitionDialogueData, getDialogueData } from './dialogue';
import { answerQuestionData } from './answerQuestion';
import { analysisRecognitionReplaceAnswerData, replaceAnswerData } from './replaceAnswer';
import { analysisRecognitionListenSelectData, getListenSelectData } from './listenSelect';
import { analysisRecognitionListenFillData, listenFillData } from './listenFill';
import { analysisRecognitionListenJudgeData, getListenJudgeData } from './listenJudge';
import { analysisRecognitionChineseData, chineseData } from './chinese';
import { analysisRecognitionWordCardData, wordCardData } from './wordCard';
import { analysisRecognitionWriteData, writeData } from './write';
import { writePictrueData } from './writePicture';
import { analysisRecognitionReadData, readData } from './read';
import { analysisRecognitionTableFillData, getTableFillData } from './tableFill';
import { analysisRecognitionWordDictationData, wordDictationData } from './wordDictation';
import { activityData } from './activity';

// 题型源数据
export const questionTypeDataOption = [
  {
    value: 'base',
    label: '基础题型',
    children: [
      // data 是为新建题目提供所需的数据
      { label: '选择题', value: 'select', data: getSelectData() },
      { label: '判断题', value: 'judge', data: getJudgeData() },
      { label: '填空题', value: 'fill', data: fillData },
      { label: '连线题', value: 'matching', data: getMatchingDataTemplate() },
      { label: '排序题', value: 'sort', data: getSortDataTemplate() },
      { label: '问答题', value: 'essay_question', data: essayQuestionData },
      { label: '填表题', value: 'table_fill', data: getTableFillData() },
      { label: '活动题', value: 'activity', data: activityData },
    ],
  },
  {
    value: 'hear',
    label: '听力题',
    children: [
      { label: '听后辨调', value: 'choose_tone', data: ChooseToneData },
      { label: '听后选择', value: 'listen_select', data: getListenSelectData() },
      { label: '听后判断', value: 'listen_judge', data: getListenJudgeData() },
      { label: '听后填空', value: 'listen_fill', data: listenFillData },
    ],
  },
  {
    value: 'spoken',
    label: '口语题',
    children: [
      { label: '朗读题', value: 'read_aloud', data: readAloudData },
      { label: '听说训练', value: 'repeat', data: repeatData },
      { label: '替换练习', value: 'replace_answer', data: replaceAnswerData },
      { label: '对话题', value: 'dialogue', data: getDialogueData() },
      { label: '口语表达', value: 'answer_question', data: answerQuestionData },
      { label: '看图说话', value: 'talk_picture', data: talkPictrueData },
    ],
  },
  {
    value: 'read',
    label: '阅读题',
    data: readData,
  },
  {
    value: 'writing',
    label: '写作题',
    children: [
      { label: '基础写作', value: 'write', data: writeData },
      { label: '看图写作', value: 'write_picture', data: writePictrueData },
    ],
  },
  {
    value: 'character',
    label: '汉字题',
    children: [
      { label: '字词卡片', value: 'word_card', data: wordCardData },
      { label: '书写题', value: 'chinese', data: chineseData },
      { label: '听写题', value: 'word_dictation', data: wordDictationData },
    ],
  },
];

// 题型选项
export const questionTypeOption = questionTypeDataOption.map(({ data, ...item }) => {
  if (item.children) {
    item.children = item.children.map(({ data, ...child }) => child);
  }
  return item;
});

// 题型数据列表
export const questionDataList = questionTypeDataOption
  .map(({ data, value, children }) => {
    if (children) return children.map(({ data, value }) => ({ value, data }));
    return { value, data };
  })
  .flat()
  .reduce((obj, { value, data }) => {
    obj[value] = data;
    return obj;
  }, {});

// 练习名称
export const exerciseNames = questionTypeOption
  .map(({ label, value, children }) => {
    if (children) return children;
    return { label, value };
  })
  .flat()
  .reduce((obj, { label, value }) => {
    obj[value] = label;
    return obj;
  }, {});

/**
 * 获取题型类型列表
 * @param {Array} arr 题型类型选项
 * @returns Object
 */
export function getExerciseTypeList(arr) {
  return arr
    .map(({ value, children }) => {
      if (children) {
        return children.map(({ value: children_value }) => {
          return { [children_value]: [value, children_value] };
        });
      }
      return { [value]: [value] };
    })
    .flat()
    .reduce((obj, item) => {
      return { ...obj, ...item };
    }, {});
}

// 题型类型列表
export const exerciseTypeList = getExerciseTypeList(questionTypeOption);

/**
 * 解析智能识别数据
 * @param {array} arr 智能识别数据
 * @param {object} data 题目数据
 * @param {boolean} isEnableReferenceAnswer 是否启用参考答案
 */
function analysisRecognition(arr, data, isEnableReferenceAnswer = false) {
  let sliceLength = 0;
  const stemReg = /^题干[:：]/;
  if (stemReg.test(arr[0])) {
    data.stem = arr[0].replace(stemReg, '');
    sliceLength += 1;
  }

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

  if (isEnableReferenceAnswer) {
    let referenceReg = /^参考答案[:：]/;
    let index = arr.findIndex((item) => referenceReg.test(item));
    if (index === -1) {
      data.reference_answer = '';
      data.property.is_enable_reference_answer = 'false';
    } else {
      data.reference_answer = arr[index].replace(referenceReg, '');
      data.property.is_enable_reference_answer = 'true';
      arr.splice(index, 1);
    }
  }
  return arr.slice(sliceLength);
}

// 问答题、看图说话、看图写作 无单独数据解析函数
// 各个题型的智能识别数据解析函数
const analysisFunctions = {
  select: analysisRecognitionSelectData,
  judge: analysisRecognitionJudgeData,
  fill: analysisRecognitionFillData,
  sort: analysisRecognitionSortData,
  matching: analysisRecognitionMatchingData,
  choose_tone: analysisRecognitionChooseToneData,
  table_fill: analysisRecognitionTableFillData,
  read_aloud: analysisRecognitionReadAloudData,
  repeat: analysisRecognitionRepeatData,
  dialogue: analysisRecognitionDialogueData,
  replace_answer: analysisRecognitionReplaceAnswerData,
  listen_select: analysisRecognitionListenSelectData,
  listen_fill: analysisRecognitionListenFillData,
  listen_judge: analysisRecognitionListenJudgeData,
  read: analysisRecognitionReadData,
  write: analysisRecognitionWriteData,
  word_dictation: analysisRecognitionWordDictationData,
  // 特殊处理的函数
  chinese: analysisRecognitionChineseData,
  word_card: analysisRecognitionWordCardData,
};

/**
 * 获取智能识别各个题型独有的数据解析返回值
 * @param {array} dataArr 智能识别数据
 * @param {string} type 题型类型
 * @returns object
 */
async function getRecognitionData(dataArr, type) {
  let analysisFunction = null;
  if (['chinese', 'word_card'].type) {
    return await analysisFunctions[type](dataArr);
  }
  analysisFunction = analysisFunctions[type];

  if (!analysisFunction) return {};

  return analysisFunction(dataArr);
}

/**
 * 解析一键导入数据
 * @param {Array} questionList 题目列表
 */
export async function analysisOneKeyImportData(questionList) {
  let dataList = [];
  await Promise.all(
    questionList.map(async (item, i) => {
      let arr = item
        .split(/[\r\n]/)
        .map((item) => item.trim())
        .filter((item) => item);
      if (arr.length === 0) return;
      let [question_number, type_name] = arr[0].split('.');

      if (!type_name) return;

      // 题型类型
      let type = Object.entries(exerciseNames).find(([key, value]) => {
        return value === type_name.trim();
      })?.[0];
      arr = arr.slice(1);

      if (!type || arr.length === 0) return;

      // 是否启用参考答案
      let isEnableReferenceAnswer = false; // 是否启用参考答案
      if (['table_fill', 'answer_question', 'essay_question', 'dialogue'].includes(type)) {
        isEnableReferenceAnswer = true;
      }
      let data = JSON.parse(JSON.stringify(questionDataList[type]));
      data.property.question_number = question_number; // 题号

      let dataArr = analysisRecognition(arr, data, isEnableReferenceAnswer); // 解析公有的数据，并返回剩余的数据

      let recObj = await getRecognitionData(dataArr, type); // 获取各个题型独有的数据解析返回值
      // 将独有的数据解析返回值合并到 data 中
      Object.keys(recObj).forEach((key) => {
        key
          .split('.')
          .slice(1)
          .reduce((prev, cur, index, arr) => {
            if (index === arr.length - 1) {
              prev[cur] = recObj[key];
            } else {
              return prev[cur];
            }
          }, data);
      });
      dataList[i] = {
        type: data.type,
        additional_type: data.type === 'select' ? 'single' : '',
        content: data,
      };
    }),
  );

  return dataList;
}
