<!-- eslint-disable vue/no-mutating-props -->
<script setup lang="ts">
defineOptions({ name: 'MjFormPhone' })

const props = withDefaults(
  defineProps<{
    clearable?: boolean
    disabled?: boolean
    modelValue: any
    placeholder?: any
  }>(),
  {
    placeholder: undefined,
    disabled: false,
    clearable: true,
  },
)

const emit = defineEmits(['update:modelValue'])

const text = computed({
  get: () => formatPhone(props.modelValue),
  set: (val) => {
    val = formatPhone(val)
    emit('update:modelValue', val.replaceAll(/\s/g, ''))
  },
})

// 表单数据
const phoneInput = ref()

// 格式化手机号
const formatPhone = (value: any) => {
  // 确保value是字符串
  const stringValue = String(value || '')
  // 移除所有非数字字符
  const numbers = stringValue.replaceAll(/\D/g, '')
  // 限制最多11位数字
  const limitedNumbers = numbers.slice(0, 11)

  // 格式化为 XXX XXXX XXXX
  if (limitedNumbers.length <= 3) {
    return limitedNumbers
  } else if (limitedNumbers.length <= 7) {
    return `${limitedNumbers.slice(0, 3)} ${limitedNumbers.slice(3)}`
  } else {
    return `${limitedNumbers.slice(0, 3)} ${limitedNumbers.slice(3, 7)} ${limitedNumbers.slice(7)}`
  }
}
</script>

<template>
  <div class="mj-form-phone-box">
    <el-input
      ref="phoneInput"
      :disabled="disabled"
      class="mj-form-phone"
      v-model="text"
      :placeholder="placeholder"
      :clearable="clearable"
    />
  </div>
</template>

<style lang="scss" scoped>
.mj-form-phone-box {
  position: relative;

  .mj-form-phone {
    display: flex;
    align-items: center;
    color: #000;
    cursor: pointer;
    border-radius: 4px;
    font-size: 16px;

    :deep(input) {
      color: #000;
    }
  }
}
</style>
