import checkFunc from './checkfunc';
import TypeDic, { requiredDesc } from './typeDic';
import { getValueByKey } from '../../../utils/MapUtils';
import { isArray } from '../../../utils/StringUtils';


const checkFields = (record, value, form, formValidate, isModalInputMappingItem) => {
  const validateType = formValidate && formValidate.validateType;
  // const opt = formValidate && formValidate.opt;
  const opt = formValidate;
  const errors = checkFunc[validateType] && checkFunc[validateType](record, value, form.getFieldsValue(), form, opt, isModalInputMappingItem);
  return errors;
};

// 表单校验
const createRules = (record, form, isModalInputMappingItem) => {
  const analyserName = getValueByKey(record, 'default', 'displayComponent', 'componentType');
  let desc = '请输入';
  if (requiredDesc.indexOf(analyserName) >= 0) {
    if (analyserName !== 'MODALINPUT' || record.isReadonly) {
      desc = '请选择';
    }
  }
  const ret = [];
  if (record.isVisible) {
    const isRequired = { required: record.isRequired, message: desc + record.description };
    // if (analyserName !== 'CHECKBOXGROUP') {
    isRequired.type = TypeDic[record.type];
    // }
    ret.push(isRequired);
    ret.push({ validator(rule, value, callback) {
      // TODO: 多个校验怎么处理
      // if (record.type === 'String') {
      //   if (value && value.length > record.length) {
      //     callback([new Error('请输入' + record.length + '个汉字内的' + record.description)]);
      //     return;
      //   }
      // }
      const formValidate = (record && record.formValidate) || (record && record.formValidates);
      if (isArray(formValidate)) {
        const errors = [];
        formValidate.some(formV => {
          const er = checkFields(record, value, form, formV, isModalInputMappingItem);
          if (er) {
            errors.push(er);
          }
          return er;
        });
        callback(errors);
      } else {
        const errors = checkFields(record, value, form, formValidate, isModalInputMappingItem);
        callback((errors && [errors]) || []);
      }
    } });
  }
  return ret;
};

export default createRules;
