/*! bxs-vue-ui v3.3.0 */
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

require('../utils/entry-virtual.js');
var normalizeComponent = require('../utils/normalize-component.js');
require('../utils/html.js');
require('../utils/es.object.to-string.js');
require('../utils/array-iteration.js');
require('../utils/sloppy-array-method.js');
var map = require('../utils/map.js');
var indexOf = require('../utils/index-of.js');
require('../utils/a-function.js');
require('../utils/species-constructor.js');
require('../utils/es.promise.js');
require('../utils/set-to-string-tag.js');
var AsyncValidator = _interopDefault(require('async-validator'));

/* eslint-disable */
// 暂时简单自行实现，等待函数库完成再切换
// 内置的校验类型可查看 https://github.com/yiminghe/async-validator#type
var buildInType = {
  email: function email(value) {
    return /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(value);
  },
  mobile: function mobile(value) {
    return /^1(3|4|5|6|7|8|9)\d{9}$/.test(value);
  },
  bank: function bank(value) {
    return /^([1-9]{1})(\d{14}|\d{18})$/.test(value);
  },
  idCard: function idCard(value) {
    return /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(value);
  }
};

var LABEL_THRESHOLD = 5;

var onlyValues = function onlyValues(values) {
  return function (str) {
    return indexOf._indexOfInstanceProperty(values).call(values, str) !== -1;
  };
};

var getPositionResult = function getPositionResult(value, type) {
  return value ? "bx-form-item__" + type + "--" + value : '';
};

var script = normalizeComponent.create({
  name: 'form-item',
  provide: function provide() {
    return {
      bxsFormItem: this
    };
  },
  inject: {
    bxsForm: {
      default: ''
    }
  },
  props: {
    prop: String,
    label: String,
    labelPosition: {
      type: String,
      default: 'left',
      validator: onlyValues(['top', 'bottom', 'left', 'right', 'middle'])
    },
    contentPosition: {
      type: String,
      default: 'left',
      validator: onlyValues(['top', 'bottom', 'left', 'right', 'middle'])
    },
    required: [Boolean, String],
    rules: Object,
    showMessage: {
      type: Boolean,
      default: undefined
    },
    ignoreValidate: {
      type: Boolean,
      default: false
    }
  },
  data: function data() {
    return {
      validateMessage: '',
      // 是否强制垂直对齐
      isVerticalAlignmentForced: false
    };
  },
  computed: {
    form: function form() {
      return this.bxsForm;
    },
    // label 文案是否超过阈值LABEL_THRESHOLD=5
    isLabelMoreThanThreshold: function isLabelMoreThanThreshold() {
      return this.label.length >= LABEL_THRESHOLD;
    },
    // 根据 labelPosition 计算class
    labelPositionClass: function labelPositionClass() {
      return getPositionResult(this.labelPosition, 'label');
    },
    // 根据 contentPosition 计算class
    contentPositionClass: function contentPositionClass() {
      return getPositionResult(this.contentPosition, 'content');
    },
    // 是否显示校验错误信息，覆盖form中的showMessage
    isShowErrorMessage: function isShowErrorMessage() {
      if (this.showMessage === undefined || this.showMessage === null) {
        return this.form.showMessage;
      }

      return this.showMessage;
    }
  },
  mounted: function mounted() {
    if (this.prop) {
      this.form.$emit('form.addField', this); // 可通过inject自行实现逻辑触发

      this.$on('form.item.validate', this.onValidate);
      this.$on('form.item.reset', this.onResetField);
    }
  },
  methods: {
    // 获取表单域上的所有规则，包括form上的rules，form-item上的rules和required
    getRules: function getRules() {
      var _context, _context2;

      var formRules = this.form.rules[this.prop];
      var selfRules = this.rules;
      var requiredRule = this.getRequiredRule();
      return normalizeComponent._concatInstanceProperty(_context = normalizeComponent._concatInstanceProperty(_context2 = []).call(_context2, selfRules || formRules || [])).call(_context, requiredRule);
    },
    getRequiredRule: function getRequiredRule() {
      if (this.required !== undefined && this.required !== null) {
        var requiredRule = {};
        requiredRule.required = !!this.required;

        if (typeof this.required === 'string') {
          requiredRule.message = this.required;
        }

        return requiredRule;
      }

      return [];
    },
    // 获取内置类型校验规则
    getBuildInRule: function getBuildInRule(rules) {
      var formItemRules = rules;
      return map._mapInstanceProperty(formItemRules).call(formItemRules, function (rule) {
        if (rule.type && !rule.validator) {
          /* eslint no-param-reassign: ["error", { "props": false }] */
          rule.validator = function (_rule, value) {
            return buildInType[rule.type](value);
          };
        }

        return rule;
      });
    },
    validate: function validate() {
      var _this = this;

      if (this.ignoreValidate) {
        return normalizeComponent._Promise.resolve();
      }

      var rules = this.getRules(); // 没有设置规则的项，直接跳过

      if (rules.length === 0) {
        return normalizeComponent._Promise.resolve();
      }

      var descriptor = {};
      rules = this.getBuildInRule(rules);
      descriptor[this.prop] = rules;
      var validator = new AsyncValidator(descriptor, {
        // 当验证到第一个错误时，立刻回调，不再执行之后的验证
        first: true
      });
      var source = {};
      source[this.prop] = this.form.model[this.prop];
      var promise = validator.validate(source);
      promise.then(function () {
        _this.resetField();
      }).catch(function (_ref) {
        var errors = _ref.errors;
        // 通知input，信息反馈
        _this.validateMessage = errors[0].message;
      });
      return promise;
    },
    resetField: function resetField() {
      this.validateMessage = '';
    },
    onResetField: function onResetField() {
      this.resetField();
    },
    onValidate: function onValidate() {
      this.validate();
    }
  }
});

/* script */
var __vue_script__ = script;
/* template */

var __vue_render__ = function __vue_render__() {
  var _vm = this;

  var _h = _vm.$createElement;

  var _c = _vm._self._c || _h;

  return _c('div', {
    staticClass: "bx-form-item",
    class: [_vm.labelPositionClass, _vm.contentPositionClass]
  }, [_c('div', {
    staticClass: "bx-form-item__inner"
  }, [_vm.label ? _c('div', {
    staticClass: "bx-form-item__label",
    class: (_vm.isLabelMoreThanThreshold || _vm.isVerticalAlignmentForced) && 'bx-form-item__labbx--lg'
  }, [_vm._v("\n      " + _vm._s(_vm.label) + "\n    ")]) : _vm._e(), _c('div', {
    staticClass: "bx-form-item__content"
  }, [_vm._t("default")], 2)]), _vm.isShowErrorMessage && _vm.validateMessage ? _c('div', {
    staticClass: "bx-form-item__error"
  }, [_vm._v("\n    " + _vm._s(_vm.validateMessage) + "\n  ")]) : _vm._e()]);
};

var __vue_staticRenderFns__ = [];
/* style */

var __vue_inject_styles__ = undefined;
/* scoped */

var __vue_scope_id__ = undefined;
/* module identifier */

var __vue_module_identifier__ = undefined;
/* functional template */

var __vue_is_functional_template__ = false;
/* style inject */

/* style inject SSR */

var index = normalizeComponent.__vue_normalize__({
  render: __vue_render__,
  staticRenderFns: __vue_staticRenderFns__
}, __vue_inject_styles__, __vue_script__, __vue_scope_id__, __vue_is_functional_template__, __vue_module_identifier__, undefined, undefined);

exports.default = index;
