import { MyResponseType } from '@/common';
import { Apis } from '@/gen/Apis';
import { state } from './state';

export const stateActions = {
  addLoading() {
    state.session.loading++;
  },
  subLoading() {
    state.session.loading--;
  },
  setReady(val: boolean) {
    state.session.ready = val;
  },
  setLogin(res: MyResponseType) {
    state.session.user = res.data.user;
    state.session.campus = res.data.campus;
    state.session.company_configs = res.data.company_configs;
    state.session.permissions = res.data.permissions;
    state.session.company = res.data.company;
    state.session.current_project = res.data.current_project;
    if (res.data?.token?.access_token)
      state.storage.access_token = res.data?.token?.access_token;
    // 解析apis
    const apiKeys: string[] = [];
    res.data.permissions.forEach((permission: any) => {
      if (permission.key) {
        apiKeys.push(permission.key);
      }
    });
    // console.log('apis', apis);
    state.session.apiKeys = apiKeys;
  },
  setLogout() {
    state.session.user = undefined;
    state.session.campus = undefined;
    state.session.permissions = undefined;
    state.storage.access_token = undefined;
  },
  me: async () => {
    const res = await Apis.Common.Auth.Me();
    if (res.success) {
      stateActions.setLogin(res);
      return {
        name: state.session.user.username,
        apiKeys: state.session.apiKeys,
        // permissions: res.data.permissions,
      };
    } else {
      return { name: '未登录', apiKeys: [] };
    }
  },
};
