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, PERM_KEY, TOKEN_KEY, USER_INFO_KEY } from '/@/enums/cacheEnum';
import { getAuthCache, setAuthCache } from '/@/utils/auth';
import { GetUserInfoModel, LoginParams } from '/@/api/sys/model/userModel';
// doLogout
import { getUserInfo, loginApi } from '/@/api/sys/user';
import { useI18n } from '/@/hooks/web/useI18n';
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 { intersection } from 'lodash-es';
import { h } from 'vue';

interface UserState {
  userInfo: Nullable<UserInfo>;
  token?: string;
  roleList: RoleEnum[];
  permList: number[];
  sessionTimeout?: boolean;
  lastUpdateTime: number;
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): UserState => ({
    // user info
    userInfo: null,
    // token
    token: undefined,
    // roleList
    roleList: [],
    permList: [],
    // Whether the login expired
    sessionTimeout: false,
    // Last fetch time
    lastUpdateTime: 0,
  }),
  getters: {
    getUserInfoCache(): UserInfo {
      return getAuthCache<UserInfo>(USER_INFO_KEY) || {};
    },
    getUserInfo(): UserInfo {
      return this.userInfo || getAuthCache<UserInfo>(USER_INFO_KEY) || {};
    },
    getToken(): string {
      return this.token || getAuthCache<string>(TOKEN_KEY);
    },
    getRoleList(): RoleEnum[] {
      return this.roleList.length > 0 ? this.roleList : getAuthCache<RoleEnum[]>(ROLES_KEY);
    },
    getPermList(): number[] {
      return this.permList.length > 0 ? this.permList : getAuthCache<number[]>(PERM_KEY);
    },
    getSessionTimeout(): boolean {
      return !!this.sessionTimeout;
    },
    getLastUpdateTime(): number {
      return this.lastUpdateTime;
    },
  },
  actions: {
    setToken(info: string | undefined) {
      this.token = info ? info : ''; // for null or undefined value
      localStorage.setItem('token', this.token);
      setAuthCache(TOKEN_KEY, info);
    },
    setRoleList(roleList: RoleEnum[]) {
      this.roleList = roleList;
      console.log('setRoleList', roleList);
      setAuthCache(ROLES_KEY, roleList);
    },
    setPermList(permList: number[]) {
      this.permList = permList;
      console.log('setPermList', permList);
      setAuthCache(PERM_KEY, permList);
    },
    setUserInfo(info: UserInfo | null) {
      this.userInfo = info;
      this.lastUpdateTime = new Date().getTime();
      setAuthCache(USER_INFO_KEY, info);
    },
    setSessionTimeout(flag: boolean) {
      this.sessionTimeout = flag;
    },
    resetState() {
      this.userInfo = null;
      this.token = '';
      this.roleList = [];
      this.sessionTimeout = false;
    },
    /**
     * @description: login
     */
    async login(
      params: LoginParams & {
        goHome?: boolean;
        mode?: ErrorMessageMode;
      },
    ): Promise<GetUserInfoModel | null> {
      try {
        const { goHome = true, mode, ...loginParams } = params;
        const data = await loginApi(loginParams, mode);
        const { id, token } = data;

        console.log('user', data);
        const userID = Number(id);

        // save token
        this.setToken(token);
        return this.afterLoginAction(userID, goHome);
      } catch (error) {
        return Promise.reject(error);
      }
    },
    async afterLoginAction(id: number, goHome?: boolean): Promise<GetUserInfoModel | null> {
      if (!this.getToken) return null;
      // get user info
      const userInfo = await this.getUserInfoAction(id);

      const sessionTimeout = this.sessionTimeout;
      if (sessionTimeout) {
        this.setSessionTimeout(false);
      } else {
        const permissionStore = usePermissionStore();
        if (!permissionStore.isDynamicAddedRoute) {
          const routes = await permissionStore.buildRoutesAction();
          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(id?: number): Promise<UserInfo | null> {
      if (!this.getToken) return null;
      const userId: number = id || Number(this.getUserInfoCache.id);
      // debugger;
      const userInfo = await getUserInfo(userId);
      const { roleIdList = [], permList = [] } = userInfo;
      isArray(roleIdList) && this.setPermList(permList);
      if (isArray(roleIdList)) {
        const roleList = roleIdList.map((item) => {
          switch (item) {
            case 1:
              return RoleEnum.SUPER;
            case 2:
              return RoleEnum.TOURIST;
            case 5:
              return RoleEnum.PLAT_ADMIN;
            case 6:
              return RoleEnum.COMPANY_ADMIN;
            case 7:
              return RoleEnum.COMPANY_ADMIN; //公司拍摄管理员
            case 8:
              return RoleEnum.STAFF;
            case 9:
              return RoleEnum.HOST;
            case 81:
              return RoleEnum.COMPANY_VIEWER;
            case 82:
              return RoleEnum.COMPANY_SHOOTER;
          }
        }) as RoleEnum[];
        console.log('roleIdList', roleList);
        this.setRoleList(roleList);
      } else {
        userInfo.roleIdList = [];
        this.setRoleList([]);
      }
      this.setUserInfo(userInfo);
      return userInfo;
    },
    /**
     * @description: logout
     */
    async logout(goLogin = false) {
      // if (this.getToken) {
      //   try {
      //     await doLogout();
      //   } catch {
      //     console.log('注销Token失败');
      //   }
      // }
      this.setToken(undefined);
      this.setSessionTimeout(false);
      this.setUserInfo(null);
      goLogin && router.push(PageEnum.BASE_LOGIN);
    },

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

    getCheckRole(value): boolean {
      const roleList = this.roleList;
      if (!value) {
        return true;
      }
      if (!isArray(value)) {
        return roleList?.includes(value as RoleEnum);
      }
      return (intersection(value, roleList) as RoleEnum[]).length > 0;
    },

    getEquity(value): boolean {
      //拍摄1  带看 2
      function isContained(a, b) {
        if (!(a instanceof Array) || !(b instanceof Array)) return false;
        if (a.length < b.length) return false;
        const aStr = a.toString();
        for (let i = 0, len = b.length; i < len; i++) {
          if (aStr.indexOf(b[i]) == -1) return false;
        }
        return true;
      }
      if (value.isArray) {
        return isContained(this.permList, value);
      } else {
        return isContained(this.permList, [value]);
      }
    },
  },
});

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