import type { IQuestion } from '@/types/question';
import { getLanguage } from '@/views/Survey/views/Preview/js/language';
import { validateEnglishLetters } from '@/views/Survey/views/Preview/components/questions/validate/validateEnglishLetters';
import { validateChineseLetter } from '@/views/Survey/views/Preview/components/questions/validate/validateChineseLetter';
import { validateEmail } from '@/views/Survey/views/Preview/components/questions/validate/validateEmail';
import { validatePhone } from '@/views/Survey/views/Preview/components/questions/validate/validatePhone';
import { validateIDCard } from '@/views/Survey/views/Preview/components/questions/validate/validateIDCard';
import type { ITranslatedText } from '@/views/Survey/views/Preview/components/questions/validate/validateChineseLetter';
import {
  validateMinLength,
  validateMaxLength
} from '@/views/Survey/views/Preview/components/questions/validate/validateStringLength';

/**
 * 生成对应的语言文字
 * 目标语言暂时写死，有需求后续更改
 */
const translatedText = getLanguage(['zh']) as ITranslatedText;

/**
 * @description 填空题验证
 * @date 2022-11-22
 * @param {IQuestion<ICompletionConfig>} question - 问卷
 * @param {IQuestionConfig} config - 相关配置
 * @param {ICompletionAnswer} answer - 答案
 */
function validateCompletion(
  question: IQuestion<ICompletionConfig>,
  config: ICompletionConfig,
  answer: string
) {
  // 是否有错误
  let isError = false;

  question.error = '';
  // 处理空白字符
  const newValue = answer.replace(/\n|\r|\r\n/g, '');

  // 根据对应的类型进行验证
  switch (config.text_type) {
    // 字母校验
    case 3:
      question.error = validateEnglishLetters(config, newValue, translatedText);
      break;
    // 中文校验
    case 4:
      question.error = validateChineseLetter(config, newValue, translatedText);
      break;
    // 邮箱校验
    case 5:
      question.error = validateEmail(newValue, translatedText);
      break;
    // 手机号
    case 6:
      question.error = validatePhone(newValue, translatedText);
      break;
    // 身份证号
    case 7:
      question.error = validateIDCard(newValue, translatedText);
      break;
    default:
      break;
  }

  // 最小输入字数校验
  const minStringValidateResult = validateMinLength(answer, isError, config, translatedText);
  // 如果内容存在， 则说明有错误，初始化赋值数据
  if (minStringValidateResult) {
    const { isError: minStringError, errorMessage: minStringErrMessage } = minStringValidateResult;

    minStringError && (isError = minStringError);
    question.error = minStringErrMessage;
  }

  // 最大输入字数校验
  const maxStringValidateResult = validateMaxLength(answer, isError, config, translatedText);
  // 如果内容存在， 则说明有错误，初始化赋值数据
  if (maxStringValidateResult) {
    const { isError: maxStringError, errorMessage: maxStringErrMessage } = maxStringValidateResult;

    maxStringError && (isError = maxStringError);
    question.error = maxStringErrMessage;
  }

  // 返回错误和对应的 question
  return {
    question,
    isError
  };
}

export { validateCompletion };
