import UserApi, { WxLoginUsingGetResponse } from "@/apis/userApi";
import APPConfig from "@/config";
import { ILoginParms } from "@/pages/user/login";
import { reduxActions } from "@/redux";
import ReduxUtil from "@/utils/reduxUtil";
import RouteUtil from "@/utils/routeUtil";
import StorageUtil, { EStorage } from "@/utils/storageUtil";
import Taro from "@tarojs/taro";

export default class UserHelper {

    /**
     * 用户微信登录
     * @param code 小程序获取的Code
     */
    public static async userWxLogin(code: string) {
        let result = await UserApi.wxLoginUsingGet({ params: { code }, errorTips: true, loading: true }).toData();
        if (result) {
            this.cacheUserInfo(result);
            this.cacheTabMenu();
            return true;
        }
        return false;
    }

    public static async cacheUserInfo(userInfo: WxLoginUsingGetResponse) {
        StorageUtil.set(EStorage.userInfo, userInfo);
        this.cacheUserInfoToRedux(userInfo);
    }

    /**缓存到redux */
    public static async cacheUserInfoToRedux(userInfo: WxLoginUsingGetResponse) {
        ReduxUtil.dispatch(reduxActions.changeUserInfo(userInfo));
    }

    public static isLogin() {
        return !!ReduxUtil.store.getState().userInfo;
    }

    /**推出登录 */
    public static outLogin() {
        Taro.clearStorageSync();
        ReduxUtil.dispatch(reduxActions.clearState());
        RouteUtil.reLaunch("/pages/bottomNavBar/index");
    }

    static callback?: () => Promise<any>;


    public static afterLogin<T = any>(options: {
        toLoginPage?: boolean,
        callbackBeforeRoute?: boolean,
        pop?: boolean
    } & Omit<ILoginParms<T>, "callbackBeforeRoute" | "pop">) {
        const { toLoginPage = true, callback, callbackBeforeRoute = false, pop = true, page, params } = options;
        this.callback = callback;
        if (UserHelper.isLogin()) {
            callback?.();
        }
        else {
            toLoginPage && RouteUtil.push<ILoginParms>("/pages/user/login/index", {
                params: {
                    page: page,
                    params,
                    callbackBeforeRoute: callbackBeforeRoute ? 1 : 0,
                    pop: pop ? 1 : 0
                }
            });
        }
    }

    public static async cacheTabMenu() {
        await UserApi.homeTabUsingPost({
            data: { "appId": APPConfig.APPID }
        })
            .toData()
            .then(p => {
                if (p) {
                    StorageUtil.set(EStorage.tabMenu, p.tabMenus);
                    ReduxUtil.dispatch(reduxActions.changeTabMenu(p.tabMenus));
                }
            })
    }
};