<script setup>
import { ref, onMounted, onBeforeMount } from "vue";
import { useRoute } from "vue-router";
import { storeToRefs } from 'pinia';
import { useUserStore } from '@/stores/userStore';
import { useDialogStore } from '@/stores/dialogStore';
import InquireForm from "@/components/InquireForm.vue";
import LoginDialog from "@/components/LoginDialog.vue";

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const dialogStore = useDialogStore();
const { mobile: userStoreMobile } = storeToRefs(userStore);

const linkIdentifier = ref("");
const feature = ref("");
const featureData = ref({});

onBeforeMount(async () => {
    await getProduct();
});

onMounted(() => {
    isFinishPayment();
});

function isFinishPayment() {
    const query = new URLSearchParams(window.location.search);
    let orderNo = query.get("out_trade_no");
    if (orderNo) {
        router.push({ path: "/report", query: { orderNo } });
    }
}

async function getProduct() {
    linkIdentifier.value = route.params.linkIdentifier;
    const { data: agentLinkData, error: agentLinkError } = await useApiFetch(
        `/agent/link?link_identifier=${linkIdentifier.value}`
    )
        .get()
        .json();
    if (agentLinkData.value && !agentLinkError.value) {
        if (agentLinkData.value.code === 200) {
            feature.value = agentLinkData.value.data.product_en;
            featureData.value = agentLinkData.value.data;
            // 确保 FLXG0V4B 排在首位
            if (
                featureData.value.features &&
                featureData.value.features.length > 0
            ) {
                featureData.value.features.sort((a, b) => {
                    if (a.api_id === "FLXG0V4B") return -1;
                    if (b.api_id === "FLXG0V4B") return 1;
                    return 0;
                });
            }
        }
    }
}
</script>

<template>
    <InquireForm :type="'promotion'" :feature="feature" :link-identifier="linkIdentifier" :feature-data="featureData" />
    <LoginDialog />
</template>