/**
 * v-copy
 * 复制某个值至剪贴板
 * 支持 string、ref(string)、reactive(string)
 */
import { ElMessage } from 'element-plus'
import { isRef, unref } from 'vue'

const directive = {
    mounted(el, binding) {
        const handleClick = async () => {
            try {
                const value = unref(binding.value)
                if (typeof value !== 'string') {
                    console.warn('v-copy 指令的值必须是字符串或字符串的 ref/reactive')
                    return
                }

                await navigator.clipboard.writeText(value)
                ElMessage.success('复制成功')
            } catch (err) {
                console.error('复制失败:', err)
                ElMessage.error('复制失败')
            }
        }

        el.__handleClick__ = handleClick
        el.addEventListener('click', handleClick)
    },

    updated(el, binding) {
        // updated 生命周期中无需更新事件，只需确保绑定值是最新的，handleClick 每次读取 unref 即可
    },

    beforeUnmount(el) {
        el.removeEventListener('click', el.__handleClick__)
        delete el.__handleClick__
    }
}

export default directive
