<template>
  <div :class="[
      'ps-form-item',
      isRequired && 'is-required',
      isError && 'is-error',
    ]">
    <div
      class="ps-form-item--title"
      v-if="label"
    >{{ label }}</div>
    <slot></slot>
    <div class="ps-form-item--error">{{ errorConent }}</div>
  </div>
</template>

<script>
import eventBus from '../../utils/eventBus'
export default {
  name: 'PsFormItem',
  props: {
    label: {
      type: String,
      default: null
    },
    prop: {
      type: String,
      default: null
    },
    isMore: {
      tyoe: Boolean,
      default: false
    }
  },
  data() {
    return {
      propArr: {},
      isRequired: false,
      isError: false,
      errorConent: null,
      formId: null
    }
  },
  // watch: {
  //   $child
  // },
  created() {
    this.propArr = this.$parent.rules
    this.formId = this.$parent.id
  },
  mounted() {
    // is-error
    this.operaInit()
    console.log('----------------------------')
    console.log(this.$parent)
    this.operaOnEventBus()
  },
  methods: {
    operaInit() {
      let nowRules = this.propArr[this.prop] || []
      nowRules.forEach(el => {
        if (el.required) {
          this.isRequired = el.required
        }
      })
    },
    validator() {
      this.isError = false
      this.errorConent = null
      //判断isMore是否位true
      if (this.isMore) {
        let moreRules = this.prop.split(',') || []
        moreRules.forEach(el => {
          if (!this.isError) {
            this.operaRequired(this.$parent.model[el], this.propArr[el] || [])
          }
        })
      } else {
        let nowRules = []
        nowRules = this.propArr[this.prop] || []
        this.operaRequired(this.$parent.model[this.prop], nowRules)
      }

      this.operaOnEventBus()
      return this.isError
    },
    operaRequired(vals, nowRules) {
      nowRules.forEach(el => {
        if (!this.isError) {
          if (el.required && (vals === null || vals === undefined || vals === '')) {
            this.isError = true
            this.errorConent = el.message
          } else if (el.validator && !el.isError) {
            this.isError = true
            this.errorConent = el.message
          } else if (el.reg && !el.reg.test(vals)) {
            this.isError = true
            this.errorConent = el.message
          }
        }
      })
    },
    operaOnEventBus() {
      if (this.prop) {
        //关闭单次bus线程
        eventBus.$off(`psForm.item.input.${this.formId}.${this.prop}`)
        eventBus.$on(`psForm.item.input.${this.formId}.${this.prop}`, () => {
          console.log(`psForm.item.input.${this.formId}.${this.prop}`)
          this.validator()
        })
      }
    }
  }
}
</script>

<style>
</style>
