import { request } from '../request';

// 获取登录URL
function getLoginUrl(): Promise<string> {
  return new Promise(resolve => {
    setTimeout(() => {
      try {
        const parameters = window.uiGlobalConfig?.Parameters;
        if (!parameters) {
          resolve('/auth/kivii');
          return;
        }
        const decodedStr = parameters.replace(/&quot;/g, '"');
        const parsedParams = JSON.parse(decodedStr);
        if (!parsedParams.loginUrl) {
          resolve('/auth/kivii');
          return;
        }

        resolve(parsedParams.loginUrl);
      } catch (error) {
        resolve('/auth/kivii');
      }
    }, 50);
  });
}

/**
 * Login
 *
 * @param userName User name
 * @param password Password
 */
export function fetchLogin(userName: string, password: string) {
  return getLoginUrl().then(loginUrl => {
    return request<Api.Auth.LoginToken>({
      url: loginUrl,
      method: 'post',
      data: {
        userName,
        password
      }
    });
  });
}

/** Get user info */
export function fetchGetUserInfo() {
  return request<Api.Auth.UserInfo>({ url: '/auth/getUserInfo' });
}

/**
 * Refresh token
 *
 * @param refreshToken Refresh token
 */
export function fetchRefreshToken(refreshToken: string) {
  return request<Api.Auth.LoginToken>({
    url: '/auth/refreshToken',
    method: 'post',
    data: {
      refreshToken
    }
  });
}

/**
 * return custom backend error
 *
 * @param code error code
 * @param msg error message
 */
export function fetchCustomBackendError(code: string, msg: string) {
  return request({ url: '/auth/error', params: { code, msg } });
}

/** 退出登录 */
export function fetchLogout() {
  return request({
    url: '/auth/logout.json',
    method: 'post'
  });
}
