<template>
    <div class="min-h-screen bg-[#D1D6FF]">

        <img src="@/assets/images/invitation_agent_apply.png" alt="邀请代理申请">
        <!-- 统一状态处理容器 -->
        <div class="flex flex-col items-center justify-centerx">
            <!-- 申请成功状态 -->
            <div v-if="showSuccessMessage" class="text-center">
                <span class="text-xs text-gray-500">申请成功</span>
                <div class="bg-green-100 p-1 rounded-3xl shadow-xl mt-1">
                    <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">
                        请下载"全能查APP"开始进行代理
                    </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"
        :ancestor="ancestor" />
</template>


<script setup>
import AgentApplicationForm from "@/components/AgentApplicationForm.vue";
import { aesDecrypt } from "@/utils/crypto"
import { ref, onBeforeMount } from 'vue';
import { useRoute } from 'vue-router';

const showApplyPopup = ref(false);
const showSuccessMessage = ref(false);
const route = useRoute();
const ancestor = ref("");
const isSelf = ref(false);

const agentApply = () => {
    showApplyPopup.value = true;
}

onBeforeMount(() => {
    if (route.name === "invitationAgentApplySelf") {
        isSelf.value = true;
    } else {
        try {
            const linkIdentifier = route.params.linkIdentifier;
            const decryptDataStr = aesDecrypt(decodeURIComponent(linkIdentifier), "8e3e7a2f60edb49221e953b9c029ed10");
            const decryptData = JSON.parse(decryptDataStr);
            ancestor.value = decryptData.mobile;
        } catch (err) {
            console.error('解析邀请链接失败', err);
        }
    }
});

const submitApplication = async (formData) => {
    // 提交代理申请的数据
    const { region, mobile, wechat_id, code } = formData;
    let postData = {
        region,
        mobile,
        wechat_id,
        code,
    };
    if (!isSelf.value) {
        postData.ancestor = ancestor.value;
    }

    try {
        const { data, error } = await useApiFetch("/agent/apply")
            .post(postData)
            .json();

        if (data.value && !error.value) {
            if (data.value.code === 200) {
                showApplyPopup.value = false;
                showToast({ message: "申请提交成功" });

                // 保存token等信息
                // if (data.value.data?.accessToken) {
                //     localStorage.setItem('token', data.value.data.accessToken);
                //     localStorage.setItem('refreshAfter', data.value.data.refreshAfter);
                //     localStorage.setItem('accessExpire', data.value.data.accessExpire);
                // }

                // 显示成功信息
                showSuccessMessage.value = true;
            } else {
                // showToast({ message: data.value.message || "申请提交失败" });
            }
        }
    } catch (err) {
        console.error('申请提交出错', err);
        showToast({ message: "网络错误，请稍后重试" });
    }
};
</script>

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