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
   * @param [channelCode] 渠道号
   */
  public static async userWxLogin(code: string, channelCode: string = APPConfig.CHANNELCODE) {

    let result = await UserApi.wxLoginUsingGet({
      params: { code, channelCode },
      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();
    Taro.removeStorageSync('USER_INFO')
    Taro.removeStorageSync('TAB_MENU')
    ReduxUtil.dispatch(reduxActions.clearState());
    RouteUtil.reLaunch("/pages/bottomNavBar/index");
  }

  public static async UpdateOpenId () {
    return new Promise((resolve, reject) => {
      Taro.login({
        success: async function (login_res) {
          if (login_res.code) {
            await UserApi.wxUpdateOpenIdGet({
              params: { jsCode: login_res.code }
            }).toData().then(() => {
              resolve(login_res.code)
            })
          }
        },
        fail(res) {
          reject(res)
        },
      })
    })
  }
  
  static callback?: () => Promise<any>;
  

  public static async afterLogin<T = any>(
    options: {
      toLoginPage?: boolean;
      callbackBeforeRoute?: boolean;
      pop?: boolean;
      forceLogin?: boolean;
    } & Omit<ILoginParms<T>, "callbackBeforeRoute" | "pop">
  ) {
    const {
      toLoginPage = true,
      callback,
      callbackBeforeRoute = false,
      pop = true,
      forceLogin = true,
      page,
      params,
    } = options;
    const updateOpenId = () => {
      return new Promise((resolve, reject) => {
        Taro.login({
          success: async function (login_res) {
            if (login_res.code) {
              await UserApi.wxUpdateOpenIdGet({
                params: { jsCode: login_res.code }
              })
              resolve(login_res.code)
            }
          },
          fail(res) {
            reject(res)
          },
        })
      })
    }
    this.callback = callback;
    if (UserHelper.isLogin()) {
      await updateOpenId()
      callback?.();
    } else {
      await updateOpenId()
      if (forceLogin) {
        toLoginPage &&
          RouteUtil.push<ILoginParms>("/pages/user/login/index", {
            params: {
              page: page,
              params,
              callbackBeforeRoute: callbackBeforeRoute ? 1 : 0,
              pop: pop ? 1 : 0,
            },
          });
      } else {
        callback?.();
      }
    }
  }

  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));
        }
      });
  }
}
