<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="displayStatus === 0" class="text-center">
                <span class="text-xs text-gray-500">您的申请正在审核中</span>
                <div class="bg-gray-200 p-1 rounded-3xl shadow-xl mt-1">
                    <div
                        class="text-xl font-bold px-8 py-2 bg-gray-400 text-white rounded-3xl shadow-lg cursor-not-allowed">
                        审核进行中
                    </div>
                </div>
            </div>

            <!-- 审核通过状态 -->
            <div v-if="displayStatus === 1" 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-if="displayStatus === 2" class="text-center">
                <span class="text-xs text-red-500">审核未通过，请重新提交</span>
                <div class="bg-red-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-red-500 to-red-300 text-white rounded-3xl shadow-lg cursor-pointer">
                        重新提交申请
                    </div>
                </div>
            </div>

            <!-- 未申请状态（包含邀请状态） -->
            <div v-if="displayStatus === 3" 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 { aesDecrypt } from "@/utils/crypto"
const showApplyPopup = ref(false)
const route = useRoute()
const router = useRouter()
import { storeToRefs } from 'pinia';
import { ref } from 'vue';
const store = useAgentStore();
const { status } = storeToRefs(store); // 响应式解构
const ancestor = ref("")
const isSelf = ref(false)
const agentApply = () => {
    showApplyPopup.value = true
}
// 计算显示状态（当isSelf为false时强制显示为3）
const displayStatus = computed(() => {
    return isSelf.value ? 3 : status.value
})

// 跳转到首页
const goToHome = () => {
    clearInterval(intervalId);
    router.push('/')
}
onBeforeMount(() => {
    if (route.name === "invitationAgentApplySelf") {
        isSelf.value = true
    } else {
        const linkIdentifier = route.params.linkIdentifier
        const decryptDataStr = aesDecrypt(decodeURIComponent(linkIdentifier), "8e3e7a2f60edb49221e953b9c029ed10")
        const decryptData = JSON.parse(decryptDataStr)
        ancestor.value = decryptData.mobile
    }
    const token = localStorage.getItem("token")
    if (token) {
        store.fetchAgentStatus();
    }

})
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
    }
    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: "已提交申请" });
            // refreshAgentStatus()
            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)
                refreshAgentStatus()
            }

        } else {
            console.log('申请失败', data.value);
        }
    }
};
let intervalId = null; // 保存定时器 ID

const refreshAgentStatus = () => {
    // 当 status.value 变化时（如通过监听或事件）
    if (status.value === 3) {
        // 清除已有定时器（避免重复创建）
        if (intervalId) clearInterval(intervalId);

        intervalId = setInterval(() => {
            // 每次执行前检查状态是否仍为 3
            if (status.value !== 3) {
                clearInterval(intervalId);
                intervalId = null;
                return;
            }
            store.fetchAgentStatus();
        }, 2000);
    } else {
        // 状态不是 3 时主动清除定时器
        if (intervalId) {
            clearInterval(intervalId);
            intervalId = null;
        }
    }
}
</script>

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