<template>
    <div class="min-h-screen bg-[#DBE0FF]">
        <img src="@/assets/images/invitation_agent_apply.png" alt="邀请代理申请" />
        <!-- 统一状态处理容器 -->
        <div class="flex flex-col items-center justify-centerx">
            <!-- 已是代理状态 -->
            <div v-if="isAgent" class="text-center">
                <span class="text-xs text-gray-500">您已是代理，欢迎回来！</span>
                <div class="bg-green-100 p-1 rounded-3xl shadow-xl mt-1" @click="goToHome">
                    <div
                        class="text-xl font-bold px-8 py-2 bg-gradient-to-t from-green-500 to-green-300 text-white rounded-3xl shadow-lg cursor-pointer">
                        进入应用首页
                    </div>
                </div>
            </div>

            <!-- 未成为代理状态（包含邀请状态） -->
            <div v-else class="text-center">
                <span class="text-xs text-gray-500">{{
                    isSelf ? "立即申请成为代理人" : "邀您注册代理人"
                    }}</span>
                <div class="bg-gray-100 p-1 rounded-3xl shadow-xl mt-1" @click="agentApply">
                    <div
                        class="text-xl font-bold px-8 py-2 bg-gradient-to-t from-blue-500 to-blue-300 text-white rounded-3xl shadow-lg cursor-pointer">
                        立即成为代理方
                    </div>
                </div>
            </div>
        </div>
    </div>
    <AgentApplicationForm v-model:show="showApplyPopup" @submit="submitApplication" @close="showApplyPopup = false" />
</template>

<script setup>
import { aesDecrypt } from "@/utils/crypto";
import { useAliyunCaptcha } from '@/composables/useAliyunCaptcha'
const { runWithCaptcha } = useAliyunCaptcha()
const showApplyPopup = ref(false);
const route = useRoute();
const router = useRouter();
import { storeToRefs } from "pinia";
import { ref } from "vue";
const store = useAgentStore();
const userStore = useUserStore();
const { userName } = storeToRefs(userStore);
const { isAgent } = storeToRefs(store);
const ancestor = ref("");
const isSelf = ref(false);
const agentApply = () => {
    showApplyPopup.value = true;
};


// 跳转到首页
const goToHome = () => {
    router.replace("/promote");
};
onBeforeMount(async () => {
    // 如果是通过邀请链接访问（旧的linkIdentifier格式），提取信息
    if (route.params.linkIdentifier && route.name !== "invitationAgentApplySelf") {
        try {
            const linkIdentifier = route.params.linkIdentifier;
            const decryptDataStr = aesDecrypt(
                decodeURIComponent(linkIdentifier),
                "8e3e7a2f60edb49221e953b9c029ed10"
            );
            const decryptData = JSON.parse(decryptDataStr);
            // 旧格式可能包含agentID和mobile，但新系统使用邀请码
            // 这里可以保留兼容，但主要功能是通过邀请码
        } catch (error) {
            console.error("解析链接标识符失败", error);
        }
    } else {
        isSelf.value = true;
    }
    
    // 检查是否已登录并获取代理状态
    const token = localStorage.getItem("token");
    if (token) {
        await store.fetchAgentStatus();
    }
});
import useApiFetch from '@/composables/useApiFetch'

const submitApplication = async (formData) => {
    const { region, mobile, wechat_id, code, referrer } = formData;
    
    // 根据是否已登录选择不同的API
    const isLoggedIn = !!localStorage.getItem("token");
    const apiUrl = isLoggedIn ? 'agent/apply' : 'agent/register/invite';

    // 使用滑块验证码保护申请接口
    runWithCaptcha(
        (captchaVerifyParam) =>
            useApiFetch(apiUrl)
                .post({ region, mobile, wechat_id, code, referrer, captchaVerifyParam })
                .json(),
        (res) => {
            if (res.code === 200) {
                showApplyPopup.value = false;
                showToast({ message: "注册成功，您已成为代理！" });
                // 更新token和状态
                if (res.data.accessToken) {
                    localStorage.setItem("token", res.data.accessToken);
                    localStorage.setItem("refreshAfter", res.data.refreshAfter);
                    localStorage.setItem("accessExpire", res.data.accessExpire);
                    // 重新获取代理状态
                    store.fetchAgentStatus();
                    userStore.fetchUserInfo();
                    // 跳转到代理主页
                    router.replace("/agent");
                }
            } else {
                showToast({ message: res.msg || "申请失败" });
            }
        }
    );
};
</script>

<style lang="scss" scoped></style>
