<template>
    <div class="p-4">
        <div class="mb-4 flex items-center justify-between">
            <div>
                <div class="text-sm" style="color: var(--van-text-color-2);">我的邀请码</div>
                <div class="text-2xl font-bold" style="color: var(--van-theme-primary);">{{ agentCode }}</div>
            </div>
            <button @click="copyInviteCode"
                class="px-4 py-2 bg-blue-500 text-white rounded-lg text-sm font-medium active:bg-blue-600 shadow-sm">复制邀请码</button>
        </div>
        <div class="p-3">
            <QRcode :inviteLink="inviteLink" mode="invitation" :asPage="true" />
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { showToast } from "vant";
import { storeToRefs } from "pinia";
import QRcode from "@/components/QRcode.vue";
import { useAgentStore } from "@/stores/agentStore";
import { getInviteLink } from "@/api/agent";

const inviteLink = ref("");
const agentStore = useAgentStore();
const { agentCode } = storeToRefs(agentStore);

const copyText = async (text, tip) => {
    try {
        await navigator.clipboard.writeText(text);
        showToast({ message: tip || "已复制" });
    } catch (e) {
        const ta = document.createElement("textarea");
        ta.value = text;
        document.body.appendChild(ta);
        ta.select();
        try {
            document.execCommand("copy");
            showToast({ message: tip || "已复制" });
        } finally {
            document.body.removeChild(ta);
        }
    }
};

const copyInviteCode = () => {
    if (!agentCode.value) {
        showToast({ message: "未获取到邀请码" });
        return;
    }
    copyText(String(agentCode.value), "邀请码已复制");
};

const copyInviteLink = () => {
    if (!inviteLink.value) {
        showToast({ message: "暂无邀请链接" });
        return;
    }
    copyText(inviteLink.value, "邀请链接已复制");
};

onMounted(async () => {
    if (!agentStore.isLoaded) {
        await agentStore.fetchAgentStatus();
    }
    if (!agentStore.isAgent || !agentCode.value) {
        showToast({ message: "请注册成为代理后再邀请" });
        return;
    }

    const targetPath = `/register?invite_code=${agentCode.value}`;
    const { data, error } = await getInviteLink({ invite_code: agentCode.value, target_path: targetPath });
    if (data.value && !error.value && data.value.code === 200) {
        inviteLink.value = data.value.data.invite_link || "";
    } else {
        showToast({ message: data.value?.msg || "获取邀请链接失败" });
    }
});
</script>

<style scoped></style>
