/**
 * 该文件可自行根据业务逻辑进行调整
 */
import type {
  AxiosResponse,
  InternalAxiosRequestConfig,
  RequestClientOptions,
} from '@vben/request';
import {
  authenticateResponseInterceptor,
  errorMessageResponseInterceptor,
  RequestClient,
} from '@vben/request';

import { useAppConfig } from '@vben/hooks';
import { preferences } from '@vben/preferences';
import { useAccessStore } from '@vben/stores';

import { ElMessage } from 'element-plus';
 
import { useAuthStore } from '#/store';
import { isStringEmpty } from '#/utils';
import { LocationFilled } from '@element-plus/icons-vue';

const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);

/** 后端 301/302 到登录页时 URL 常为 .../public/login 或 .../Public/login（不区分大小写） */
const ADMIN_LOGIN_PATH_RE = /\/public\/login\b/i;

const REAUTH_LOG_SUPPRESS = '__suppressAuthLog';

type ReauthExtra = Record<string, unknown> & { [REAUTH_LOG_SUPPRESS]?: boolean };

function logRedirectToLogin(reason: string, extra?: Record<string, unknown>) {
  const copy = extra ? { ...extra } : {};
  delete (copy as ReauthExtra)[REAUTH_LOG_SUPPRESS];
  console.warn('[admin auth] redirect to login', { reason, ...copy });
}

function isPhpAdminSessionRedirectToLogin(response: AxiosResponse) {
  const finalUrl =
    typeof response.request?.responseURL === 'string'
      ? response.request.responseURL
      : '';
  const reqUrl = String(response.config?.url ?? '');
  const baseURL = String(response.config?.baseURL ?? '');
  const haystack = `${finalUrl} ${baseURL}${reqUrl} ${reqUrl}`;
  return ADMIN_LOGIN_PATH_RE.test(haystack);
}

/** axios 未跟随重定向时，用状态码 + Location 判断 */
function isRedirectToAdminLogin(error: any): boolean {
  const res = error?.response;
  if (!res) return false;
  const status = res.status;
  const loc = res.headers?.location ?? res.headers?.Location;
  const locStr = typeof loc === 'string' ? loc : '';
  const finalUrl = typeof res.responseURL === 'string' ? res.responseURL : '';

  if ([301, 302, 303, 307, 308].includes(status)) {
    if (ADMIN_LOGIN_PATH_RE.test(locStr) || ADMIN_LOGIN_PATH_RE.test(finalUrl)) {
      return true;
    }
  }
  return ADMIN_LOGIN_PATH_RE.test(finalUrl);
}

function rejectSessionHandledError() {
  const err = new Error('SESSION_EXPIRED');
  (err as any).isReAuthHandled = true;
  return Promise.reject(err);
}

