import { appId, BASE_URL } from "../../env";
import { LoginRes } from "./login.d";
import { wxLogin, wxRequest } from "../../utils/wx-api";

const app = getApp<IAppOption>();
const WXROOM_REDIRECT_PATH_KEY = "wxroomRedirectPath";

Page({
    data: {
        back: "",
        agree: false,
        safeBottom: app.globalData.safeBottom,
    },

    buildQueryString(params: Record<string, any>): string {
        return Object.entries(params)
            .map(
                ([key, value]) =>
                    `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
            )
            .join("&");
    },

    redirectUrl() {
        const self = this;
        let fullPath = "";
        const tabPages = [
            "/pages/tab-bar/medicine-box/index",
            "/pages/tab-bar/shopping-cart/shopping-cart",
            "/pages/tab-bar/course/course",
            "/pages/tab-bar/user/user",
            "/pages/tab-bar/points-mall/points-mall",
            "/pages/tab-bar/category/category",
        ];

        if (self.data.back) {
            if (self.data.back === "wxroom") {
                fullPath =
                    wx.getStorageSync(WXROOM_REDIRECT_PATH_KEY) ||
                    "/package-live/wxroom/index";
                wx.removeStorageSync(WXROOM_REDIRECT_PATH_KEY);
            } else {
                const store = app.globalData.store;
                const state = wx.getStorageSync("state") ?? undefined;
                const code = wx.getStorageSync("code") ?? undefined;
                const groupId = wx.getStorageSync("groupId") ?? undefined;

                if (state && !code) {
                    if (self.data.back === "video") {
                        const storeParams =
                            typeof store === "string" ? store : this.buildQueryString(store);
                        fullPath = `/pages/live/video/video?${storeParams}`;
                    } else if (self.data.back === "red") {
                        fullPath = `/pages/common/red/red`;
                    } else if (self.data.back === "user") {
                        fullPath = `/pages/tab-bar/user/user`;
                    } else {
                        fullPath = `/pages/live/registration/registration?state=${state}`;
                    }
                } else if (!state && code) {
                    if (self.data.back === "video") {
                        const storeParams =
                            typeof store === "string" ? store : this.buildQueryString(store);
                        fullPath = `/pages/live/video/video?${storeParams}`;
                    } else if (self.data.back === "red") {
                        fullPath = `/pages/common/red/red`;
                    } else if (self.data.back === "user") {
                        fullPath = `/pages/tab-bar/user/user`;
                    } else {
                        fullPath = `/pages/live/registration/registration?code=${code}`;
                    }
                } else {
                    if (self.data.back === "room") {
                        fullPath = `/pages/live/room/room?groupId=${groupId}`;
                    } else if (self.data.back === "red") {
                        fullPath = `/pages/common/red/red`;
                    } else if (self.data.back === "user") {
                        fullPath = `/pages/tab-bar/user/user`;
                    }
                }
            }
        } else {
            const pages = getCurrentPages();
            const currentPage = pages[pages.length - 2];

            if (!currentPage) {
                const tabbarItems = app.globalData.tabbarItems;
                if (tabbarItems && tabbarItems.length > 0) {
                    wx.switchTab({ url: tabbarItems[0].pagePath });
                } else {
                    wx.switchTab({ url: "/pages/tab-bar/medicine-box/index" });
                }
                return;
            }

            const route = `/${currentPage.route}`;
            const options = currentPage.options || {};
            const query = this.buildQueryString(options);
            fullPath = query ? `${route}?${query}` : route;

            if (tabPages.includes(route)) {
                wx.switchTab({ url: route });
                return;
            }

            wx.redirectTo({ url: route });
            return;
        }

        if (tabPages.includes(fullPath)) {
            wx.switchTab({ url: fullPath });
        } else {
            wx.redirectTo({ url: fullPath });
        }
    },

    async handleLogin() {
        if (!this.data.agree) {
            wx.showModal({
                title: "请先勾选用户协议和隐私政策",
                icon: "none",
                success: (options) => {
                    if (options.confirm) {
                        this.setData({ agree: true });
                    }
                },
            });
            if (!this.data.agree) return;
        }

        try {
            wx.showLoading({ title: "登录中" });
            const loginRes = await wxLogin();
            if (!loginRes.code) throw new Error(loginRes.errMsg);

            const state = wx.getStorageSync("state");
            let loginResult: LoginRes;

            if (state) {
                loginResult = await wxRequest<LoginRes>({
                    url: `${BASE_URL}/api/auth/app-login?appId=${appId}&code=${loginRes.code}`,
                    method: "POST",
                    data: {
                        state: wx.getStorageSync("state") ?? undefined,
                    },
                });
            } else {
                loginResult = await wxRequest<LoginRes>({
                    url: `${BASE_URL}/api/auth/app-auth?appId=${appId}&code=${loginRes.code}`,
                    method: "POST",
                    data: {
                        state: wx.getStorageSync("code") ?? undefined,
                    },
                });
            }

            if (
                loginResult?.statusCode !== 200 ||
                (loginResult.data.code && loginResult.data.code !== 200)
            ) {
                throw new Error(loginResult?.data?.msg || "登录失败");
            }

            const {
                mpUserId,
                id,
                openId,
                unionId,
                nickName: resNickName,
                avatarUrl: resAvatarUrl,
            } = loginResult.data;

            const storageData = {
                openId,
                userId: mpUserId,
                mbuId: id,
                unionId,
                userName: resNickName,
                avatarUrl: resAvatarUrl,
            };

            Object.entries(storageData).forEach(([key, value]) => {
                wx.setStorageSync(key, value);
            });

            app.globalData.isLogin = true;
            wx.showToast({
                title: "登录成功",
                duration: 2000,
            });
            this.redirectUrl();

        } catch (err: any) {
            console.log("登录失败:", err);
            app.globalData.isLogin = false;
            wx.showToast({
                title: `登录失败：${err.message || err.errMsg}`,
                icon: "none",
            });
        } finally {
            setTimeout(() => wx.hideToast(), 3000);
        }
    },

    handleToggleAgree() {
        this.setData({ agree: !this.data.agree });
    },

    openPrivacyContract() {
        // @ts-ignore
        wx.openPrivacyContract();
    },

    onLoad(options: any) {
        if (options.back) {
            this.setData({ back: options.back });
        }
    },
});