import type { UserInfo } from '/#/store';
import type { ErrorMessageMode } from '/#/axios';
import { defineStore } from 'pinia';
import { store } from '/@/store';
import { RoleEnum } from '/@/enums/roleEnum';
import { PageEnum } from '/@/enums/pageEnum';
import {
  ROLES_KEY,
  TOKEN_KEY,
  USER_INFO_KEY,
  LOGINTYPE_KEY,
  EXPRISEIN_KEY,
  REFRESH_TOKEN_KEY,
  PORTAL_KEY,
  TENANT_KEY,
} from '/@/enums/cacheEnum';
import { getAuthCache, setAuthCache } from '/@/utils/auth';
import { GetUserInfoModel, LoginParams } from '/@/api/sys/model/userModel';
import { Logout, Login, RefreshToken } from '/@/api/sys/oauthApi';
import { userLoginInfo } from '/@/api/sys/sysUserApi';
import { getUserPortalList } from '/@/api/sys/sysPortalApi';
import { useMessage } from '/@/hooks/web/useMessage';
import { router } from '/@/router';
import { usePermissionStore } from '/@/store/modules/permission';
import { RouteRecordRaw } from 'vue-router';
import { PAGE_NOT_FOUND_ROUTE } from '/@/router/routes/basic';
import { isArray } from '/@/utils/is';
import { h } from 'vue';
import locales from '/@/utils/locales';
import { useGlobSetting } from '/@/hooks/setting';
import { sysTenantQueryCurrent } from '@/api/sys/sysTenantApi';

