import {
  checkPhoneNumber,
  validatorEnterpriseEmail,
  checkIdentityCode,
  checkWebsite,
  checkBankcard,
  checkSumFixedTwo,
  checkPureDigital,
  checkPureEnglish,
  checkPureChinese
} from '@/utils/common/rules';
import Request from '@/utils/request/request-util';

// 获取组件验证规则
export function getRules(record) {
  const {
    componentCode,
    itemLabelName,
    contentValidateType,
    formatType,
    validateErrorTip,
    regexExpression,
    jsValidateCode,
    backendValidateParamName,
    backendValidateUrl
  } = record;
  let message = '请输入';
  let trigger = 'blur';
  let type = 'string';
  if (
    [
      'select',
      'custom-select',
      'tree-select',
      'link-select',
      'date',
      'time',
      'dateTime',
      'date-range',
      'radio',
      'switch',
      'city',
      'checkbox'
    ].includes(componentCode)
  ) {
    message = '请选择' + itemLabelName;
    trigger = 'blur';
  } else if (['upload', 'upload-pic'].includes(componentCode)) {
    message = '请' + itemLabelName;
    trigger = 'blur';
    type = 'string';
  } else if (['table'].includes(componentCode)) {
    message = itemLabelName + '不能为空';
    type = 'array';
    trigger = 'blur';
  } else if (
    ['select-user', 'select-org', 'select-modal', 'select-role', 'select-dict', 'select-position', 'org-user', 'view-select'].includes(
      componentCode
    )
  ) {
    message = '请选择' + itemLabelName;
    trigger = ['change', 'blur'];
  } else {
    message = '请输入' + itemLabelName;
    trigger = 'blur';
    if (['number', 'progress'].includes(componentCode)) {
      type = 'number';
    }
  }
  // 组装规则
  let rule = [
    {
      required: record.itemRequiredFlag ?? false,
      message: validateErrorTip || message,
      type: type,
      trigger: trigger,
      itemLabelName: itemLabelName,
      validateErrorTip: validateErrorTip
    }
  ];
  if (componentCode == 'phone') {
    delete rule[0].message;
    rule[0].validator = checkPhoneNumber;
  } else if (componentCode == 'email') {
    delete rule[0].message;
    rule[0].validator = validatorEnterpriseEmail;
  } else if (componentCode == 'idcard') {
    delete rule[0].message;
    rule[0].validator = checkIdentityCode;
  }

  // 内容校验类型
  if (contentValidateType == 1 && formatType) {
    // 常用格式校验：10-手机号码，20-邮箱，30-身份证，40-网址，50-银行卡，60-金额，70-纯数字，80-纯英文，90-纯中文
    if (rule[0]?.message) delete rule[0].message;
    switch (formatType) {
      case 10:
        rule[0].validator = checkPhoneNumber;
        break;
      case 20:
        rule[0].validator = validatorEnterpriseEmail;
        break;
      case 30:
        rule[0].validator = checkIdentityCode;
        break;
      case 40:
        rule[0].validator = checkWebsite;
        break;
      case 50:
        rule[0].validator = checkBankcard;
        break;
      case 60:
        rule[0].validator = checkSumFixedTwo;
        break;
      case 70:
        rule[0].validator = checkPureDigital;
        break;
      case 80:
        rule[0].validator = checkPureEnglish;
        break;
      case 90:
        rule[0].validator = checkPureChinese;
        break;
    }
  } else if (contentValidateType == 2 && regexExpression) {
    // 基于正则表达式校验
    if (rule[0]?.message) delete rule[0].message;
    rule[0].validator = (rule, value) => {
      if (rule.required && !value) {
        return Promise.reject(validateErrorTip || `请输入${itemLabelName}`);
      }
      if (value) {
        let reg = regexExpression.slice(1, -1);
        const regex = new RegExp(reg);
        if (!regex.test(value)) {
          return Promise.reject(validateErrorTip || `请输入正确的${itemLabelName}格式`);
        } else {
          return Promise.resolve();
        }
      }
    };
  } else if (contentValidateType == 3 && jsValidateCode) {
    // 基于js校验
    if (rule[0]?.message) delete rule[0].message;
    rule[0].validator = (rule, value) => {
      if (rule.required && !value) {
        return Promise.reject(validateErrorTip || `请输入${itemLabelName}`);
      }
      if (value) {
        const func = new Function('value', jsValidateCode);
        const flag = func(value);
        if (flag) {
          return Promise.resolve();
        } else {
          return Promise.reject(validateErrorTip || `请输入正确的${itemLabelName}格式`);
        }
      }
    };
  } else if (contentValidateType == 4 && backendValidateParamName && backendValidateUrl) {
    // 基于后台接口校验
    if (rule[0]?.message) delete rule[0].message;
    rule[0].validator = async (rule, value) => {
      if (rule.required && !value) {
        return Promise.reject(validateErrorTip || `请输入${itemLabelName}`);
      }
      if (value) {
        let params = {}
        params[backendValidateParamName] = value;
        const res = await Request['post'](backendValidateUrl, params);
        if (res.data) {
          return Promise.resolve();
        } else {
          return Promise.reject(validateErrorTip || `请输入正确的${itemLabelName}格式`);
        }
      }
    };
  }

  return rule;
}
