<script setup>
import { login, bindCard } from "@/api";

import { useRouter, useRoute } from 'vue-router';

const route = useRoute();
const router = useRouter();

const liff = window.liff;

try {
    if (!liff.isLoggedIn()) liff.login({ redirectUri: window.location.href });
} catch (err) {
    console.log(`liff.state init error ${err}`);
    showToast("登入失敗。請聯絡管理員");
    router.push("/login");
}


if (!sessionStorage.getItem("token")) { // 未登入先要登入
    const profile = await liff.getProfile();

    const id_token = liff.getIDToken();

    let loginRes = await login({ line_id: profile.userId, token: id_token });

    if (loginRes.code === 200) {
        if (route.query.act === "openright") {
            showToast("您已經是本站會員");
        }
        sessionStorage.setItem("token", loginRes.data.token);
        sessionStorage.setItem("uid", loginRes.data.uid);
    } else if (loginRes.code === 202) { // 未綁定卡片
        if (route.query.act === "openright") {
            if (route.query.verify) {
                //詢問是否綁定
                Dialog.confirm({
                    title: "卡片綁定",
                    message: "確認是否綁定這張卡片",
                })
                    .then(async () => {
                        //確認綁定
                        let bindRes = await bindCard({
                            uid: loginRes.data.uid,
                            verify: route.query.verify,
                        });
                        if (bindRes.code === 200) {
                            showSuccessToast("綁定成功");
                        } else {
                            showToast.fail("綁定失敗");
                        }
                    })
                    .catch(() => { });
            }
        }

        sessionStorage.setItem("token", loginRes.data.token);
        sessionStorage.setItem("uid", loginRes.data.uid);
    } else if (loginRes.code === 201) { // 非會員
        if (route.query.act === "openright") {  // 開卡
            if (route.query.verify || route.query.user_id) {
                router.push({
                    path: "/register",
                    query: {
                        verify: route.query.verify,
                        user_id: route.query.user_id,
                    },
                });
            }
        } else if (route.query.aid) { // 會員註冊
            router.push({
                path: "/register",
                query: {
                    aid: route.query.aid,
                },
            });
        } else {
            showToast("請先註冊成為本站會員");
            router.push({
                path: "/register",
                query: { refer: route.query.refer },
            });
        }
    } else {
        showToast("登入失敗。請聯絡管理員");
        router.push("/login");
    }
}

// 如果存在redirect，就跳轉
if (sessionStorage.getItem("redirect")) {
    router.push(sessionStorage.getItem("redirect"));
    sessionStorage.removeItem("redirect");
} else {
    router.push("/");
}
</script>