interface UserState {
  userInfo: Nullable<UserInfo>;
  token?: string;
  refreshToken?: string;
  roleList: RoleEnum[];
  sessionTimeout?: boolean;
  lastUpdateTime: number;
  loginType: string | undefined;
  expiresIn?: number;
  portalList?: [];
  tenant?: undefined;
}
const globSetting = useGlobSetting();

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): UserState => ({
    // user info
    userInfo: null,
    // token
    token: undefined,
    // 刷新token
    refreshToken: undefined,
    // roleList
    roleList: [],
    // Whether the login expired
    sessionTimeout: false,
    // Last fetch time
    lastUpdateTime: 0,
    // loginType
    loginType: undefined,
    // 过期时间
    expiresIn: 0,
    // 门户列表
    portalList: [],
    // 当前租户信息
    tenant: undefined,
  }),
  getters: {
    getUserInfo(): UserInfo {
      return this.userInfo || getAuthCache<UserInfo>(USER_INFO_KEY) || {};
    },
    getToken(): string {
      return this.token || getAuthCache<string>(TOKEN_KEY);
    },
    getRefreshToken(): string {
      return this.refreshToken || getAuthCache<string>(REFRESH_TOKEN_KEY);
    },
    getRoleList(): RoleEnum[] {
      return this.roleList.length > 0 ? this.roleList : getAuthCache<RoleEnum[]>(ROLES_KEY);
    },
    getSessionTimeout(): boolean {
      return !!this.sessionTimeout;
    },
    getLastUpdateTime(): number {
      return this.lastUpdateTime;
    },
    getLoginType(): string {
      return this.loginType || getAuthCache<string>(LOGINTYPE_KEY);
    },
    getExpiresIn(): number {
      return this.expiresIn || Number(getAuthCache<string>(EXPRISEIN_KEY));
    },
    getTenant(): number {
      return this.tenant || getAuthCache(TENANT_KEY);
    },
  },
  actions: {
    setToken(info: string | undefined) {
      this.token = info ? info : ''; // for null or undefined value
      setAuthCache(TOKEN_KEY, info);
    },
    setRefreshToken(info: string | undefined) {
      this.refreshToken = info ? info : ''; // for null or undefined value
      setAuthCache(REFRESH_TOKEN_KEY, info);
    },
    setRoleList(roleList: RoleEnum[]) {
      this.roleList = roleList;
      setAuthCache(ROLES_KEY, roleList);
    },
    setPortalList(portalList: []) {
      this.roleList = portalList;
      setAuthCache(PORTAL_KEY, portalList);
    },
    setUserInfo(info: UserInfo | null) {
      this.userInfo = info;
      this.lastUpdateTime = new Date().getTime();
      setAuthCache(USER_INFO_KEY, info);
    },
    setSessionTimeout(flag: boolean) {
      this.sessionTimeout = flag;
    },
    // 登录类型
    setLoginType(info: string | undefined) {
      this.loginType = info ? info : '';
      setAuthCache(LOGINTYPE_KEY, info);
    },
    setExpiresIn(info: number | undefined) {
      this.expiresIn = info || 0;
    },
    setTenant(info: number | undefined) {
      this.tenant = info || {};
      setAuthCache(TENANT_KEY, info);
    },
    resetState() {
      this.userInfo = null;
      this.token = '';
      this.roleList = [];
      this.sessionTimeout = false;
      this.tenant = {};
    },
    /**
     * @description: login
     */
    async login(
      params: LoginParams & {
        goHome?: boolean;
        mode?: ErrorMessageMode;
      },
    ): Promise<GetUserInfoModel | null> {
      try {
        const { goHome = true, mode, ...loginParams } = params;
        const data = await Login(loginParams, mode);
        const { access_token, refresh_token, expires_in } = data;
        console.log('🚀 ~ file: user.ts:124 ~ data:', data);
        // save token
        this.setToken(access_token);
        this.setRefreshToken(refresh_token);
        // save loginType
        this.setLoginType('login');
        // token 过期时间
        this.setExpiresIn(expires_in);
        await router.replace(PageEnum.BASE_HOME);
        return this.afterLoginAction(goHome);
      } catch (error) {
        return Promise.reject(error);
      }
    },
    async afterLoginAction(goHome?: boolean): Promise<GetUserInfoModel | null> {
      if (!this.getToken) return null;
      // get user info
      const userInfo = await this.getUserInfoAction();
      // const userInfo = {
      //   roles: [{ roleName: 'admin', value: 'admin' }],
      //   userId: '123123',
      //   username: 'fanfan',
      //   realName: 'fanfan',
      //   homePath: PageEnum.BASE_HOME,
      //   avatar: '',
      // };
      // this.setUserInfo(userInfo);
      // getWebsocket();
      const sessionTimeout = this.sessionTimeout;
      console.log('🚀 ~ file: user.ts:152 ~ afterLoginAction ~ sessionTimeout:', sessionTimeout);
      if (sessionTimeout) {
        this.setSessionTimeout(false);
      } else {
        const permissionStore = usePermissionStore();
        if (!permissionStore.isDynamicAddedRoute) {
          const routes = await permissionStore.buildRoutesAction();
          console.log('🚀 ~ file: user.ts:152 ~ afterLoginAction ~ routes', routes);
          routes.forEach(route => {
            router.addRoute(route as unknown as RouteRecordRaw);
          });
          router.addRoute(PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw);
          permissionStore.setDynamicAddedRoute(true);
        }
        goHome && (await router.replace(userInfo?.homePath || PageEnum.BASE_HOME));
      }

      return userInfo;
    },
    async getUserInfoAction(): Promise<UserInfo | null> {
      // const userInfo = {
      //   roles: [{ roleName: 'admin', value: 'admin' }],
      //   userId: '123123',
      //   username: 'fanfan',
      //   realName: 'fanfan',
      //   homePath: PageEnum.BASE_HOME,
      //   avatar: '',
      // };
      // this.setUserInfo(userInfo);
      const userInfo = await userLoginInfo();
      const { roles = [] } = userInfo;
      if (isArray(roles)) {
        const roleList = roles.map(item => item.value) as RoleEnum[];
        this.setRoleList(roleList);
      } else {
        userInfo.roles = [];
        this.setRoleList([]);
      }
      const portalList = await getUserPortalList();
      if (portalList) {
        this.setPortalList(portalList);
        userInfo.portalList = portalList;
      }
      this.getTenantCurrent();
      this.setUserInfo(userInfo);
      return userInfo;
    },
    /**
     * @description 租户信息
     */
    async getTenantCurrent() {
      const tenantInfo = await sysTenantQueryCurrent();
      console.log('🚀 ~ file: user.ts:237 ~ getTenantCurrent ~ tenantInfo:', tenantInfo);
      this.setTenant(tenantInfo || {});
    },
    /**
     * @description 刷新token
     */
    async refreshToken() {
      console.log('刷新token');
      const data = {
        client_id: globSetting.clientId,
        client_secret: globSetting.clientSecret,
        refresh_token: this.refreshToken,
      };
      const res = await RefreshToken(data);
      if (res.access_token) {
        this.setToken(res.access_token);
        // token 过期时间
        this.setExpiresIn(res.expires_in);
      }
      return res;
    },
    /**
     * @description 退出登录
     * @param {boolean} [goLogin=false]
     */
    async logout(goLogin = false) {
      if (this.getToken) {
        try {
          await Logout();
        } catch {
          console.log('注销Token失败');
        }
      }
      this.setToken(undefined);
      this.setSessionTimeout(false);
      this.setUserInfo(null);
      this.setPortalList(null);
      goLogin && router.push(PageEnum.BASE_LOGIN);
    },

    /**
     * @description: Confirm before logging out
     */
    confirmLoginOut() {
      const { createConfirm } = useMessage();
      createConfirm({
        iconType: 'warning',
        title: () => h('span', locales.app.logoutTip),
        content: () => h('span', locales.app.logoutMessage),
        onOk: async () => {
          await this.logout(true);
        },
      });
    },
  },
});

// Need to be used outside the setup
export function useUserStoreWithOut() {
  return useUserStore(store);
}
