<script>
export default {
  props: {
    fieldValue: {
      default: ''
    },
    rules: [Object, Array],
    reset: {
      type: Boolean,
      default: false
    },
    teamFlag: {
      default: ''
    }
  },
  data() {
    return {
      validateMessage: ''
    }
  },
  watch: {
    fieldValue (nextValue, oldValue) {
      if (!this.rules || this.reset) return
      if (oldValue === '') {
        this.$emit('blank', true)
      }
      if (this.teamFlag === 'team' && (nextValue !== '' || nextValue === '')) {
        this.validateMessage = ''
        return
      }
      this.validate()
    }
  },
  mounted() {
    if (!this.rules) return
    this.$emit('form', this)
  },
  methods: {
    // 验证邮箱
    checkEmail(email) {
      if (email === undefined || email === '' || !email.match(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/)) {
        return false
      }
      return true
    },
    validate(fn = () => {}) {
      if (!this.rules) return
      const rules = this.rules
      for (let i = 0; i < rules.length; i++) {
        const rule = rules[i]
        if (rule.required && this.fieldValue === '') {
          this.handelMessage(fn, rule.message, true)
          return
        }
        if (rule.type && rule.type === 'email' && !this.checkEmail(this.fieldValue)) {
          if (!this.fieldValue.match(/\@/)) {
            this.handelMessage(fn, 'Please Enter a valid email address')
          } else {
            this.handelMessage(fn, rule.message)
          }
          return
        }
        if (rule.type && rule.type === 'phone' && /[a-zA-Z]/.test(this.fieldValue)) {
          this.handelMessage(fn, rule.message)
          return
        }
        if (rule.type && rule.type === 'users' && /[^0-9]/.test(this.fieldValue)) {
          this.handelMessage(fn, rule.message)
          return
        }
      }
      this.validateMessage = ''
      fn()
    },
    handelMessage (fn, message, blank) {
      blank ? fn(message, true) : fn(message)
      this.validateMessage = message
    }
  }
}
</script>

<template>
  <div class="form" :class="{ 'err-form': rules && rules[0].required && validateMessage, 'notShowErr': teamFlag === 'partner' }">
    <slot></slot>
    <div v-if="rules && rules[0].required && validateMessage" class="err">{{ validateMessage }}</div>
  </div>
</template>

<style lang="scss" scoped>
  .notShowErr {
    margin-bottom: 21px;
  }
  .err {
    width: 100%;
    margin-top: 5px;
    color: #fc4043;
    font-size: 14px;
    text-align: left;
  }
  .err-form{
    margin-bottom: 0px;
  }
</style>
