<template>
    <ele-modal v-model="visible" title="链接" :width="500" :footer="null">
        <div class="flex flex-col items-center justify-center py-6">
            <el-input
                v-model="linkUrl"
                readonly
                placeholder="请输入"
                class="mb-6 w-full"
            />
            <el-button
                type="success"
                @click="handleCopy"
                class="!px-8 !py-5 text-base"
                >复制链接</el-button
            >
        </div>
    </ele-modal>
</template>

<script setup>
    import { ref } from 'vue';
    import { EleMessage } from 'ele-admin-plus/es';
    import request from '@/utils/request';
    import useClipboard from 'vue-clipboard3';

    const visible = ref(false);
    const redPacketId = ref('');
    const linkUrl = ref('');
    const { toClipboard } = useClipboard();

    const open = async (id) => {
        redPacketId.value = id;
        visible.value = true;
        if (id) {
            await fetchLink();
        } else {
            linkUrl.value = '';
        }
    };

    const fetchLink = async () => {
        try {
            const res = await request.get('/shop/couponInfo/getCouponUrl', {
                params: {
                    couponId: redPacketId.value
                }
            });
            if (res.data.code === 200) {
                linkUrl.value = res.data.data;
            } else {
                EleMessage.error(res.data.msg || '获取链接失败');
            }
        } catch (error) {
            console.error(error);
            EleMessage.error('获取链接失败');
        }
    };

    const handleCopy = async () => {
        if (!linkUrl.value) {
            EleMessage.warning('链接为空');
            return;
        }
        try {
            await toClipboard(linkUrl.value);
            EleMessage.success('复制成功');
            visible.value = false;
        } catch (e) {
            EleMessage.error('复制失败');
        }
    };

    defineExpose({ open });
</script>

<style scoped>
    :deep(.el-button--success) {
        --el-button-bg-color: #3ab54a;
        --el-button-border-color: #3ab54a;
        --el-button-hover-bg-color: #4ac75a;
        --el-button-hover-border-color: #4ac75a;
    }
</style>
