<template>
    <van-popup v-model:show="show" round position="bottom">
        <div class="max-h-[calc(100vh-100px)] m-4 ">
            <div class="p-4">
                <canvas ref="posterCanvas" class="rounded-xl shadow h-[500px] m-auto"></canvas>
            </div>
            <!-- <div class="m-2"></div> -->
            <van-divider>分享到好友</van-divider>

            <div class="flex items-center justify-around">
                <!-- <div class="flex flex-col items-center justify-center" @click="toPromote">
                    <img src="@/assets/images/icon_share_wechat.svg" class="w-12 h-12 rounded-full" />
                    <div class="text-center mt-1">微信好友</div>
                </div>
                <div class="flex flex-col items-center justify-center">
                    <img src="@/assets/images/icon_share_friends.svg" class="w-12 h-12 rounded-full" />
                    <div class="text-center mt-1">微信朋友圈</div>
                </div> -->
                <div class="flex flex-col items-center justify-center" @click="savePoster">
                    <img src="@/assets/images/icon_share_img.svg" class="w-10 h-10 rounded-full" />
                    <div class="text-center mt-1 text-gray-600 text-xs">保存图片</div>
                </div>
                <div class="flex flex-col items-center justify-center" @click="copyUrl">
                    <img src="@/assets/images/icon_share_url.svg" class="w-10 h-10 rounded-full" />
                    <div class="text-center mt-1  text-gray-600 text-xs">复制链接</div>
                </div>
            </div>
        </div>
    </van-popup>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue';
import QRCode from 'qrcode';
const props = defineProps({
    linkIdentifier: {
        type: String,
        required: true,
    },
    mode: {
        type: String,
        default: "promote", // 例如 "promote" | "invitation"
    },
});
const { linkIdentifier, mode } = toRefs(props);
const posterCanvas = ref(null);  // 用于绘制海报的canvas
let posterGenerated = ref(false);  // 标记海报是否已经生成过
const show = defineModel('show')
const url = computed(() => {
    const baseUrl = window.location.origin; // 获取当前站点的域名
    return mode.value === "promote"
        ? `${baseUrl}/agent/promotionInquire/`  // 使用动态的域名
        : `${baseUrl}/agent/invitationAgentApply/`;
});

const qrcodeImage = ref(null);
const loadPosterImage = async () => {
    if (mode.value === "promote") {
        const module = await import("@/assets/images/tg_qrcode_1.png");
        return module.default;
    } else {
        const module = await import("@/assets/images/yq_qrcode_1.png");
        return module.default;
    }
};
onMounted(async () => {
    qrcodeImage.value = await loadPosterImage()
});
// 生成海报并合成二维码
const generatePoster = async () => {
    // 如果已经生成过海报，就直接返回
    if (posterGenerated.value) return;

    // 确保 DOM 已经渲染完成
    await nextTick();

    const canvas = posterCanvas.value;
    if (!canvas) return;  // 如果 canvas 元素为空则直接返回

    const ctx = canvas.getContext('2d');

    // 1. 加载海报图片
    const posterImg = new Image();
    posterImg.src = qrcodeImage.value;

    posterImg.onload = () => {
        // 设置 canvas 尺寸与海报图一致
        canvas.width = posterImg.width;
        canvas.height = posterImg.height;

        // 2. 绘制海报图片
        ctx.drawImage(posterImg, 0, 0);

        // 3. 生成二维码
        QRCode.toDataURL(generalUrl(), { width: 150, margin: 0 }, (err, qrCodeUrl) => {
            if (err) {
                console.error(err);
                return;
            }

            // 4. 加载二维码图片
            const qrCodeImg = new Image();
            qrCodeImg.src = qrCodeUrl;
            qrCodeImg.onload = () => {
                const qrX = mode.value === "promote" ? 180 : 360;  // **根据模式调整二维码位置**
                const qrY = mode.value === "promote" ? posterImg.height - 480 : posterImg.height - 1370;
                const qrSize = mode.value === "promote" ? 300 : 360
                ctx.drawImage(qrCodeImg, qrX, qrY, qrSize, qrSize);

                // 标记海报已生成
                posterGenerated.value = true;
            };
        });
    };
};

// 监听 show 变化，show 为 true 时生成海报
watch(show, (newVal) => {
    if (newVal && !posterGenerated.value) {
        generatePoster();  // 当弹窗显示且海报未生成时生成海报
    }
});

// 分享到微信
const toPromote = () => {
    // 这里可以实现微信分享的功能，比如调用微信JS-SDK等
    console.log('分享到微信好友');
};

// 保存海报图片
const savePoster = () => {
    const canvas = posterCanvas.value;
    const dataURL = canvas.toDataURL('image/png'); // 获取 canvas 内容为图片
    const a = document.createElement('a');
    a.href = dataURL;
    a.download = '天远数据查询.png';
    a.click();
};
const generalUrl = () => {
    return url.value + encodeURIComponent(linkIdentifier.value)
}
const copyUrl = () => {
    copyToClipboard(generalUrl())
}
// 复制链接
const copyToClipboard = (text) => {
    if (navigator.clipboard && window.isSecureContext) {
        // 支持 Clipboard API
        navigator.clipboard.writeText(text).then(() => {
            showToast({ message: "链接已复制！" });
        }).catch(err => {
            console.error('复制失败:', err);
        });
    } else {
        // 对于不支持 Clipboard API 的浏览器，使用 fallback 方法
        const textArea = document.createElement('textarea');
        textArea.value = text;
        document.body.appendChild(textArea);
        textArea.select();
        try {
            document.execCommand('copy');
            showToast({ message: "链接已复制！" });
        } catch (err) {
            console.error('复制失败:', err);
        } finally {
            document.body.removeChild(textArea);
        }
    }
};
</script>

<style lang="scss" scoped>
/* 这里是你自定义的样式 */
</style>
