import type { MutationTree } from 'vuex';
import type { UserState } from './typing';
import { initState } from './state';
import {
  STORAGE_TOKEN_KEY,
  USER_INFO_KEY,
  HOME_ROUTER_KEY,
  STORAGE_LANG_KEY,
} from '@/store/mutation-type';
/* import ls from '@/utils/local-storage'; */
import { ls } from '@remote/icpx-platform/utils';

export const SET_TOKEN = 'SET_TOKEN';
export const SET_AVATAR = 'SET_AVATAR';
export const SET_ROLE = 'SET_ROLE';
export const SET_INFO = 'SET_INFO';
export const SET_ROUTERS = 'SET_ROUTERS';
export const RESET_CURRENT_USER = 'RESET_CURRENT_USER';
export const SET_MENU_AUTH_DATA = 'SET_MENU_AUTH_DATA';
export const SET_ROUTE_AUTH_DATA = 'SET_ROUTE_AUTH_DATA';
export const SET_ORG_NAME = 'SET_ORG_NAME';

export const mutations: MutationTree<UserState> = {
  [SET_TOKEN]: (state, token: string) => {
    state.token = token;
    ls.set(STORAGE_TOKEN_KEY, token);
  },
  [SET_INFO]: (state, info) => {
    ls.set(USER_INFO_KEY, JSON.stringify(info));
    for (const key in info) {
      // ls.set(key, info[key]);
      window.localStorage.setItem(key, info[key]);
    }
    if (info.role) {
      state.role = info.role;
    }
    if (info.user_name) {
      state.username = info.user_name;
    }
    if (info.user_name) {
      state.nickname = info.user_name;
    }
    if (info.avatar) {
      state.avatar = info.avatar;
    }
    if (info.lang) {
      ls.set(STORAGE_LANG_KEY, info.lang);
    } else {
      window.localStorage.setItem('lang', ls.get('app_lang'));
    }
    state.extra = { ...info };
  },
  [SET_ROLE]: (state, role) => {
    state.role = role;
  },
  [SET_AVATAR]: (state, avatar) => {
    state.avatar = avatar;
  },
  [SET_ROUTERS]: (state, allowRoutes) => {
    state.allowRouters = allowRoutes;
    sessionStorage.setItem(HOME_ROUTER_KEY, JSON.stringify(allowRoutes));
  },
  [RESET_CURRENT_USER]: state => {
    Object.assign(state, initState);
  },
  [SET_MENU_AUTH_DATA]: (state, menuAuth) => {
    state.menuAuth = menuAuth;
    ls.set('menuAuth', menuAuth);
  },
  [SET_ROUTE_AUTH_DATA]: (state, routeAuth) => {
    state.routeAuth = routeAuth;
  },
  [SET_ORG_NAME]: (state, orgName) => {
    state.orgName = orgName;
  },
};
