<template>
  <el-form ref="formRef" :model="groupData" :rules="rules">
    <el-form-item
      :label-width="LABEL_WIDTH"
      prop="modelValue"
      label="邮箱"
    >
      <el-input
        v-bind="$attrs"
        v-model="groupData.modelValue"
        @input="onInput()"
        @blur="validate()"
        max="11"
      ></el-input>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { LABEL_WIDTH } from '@/constant';
import { ref, defineProps, defineEmits, defineExpose } from 'vue'
const formRef = ref(null);
const props = defineProps({
  isRequired: {
    type: Boolean,
    default: false
  }
})

// import { validateIdentity } from './rules'
const groupData = ref({
  modelValue: ''
});
const emits = defineEmits(['update:modelValue']);
const onInput = (e) => {
  emits('update:modelValue', groupData.value.modelValue)
}
const isBX = ref(false)

const validateIdentity = () => {
  return (rule, value, callback) => {
    const reg = /^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/
    if (!value) {
    } else {
      if (!reg.test(value)) {
        return callback(new Error('请输入正确的邮箱地址'));
      } else {
        callback();
      }
    }
  };
};

// 验证规则
const rules = ref({
  modelValue: [
    {
      required: props.isRequired,
      message: '请输入邮箱',
      trigger: 'blur'
    },
    {
      trigger: 'blur',
      validator: validateIdentity()
    }
  ]
})

// 校验是否 符合规则 。 把当前组件名通过 emits分发出去
const validate = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      emits('validateStatus', { 'Email': true })
    } else {
      emits('validateStatus', { 'Email': false })
    }
  })
  if (!props.isRequired && groupData.value.modelValue.length === 0) {
    emits('validateStatus', { 'Email': true })
  }
}

const childMethod = () => {
  groupData.value.modelValue = ""
}
// 主动暴露childMethod方法
defineExpose({ childMethod })
</script>

<style lang="scss" scoped>
</style>
