<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
  }
})

const isOk = ref()

// 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) => {
    if (!value) {
    } else {
      const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
      if (reg.test(value)) {
        callback();
      } else {
        return callback(new Error('请输入正确的手机号'));
      }
    }
  };
};

// 验证规则
const rules = ref({
  modelValue: [
    {
      required: props.isRequired,
      message: '请输入手机号',
      trigger: 'blur'
    },
    {
      min: 11,
      message: '手机号格式不正确',
      trigger: 'blur'
    },
    {
      trigger: 'blur',
      validator: validateIdentity()
    }
  ]
})

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

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

<style lang="scss" scoped>
.is-success {
  .el-form-item__content .el-input {
    .el-input__inner {
      // background-color: var(--el-color-primary-light-7); 不定义背景色
    }
  }
}
</style>