function createRequestClient(baseURL: string, options?: RequestClientOptions) {
  const client = new RequestClient({
    ...options,
    baseURL,
  });

  /**
   * 增加ts时间戳防缓存
   */

  client.instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
    if ((config.method || 'get').toLocaleLowerCase() === 'get') {
      if (!config.params || typeof config.params !== 'object') { 
        config.params = {}
      }
      config.params.ts = Date.now()
    }
    return config;
  });


  /**
   * 重新认证逻辑
   */
  async function doReAuthenticate(
    reason = 'session-invalid',
    extra?: ReauthExtra,
  ) {
    if (!extra?.[REAUTH_LOG_SUPPRESS]) {
      logRedirectToLogin(reason, extra);
    }
    const accessStore = useAccessStore();
    const authStore = useAuthStore();
    accessStore.setAccessToken(null);
    if (
      preferences.app.loginExpiredMode === 'modal' &&
      accessStore.isAccessChecked
    ) {
      accessStore.setLoginExpired(true);
    } else {
      await authStore.logout();
    }
  }

  let reauthInFlight: Promise<void> | null = null;
  function doReAuthenticateOnce(reason: string, extra?: ReauthExtra) {
    if (!reauthInFlight) {
      reauthInFlight = doReAuthenticate(reason, extra).finally(() => {
        reauthInFlight = null;
      });
    }
    return reauthInFlight;
  }

  /**
   * 刷新token逻辑
   */
  async function doRefreshToken() {
    const accessStore = useAccessStore();
    // const resp = await reqAdmin.Auth$refresh$post();
    const resp = await client.instance.post('/admin/auth/refresh')
    const newToken = resp.data;
    accessStore.setAccessToken(newToken);
    return newToken;
  }

  function formatToken(token: null | string) {
    return token ? `Bearer ${token}` : null;
  }

  // 请求头处理
  client.addRequestInterceptor({
    fulfilled: async (config) => {
      /* const accessStore = useAccessStore();

                  config.headers.Authorization = formatToken(accessStore.accessToken); */
      config.headers['Accept-Language'] = preferences.app.locale;
      return config;
    },
  });

  // isGetListApi过滤get请求且含有分页或者无任何数据的列表请求
  client.commonHandleMsg = (
    jsonCode: int,
    jsonMsg: string,
    isGetListApi?: boolean,
  ) => {
    if (jsonCode >= 0) {
      if (!isGetListApi) {
        ElMessage({
          message: jsonMsg,
          type: 'success',
        });
      }
    } else if (jsonCode < 0) {
      ElMessage({
        message: jsonMsg,
        type: 'error',
      });
    }
  };

  client.socketApiGlobalEventHandler = (resp: object) => {
    const { action, ret } = resp;
    switch (action) {
      case 'error': {
        client.commonHandleMsg(ret.code, ret.msg);
        break;
      }
      default:
    }
  };

  // response数据解构
  client.addResponseInterceptor({
    fulfilled: async (response) => {
      // add 文件流
      if (response.config.responseType === 'blob') {
        return response.data;
      }

      if (isPhpAdminSessionRedirectToLogin(response)) {
        await doReAuthenticateOnce('response-final-url-public-login', {
          responseURL: response.request?.responseURL,
          requestUrl: response.config?.url,
        });
        return rejectSessionHandledError();
      }

      const respBodyJson = response.data;
      // 301 跟随重定向后常为 200 + HTML 字符串，按 JSON 接口约定视为未登录
      if (typeof respBodyJson === 'string') {
        await doReAuthenticateOnce('response-body-html-or-string', {
          responseURL: response.request?.responseURL,
          requestUrl: response.config?.url,
          bodyPreview: respBodyJson.slice(0, 120),
        });
        return rejectSessionHandledError();
      }
      if (
        respBodyJson === null ||
        typeof respBodyJson !== 'object' ||
        Array.isArray(respBodyJson)
      ) {
        await doReAuthenticateOnce('response-body-not-json-object', {
          responseURL: response.request?.responseURL,
          requestUrl: response.config?.url,
          dataType: respBodyJson === null ? 'null' : typeof respBodyJson,
        });
        return rejectSessionHandledError();
      }

      let { code, data, msg } = respBodyJson as {
        code?: unknown;
        data?: unknown;
        msg?: unknown;
      };
      client.commonHandleMsg(
        code,
        msg,
        (response.config.method?.toLocaleLowerCase() === 'post' &&
          ['object', 'string'].includes(Object.prototype.toString.call(response.config?.data).toLowerCase().slice(8, -1)) &&
          JSON.parse(response.config?.data)?.page
        ) ||
        (response.config.method?.toLocaleLowerCase() === 'get'),
      );
// 暂时不判断
// (response.config?.params?.page ||
//           Object.keys(response.config?.params || {}).length === 0)

      if (isStringEmpty(data)) {
        data = {};
      }
      if (typeof data === 'object') {
        respBodyJson.page && (data._page_ = respBodyJson.page); // add 分页数据 page
        data._code_ = code;
        data._msg_ = msg;
      }

      return data;
    },
  });

  // token过期的处理
  client.addResponseInterceptor(
    authenticateResponseInterceptor({
      client,
      doReAuthenticate: (cause?: string) => {
        const reason =
          cause === 'refresh-failed' ? 'refresh-token-failed' : 'http-401';
        return doReAuthenticate(reason);
      },
      doRefreshToken,
      enableRefreshToken: preferences.app.enableRefreshToken,
      formatToken,
    }),
  );

  // 通用的错误处理,如果没有进入上面的错误处理逻辑，就会进入这里
  client.addResponseInterceptor(
    errorMessageResponseInterceptor((msg: string, error) => {
      /**
       * PHP session 失效：可能直接返回 301/302 + Location 指向 public/login（axios 未跟随时）；
       * 或跟随重定向后在 fulfilled 里已处理。此处补齐错误分支。
       */
      if (isRedirectToAdminLogin(error)) {
        const res = error?.response;
        const detail = {
          status: res?.status,
          location: res?.headers?.location ?? res?.headers?.Location,
          responseURL: res?.responseURL,
          requestUrl: error?.config?.url,
        };
        logRedirectToLogin('http-error-redirect-to-login', detail);
        void doReAuthenticateOnce('http-error-redirect-to-login', {
          ...detail,
          [REAUTH_LOG_SUPPRESS]: true,
        });
        location.replace('/auth/login');
        return;
      }

      const url = error?.response?.responseURL;
      if (url && ADMIN_LOGIN_PATH_RE.test(String(url))) {
        const detail = {
          responseURL: url,
          requestUrl: error?.config?.url,
        };
        logRedirectToLogin('http-error-responseURL-public-login', detail);
        void doReAuthenticateOnce('http-error-responseURL-public-login', {
          ...detail,
          [REAUTH_LOG_SUPPRESS]: true,
        });
        location.replace('/auth/login');
        return;
      }

      // 这里可以根据业务进行定制,你可以拿到 error 内的信息进行定制化处理，根据不同的 code 做不同的提示，而不是直接使用 message.error 提示 msg
      // 当前mock接口返回的错误字段是 error 或者 message
      const errorMessage = error?.response?.data?.msg ?? null;
      // 如果没有错误信息，则会根据状态码进行提示
      ElMessage.error(errorMessage || msg);
    }),
  );

  return client;
}

export const requestClient = createRequestClient(apiURL, {
  // withCredentials: true, // send cookies when cross-domain requests
  headers: {
    'view-to-json-ver': 2, // 使用 第二个版本 新版 和 /bbs/ 一致 的标准
  },
  timeout: import.meta.env.PROD ? 60_000 : 10_000, // 正式 60s 超时
});
