import { stemTypeList, scoreTypeList, questionNumberTypeList, switchOption, fontSizeList } from './common';
import { getRandomNumber } from '@/utils/index';
import { GetStaticResources } from '@/api/app';
import { addTone } from '@/views/exercise_questions/data/common';
let res_arr;

export function getOption(content = '') {
  return {
    content,
    mark: getRandomNumber(),
    audio_file_id: '',
    pinyin: '',
    pinyin_item_list: [],
    definition: '',
    collocation: '',
    hz_strokes_list: [],
  };
}
// 汉字类型列表
export const learnTypeList = [
  { value: 'paint', label: '描红' },
  { value: 'write', label: '临写' },
];

// 音频生成方式类型
export const audioGenerationMethodList = [
  {
    value: 'upload',
    label: '上传',
  },
  {
    value: 'auto',
    label: '自动生成',
  },
  {
    value: 'record',
    label: '录音',
  },
];

export function handleValue(valItem) {
  let numList = [];
  if (/[A-Za-zü]+\d/g.test(valItem)) {
    valItem.split('').forEach((item, i) => {
      if (/\d/.test(item)) {
        let con = valItem.replace(/\d/g, '');
        numList.push({
          index: i,
          number: item,
          con,
          isTran: true,
        });
      }
    });
  } else {
    numList = [];
  }

  return numList.length === 0 ? [{ con: valItem }] : numList;
}

function handleReplaceTone(value, mark, matically_pinyin_obj) {
  if (!value) return;
  value.split(/\s+/).forEach((item) => {
    res_arr.push(handleValue(item));
  });
  matically_pinyin_obj[mark] = res_arr
    .map((item) => item.map(({ number, con }) => (number && con ? addTone(Number(number), con) : number || con || '')))
    .filter((item) => item.length > 0)
    .join(' ');
}

export function handleItemPinyin(content, mark, matically_pinyin_obj) {
  let content_arr = content.trim().split(' ');
  matically_pinyin_obj[mark] = [];
  res_arr = [];
  content_arr.forEach((items) => {
    let items_trim = items.trim();
    if (items_trim) {
      handleReplaceTone(items_trim, mark, matically_pinyin_obj);
    }
  });
}

// 切割拼音
export function handleSplitPy(item) {
  let index = item.pinyin.search(/0|1|2|3|4/);
  let matically_pinyin_obj = {};
  if (index > -1) {
    handleItemPinyin(item.pinyin, item.mark, matically_pinyin_obj);
    setTimeout(() => {
      item.pinyin = matically_pinyin_obj[item.mark];
    }, 10);
  }
  let pinyin_list = item.pinyin.trim().split(' ');
  item.pinyin_item_list = [];
  pinyin_list.forEach((itemp) => {
    item.pinyin_item_list.push({
      pinyin_item: itemp,
    });
  });
}

async function fetchStrokesContent(itemc, indexc, content_arr_strokes) {
  let MethodName = 'hz_resource_manager-GetHZStrokesContent';
  let data = {
    hz: itemc,
  };
  const res = await GetStaticResources(MethodName, data);
  content_arr_strokes[indexc] = {
    hz: itemc.trim(),
    strokes: res,
  };
}

// 生成汉字
export async function handleChineseStrokes(item) {
  if (item.content.trim()) {
    let content_arr = item.content.trim().split('');
    let content_arrs = [];
    let content_arr_strokes = [];
    content_arr.forEach((itemc) => {
      if (itemc.trim()) {
        content_arrs.push(itemc.trim());
      }
    });

    await Promise.all(
      content_arrs.map(async (itemc, indexc) => await fetchStrokesContent(itemc, indexc, content_arr_strokes)),
    );
    item.hz_strokes_list = content_arr_strokes;
  }
}

/**
 * 解析智能识别数据
 * @param {array} arr 智能识别数据
 * @returns object
 */
export async function analysisRecognitionChineseData(arr) {
  const option_list = await Promise.all(
    arr.map(async (content) => {
      const content_item = content.split('/');
      const option = {
        content: content_item[0] || '',
        mark: getRandomNumber(),
        audio_file_id: '',
        pinyin: content_item[1] || '',
        pinyin_item_list: [],
        definition: content_item[2] || '',
        collocation: content_item[3] || '',
        hz_strokes_list: [],
      };
      handleSplitPy(option);
      await handleChineseStrokes(option);
      return option;
    }),
  );

  return {
    'data.option_list': option_list,
  };
}

// 书写题数据模板
export const chineseData = {
  type: 'chinese', // 题型
  stem: '', // 题干
  description: '', // 描述
  answer: { score: 1, score_type: scoreTypeList[0].value }, // 答案
  option_list: [getOption(), getOption(), getOption()], // 选项
  file_id_list: [],
  // 题型属性
  property: {
    stem_type: stemTypeList[1].value, // 题干类型
    question_number: '1', // 题号
    stem_question_number_font_size: fontSizeList[6], // 题干题号
    is_enable_description: switchOption[1].value, // 描述
    score: 1, // 分值
    score_type: scoreTypeList[0].value, // 分值类型
    learn_type: learnTypeList[0].value,
    tian_number: 8, // 田字格组
  },
  // 其他属性
  other: {
    question_number_type: questionNumberTypeList[1].value, // 题号类型
    audio_generation_method: audioGenerationMethodList[0].value, // 音频生成方式
  },
};
