import { loginApi } from '@/api/path'
import { useSystemStore } from '@/store/modules/systemStore/systemStore'
import { SystemStoreUserInfoEnum, SystemStoreEnum } from '@/store/modules/systemStore/systemStore.d'

let promise;

export async function refreshToken() {
  if (promise) {
    return promise;
  }
  const systemStore = useSystemStore()
  promise = new Promise(async (resolve) => {
    const res = await loginApi({username:'admin',password:'123456',__isRefreshToken: true})
    if(res && res.data) {
      const { tokenValue, tokenName } = res.data.token
      const { nickname, username, id } = res.data.userinfo
      // 存储到 pinia 
      systemStore.setItem(SystemStoreEnum.USER_INFO, {
        [SystemStoreUserInfoEnum.USER_TOKEN]: tokenValue,
        [SystemStoreUserInfoEnum.TOKEN_NAME]: tokenName,
        [SystemStoreUserInfoEnum.USER_ID]: id,
        [SystemStoreUserInfoEnum.USER_NAME]: username,
        [SystemStoreUserInfoEnum.NICK_NAME]: nickname,
      })
       resolve(res.code == 200);
    }
   
  });
  promise.finally(() => {
    promise = null;
  });
  return promise;
}

export function isRefreshRequest(config) {
  return !!config.__isRefreshToken; //两个取反，变成boolean
}
