// HTTP 请求封装
import { router } from 'expo-router';
import { Alert, Platform } from 'react-native';

import { COMMON_HEADER, SERVICE_URL } from './config';

export const SUCCESS_CODE = 0;
export const SUCCESS_CODE_200 = 200;
export const AUTH_INVALID = 401;
export const AUTH_INVALID_2 = 403;

interface RequestOptions {
  loading?: boolean;
  showMsg?: boolean;
  method?: 'GET' | 'POST';
  token?: string;
  silent?: boolean; // 静默模式，不显示错误提示
}

interface ApiResponse<T = any> {
  code: number;
  msg: string;
  data: T;
  success: boolean;
  count?: number;
}

// 存储 token
let authToken: string | null = null;

export const setToken = (token: string | null) => {
  authToken = token;
};

export const getToken = () => authToken;

export const clearToken = async () => {
  authToken = null;
};

// 处理认证失败
const handleAuthError = () => {
  setToken(null);
  // 跳转到登录页
  router.push('/login');
};

// 检查是否认证失败
const isAuthError = (code: number | string) => {
  const numCode = Number(code);
  return numCode === AUTH_INVALID || numCode === AUTH_INVALID_2;
};

// 检查是否成功的 code
const isSuccessCode = (code: number | string) => {
  const numCode = Number(code);
  return numCode === SUCCESS_CODE || numCode === SUCCESS_CODE_200;
};

// 显示错误提示（兼容 Web 和 Native）
const showErrorMessage = (msg: string) => {
  const message = msg || '请求失败，请稍后重试';
  if (Platform.OS === 'web') {
    // Web 环境使用 window.alert
    window.alert(message);
  } else {
    // Native 环境使用 Alert.alert
    Alert.alert('提示', message);
  }
};

// 基础请求方法
export const request = async <T = any>(
  url: string,
  data: any = {},
  options: RequestOptions = {}
): Promise<ApiResponse<T>> => {
  const { method = 'POST', silent = false } = options;

  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    track: JSON.stringify(COMMON_HEADER),
  };

  if (authToken) {
    headers.Authentication = authToken;
  }

  const fullUrl = url.startsWith('http') ? url : `${SERVICE_URL}${url}`;

  try {
    const config: RequestInit = {
      method,
      headers,
    };

    if (method === 'GET') {
      const params = new URLSearchParams();
      Object.keys(data).forEach((key) => {
        if (data[key] !== undefined && data[key] !== null) {
          params.append(key, String(data[key]));
        }
      });
      const queryString = params.toString();
      const requestUrl = queryString ? `${fullUrl}?${queryString}` : fullUrl;
      
      const response = await fetch(requestUrl, config);
      const result = await response.json();
      
      // 处理 401/403 认证失败（不显示错误提示，直接跳转登录）
      if (isAuthError(result.code)) {
        handleAuthError();
        return {
          code: result.code,
          msg: '登录已过期，请重新登录',
          data: null as any,
          success: false,
        };
      }

      const success = isSuccessCode(result.code);
      
      // 非成功状态且非静默模式，显示错误提示
      if (!success && !silent && result.msg) {
        showErrorMessage(result.msg);
      }
      
      return {
        ...result,
        success,
      };
    } else {
      config.body = JSON.stringify(data);
      const response = await fetch(fullUrl, config);
      const result = await response.json();
      
      // 打印接口返回内容
      console.log('[HTTP Response]', fullUrl, result);
      
      // 处理 401/403 认证失败（不显示错误提示，直接跳转登录）
      if (isAuthError(result.code)) {
        handleAuthError();
        return {
          code: result.code,
          msg: '登录已过期，请重新登录',
          data: null as any,
          success: false,
        };
      }

      const success = isSuccessCode(result.code);
      
      // 非成功状态且非静默模式，显示错误提示
      if (!success && !silent && result.msg) {
        console.log('[HTTP Error]', fullUrl, 'msg:', result.msg, 'silent:', silent);
        showErrorMessage(result.msg);
      }
      
      return {
        ...result,
        success,
      };
    }
  } catch (error) {
    console.error('Request error:', error);
    if (!silent) {
      showErrorMessage('网络异常，请检查网络连接');
    }
    return {
      code: -1,
      msg: '网络异常',
      data: null as any,
      success: false,
    };
  }
};

// GET 请求
export const get = <T = any>(url: string, params: any = {}, options: RequestOptions = {}) => {
  return request<T>(url, params, { ...options, method: 'GET' });
};

// POST 请求
export const post = <T = any>(url: string, data: any = {}, options: RequestOptions = {}) => {
  return request<T>(url, data, { ...options, method: 'POST' });
};

// 带 loading 的 GET 请求
export const getL = <T = any>(url: string, params: any = {}, options: RequestOptions = {}) => {
  return get<T>(url, params, { ...options, loading: true });
};

// 带 loading 的 POST 请求
export const postL = <T = any>(url: string, data: any = {}, options: RequestOptions = {}) => {
  return post<T>(url, data, { ...options, loading: true });
};
