<!--
 * @Author: zhaojinfeng 121016171@qq.com
 * @Date: 2023-07-23 16:27:37
 * @LastEditors: zhaojinfeng 121016171@qq.com
 * @LastEditTime: 2023-08-14 20:40:41
 * @FilePath: \vue3\packages\mask-text\index.vue
 * @Description: 敏感数据隐藏组件
 *
-->
<template>
  <span :class="{ 'cursor-help': hideden && !disabled }" @click="click">
    {{ data }}
  </span>
</template>

<script lang="ts" setup name="ThMaskText">
const props = withDefaults(defineProps<{
  /** 带隐藏的文字 */
  text?: string
  /** 左侧可见的位数 */
  left?: number
  /** 右侧可见的位数 */
  right?: number
  /** 禁用点击事件 */
  disabled?: boolean
}>(), { left: 0, right: 0, disabled: false })

const hideden = ref(true)

const data = computed(() => {
  if (!props.text)
    return ''

  const left = props.left < 0 ? 0 : props.left
  const right = props.right < 0 ? 0 : props.right
  const textLength = props.text.length
  if (!hideden.value
    || left > textLength
    || right > textLength
    || right + left > textLength
  )
    return props.text
  const rightIndex = textLength - right
  const centerLength = textLength - right - left
  const leftText = props.text.slice(0, left)
  const centerText = '*'.repeat(centerLength)
  const rightText = props.text.slice(rightIndex)

  return leftText + centerText + rightText
})

function click() {
  if (!props.disabled)
    hideden.value = true
}
</script>
