import axios from 'axios';
import { GadminCrud as gadminDataProvider } from '@gadmin2/react-common';
import { HttpError } from '@refinedev/core';
import { getApiUrl, getUrlParams } from './utils';
import Cookies from 'js-cookie';

export const GAdminTokenName = 'gadmin-token';

type LoginCookie = {
  gadminToken?: string;
};

const axiosInstance = axios.create();

axiosInstance.interceptors.request.use(
  (config) => {
    if (config.headers) {
      const headers = requestHeaders();
      Object.assign(config.headers, headers);
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

axiosInstance.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error?.response?.status === 401) {
      console.log('login expired');
      login();
      // 返回pending状态的promise，以免后续代码出错
      return new Promise(() => {});
    }
    let message = error.response?.data?.message;
    if (message) {
      if (Array.isArray(message)) {
        message = message.join(' AND ');
      } else if (typeof message === 'string') {
        if (message.includes('Unique constraint')) {
          message = `Unique constraint ${message.split('Unique constraint')[1]}`;
        } else {
          let strings = message.split(')');
          message = strings[strings.length - 1];
        }
      }
    }
    const customError: HttpError = {
      ...error,
      message: `${error?.response?.statusText || ''}: ${message}`,
      statusCode: error?.response?.status || 500,
    };

    return Promise.reject(customError);
  }
);

const apiUrl = getApiUrl();
export const gadminCrudProvider = gadminDataProvider(apiUrl, axiosInstance);

export function login() {
  // woa域名直接刷新页面
  if (window.location.hostname.endsWith('.woa.com')) {
    window.location.reload();
    return;
  }
  clearLoginCookie();
  window.location.href = `${apiUrl}/login?redirect_url=${encodeURIComponent(window.location.href)}`;
}

export function logout() {
  clearLoginCookie();
  window.location.href = `${apiUrl}/logout?redirect_url=${encodeURIComponent(
    window.location.origin
  )}`;
}

/**
 * 通过cookie检测是否登录及参数转cookie(for dev)
 */
export function checkLogin(): boolean {
  if (window.location.hostname.endsWith('.woa.com')) {
    return true;
  }

  if (Cookies.get(GAdminTokenName)) {
    return true;
  }

  const params = getUrlParams();
  const gadminToken = params[GAdminTokenName];
  if (gadminToken) {
    setLoginCookie({ gadminToken });
    return true;
  }

  return false;
}

export function setLoginCookie({ gadminToken }: Required<LoginCookie>) {
  const expires = 1; // 本地登录态缓存1天
  Cookies.set(GAdminTokenName, gadminToken, { expires });
}

export function clearLoginCookie() {
  Cookies.remove(GAdminTokenName);
}

export function requestHeaders() {
  const gadminToken = Cookies.get(GAdminTokenName);
  const headers = {
    'X-Requested-With': 'XMLHttpRequest',
    ...(gadminToken && { [GAdminTokenName]: gadminToken }),
  };
  return headers;
}
