<template>
    <el-input v-model="displayValue" :placeholder="placeholder" clearable style="width: 100%" @focus="onFocus"
        @blur="onBlur" />
</template>

<script setup>
import { ref, watch, reactive } from "vue"
import * as rule from "@/utils/rules.js";
import { filterqx } from "@/utils/auth.js"
// 接收父组件传入的参数
const props = defineProps({
    modelValue: { type: String, default: "" }, // 绑定的值（v-model）
    label: { type: String, default: "" }, // 表单标签
    prop: { type: String, default: "" }, // el-form-item 校验字段名
    placeholder: { type: String, default: "请输入" }, // 占位符
    isShow: { type: Boolean, default: true } // 是否脱敏显示，默认 true
})
const emit = defineEmits(["update:modelValue"])

// 显示层内容
const displayValue = ref("")
const isFocused = ref(false)

// 脱敏逻辑：保留前三后四，中间用****
const maskPhone = (num) => {
    if (!num && num !== 0) return ""
    const str = String(num)
    if (str.length < 7) return str
    return str.replace(/^(.{4})(?:\d+)(.{4})$/, "$1********$2")
}
const cleanVal = ref()

// 同步父组件的 modelValue -> 显示层
watch(
    () => props.modelValue,
    (val) => {
        if (!isFocused.value) {
            displayValue.value = !props.isShow ? maskPhone(val) : val
        }
    },
    { immediate: true }
)

// 聚焦时显示真实号码
const onFocus = () => {
    isFocused.value = true
    displayValue.value = !props.isShow ? "" : displayValue.value
}
// 失焦时写回父组件并显示脱敏
const onBlur = () => {
    isFocused.value = false
    cleanVal.value = displayValue.value ? String(displayValue.value).trim() : ""
    console.log(cleanVal.value)
    emit("update:modelValue", cleanVal.value)
    displayValue.value = !props.isShow ? maskPhone(cleanVal.value) : cleanVal.value
}
</script>
