<script lang="ts" setup>
import Desensitize from '@/common/utils/desensitize'

const props = withDefaults(defineProps<{
  value: string
  type: keyof typeof Desensitize
  show?: boolean
}>(), {show: false})

const showOriginal = ref(false)

watch(
  () => props.show,
  (val) => {
    showOriginal.value = val
  })

let clickTimer: number | null = null
const transformedValue = computed(() => (showOriginal.value ? props.value : (Desensitize[props.type]?.(props.value) ?? props.value)))

const handleClick = () => {
  if (clickTimer) clearTimeout(clickTimer)
  clickTimer = window.setTimeout(() => {
    showOriginal.value = !showOriginal.value
    clickTimer = null
  }, 300)
}

const handleDblClick = async () => {
  if (clickTimer) {
    clearTimeout(clickTimer)
    clickTimer = null
  }
  try {
    await navigator.clipboard.writeText(props.value)
    ElMessage.success('复制成功')
  } catch (err) {
    ElMessage.error('复制失败，请手动复制')
  }
}
</script>

<template>
  <span
    class="desensitize-txt"
    @click="handleClick"
    @dblclick.stop="handleDblClick"
  >
    {{ transformedValue }}
  </span>
</template>

<style lang="stylus" scoped>
.desensitize-txt {
  display: inline-block;
  position: relative;
  cursor: pointer;
  user-select none

  &:hover {
    color: var(--el-color-primary);
    text-decoration: underline;
  }
}
</style>
