import { Effect, Reducer } from 'umi';

import { queryCurrent, refreshToken } from '@/services/user';

export interface CurrentUser {
  id?: number;
  userNo?: string;
  userName?: string;
  role?: string;
  permission?: string;
}

export interface CurrentToken {
  accessToken?: string,
  refreshToken?: string,
}

export interface UserModelState {
  currentUser?: CurrentUser;
  token?: CurrentToken;
}

export interface UserModelType {
  namespace: 'user';
  state: UserModelState;
  effects: {
    fetchCurrent: Effect;
    refreshToken: Effect;
  };
  reducers: {
    saveCurrentUser: Reducer<UserModelState>;
    saveToken: Reducer<UserModelState>;
  };
}

const UserModel: UserModelType = {
  namespace: 'user',

  state: {
    currentUser: {},
    token: {},
  },

  effects: {
    *fetchCurrent(_, { call, put }) {
      const response = yield call(queryCurrent);
      yield put({
        type: 'saveCurrentUser',
        payload: response,
      });
    },
    *refreshToken(_, { call, put }) {
      const token = localStorage.getItem('refreshToken') || ''
      const param = {
        refreshToken: token
      }
      const response = yield call(refreshToken, param);
      yield put({
        type: 'saveToken',
        payload: response,
      });
    },
  },

  reducers: {
    saveCurrentUser(state, action) {
      return {
        ...state,
        currentUser: action.payload.data || {},
      };
    },
    saveToken(state, action) {
      if (action.payload.retcode) {
        localStorage.setItem('token', action.payload.data.accessToken)
        localStorage.setItem('expTime', `${new Date().getTime() + 28 * 60 * 1000}`)
      }
      return {
        ...state,
        token: action.payload.data || {},
      };
    }
  },
};

export default UserModel;
