/**
 * 全局调试工具 - 用于 App 端调试
 * 启用后会在控制台输出页面加载、参数和错误信息
 */

// 控制是否启用调试模式
import { onShow, onHide } from '@dcloudio/uni-app';

const DEBUG_ENABLED = true;

// 颜色代码
const colors = {
  page: '#4f46e5',
  param: '#059669',
  error: '#ef4444',
  warn: '#f59e0b',
  info: '#3b82f6',
  api: '#8b5cf6',
  apiResponse: '#10b981',
};

// 格式化日志前缀
function getPrefix(type: 'page' | 'param' | 'error' | 'warn' | 'info' | 'api' | 'apiResponse'): string {
  const prefixes = {
    page: '📱 [页面]',
    param: '📋 [参数]',
    error: '❌ [错误]',
    warn: '⚠️ [警告]',
    info: 'ℹ️ [信息]',
    api: '🚀 [API请求]',
    apiResponse: '✅ [API响应]',
  };
  return prefixes[type];
}

// 日志输出函数
function log(type: 'page' | 'param' | 'error' | 'warn' | 'info' | 'api' | 'apiResponse', message: string, data?: any) {
  if (!DEBUG_ENABLED) return;

  const prefix = getPrefix(type);
  const timestamp = new Date().toLocaleTimeString('zh-CN', { hour12: false });

  switch (type) {
    case 'page':
      console.log(`%c${timestamp} ${prefix} ${message}`, `color: ${colors[type]}; font-weight: bold;`, data || '');
      break;
    case 'param':
      console.log(`%c${timestamp} ${prefix} ${message}`, `color: ${colors[type]};`, data || '');
      break;
    case 'error':
      console.error(`%c${timestamp} ${prefix} ${message}`, `color: ${colors[type]}; font-weight: bold;`, data || '');
      break;
    case 'warn':
      console.warn(`%c${timestamp} ${prefix} ${message}`, `color: ${colors[type]};`, data || '');
      break;
    case 'info':
      console.info(`%c${timestamp} ${prefix} ${message}`, `color: ${colors[type]};`, data || '');
      break;
    case 'api':
      console.log(`%c${timestamp} ${prefix} ${message}`, `color: ${colors[type]}; font-weight: bold;`, data || '');
      break;
    case 'apiResponse':
      console.log(`%c${timestamp} ${prefix} ${message}`, `color: ${colors[type]}; font-weight: bold;`, data || '');
      break;
  }
}

// 获取当前页面信息
function getCurrentPageInfo(): { path: string; options: Record<string, any> } | null {
  const pages = getCurrentPages();
  if (pages.length === 0) return null;

  const currentPage = pages[pages.length - 1] as any;
  const pagePath = currentPage?.route || currentPage?.$page?.route || 'unknown';

  // #ifdef APP-PLUS
  const options = currentPage?.$page?.options || {};
  // #endif
  // #ifndef APP-PLUS
  const options = currentPage?.options || {};
  // #endif

  return { path: pagePath, options };
}

// 页面加载调试
function debugPageShow() {
  const pageInfo = getCurrentPageInfo();
  if (pageInfo) {
    log('page', `页面加载: /${pageInfo.path}`);
    if (Object.keys(pageInfo.options).length > 0) {
      log('param', '页面参数:', pageInfo.options);
    }
  }
}

// 全局错误处理
let originalOnError: any;
let originalOnShow: any;

function initGlobalErrorHandler() {
  // 捕获 unhandled promise errors
  if (typeof window !== 'undefined') {
    window.addEventListener('unhandledrejection', (event) => {
      log('error', '未处理的 Promise 错误', {
        reason: event.reason?.message || event.reason,
        stack: event.reason?.stack
      });
    });

    // 捕获全局错误
    window.addEventListener('error', (event) => {
      log('error', 'JavaScript 运行时错误', {
        message: event.message,
        filename: event.filename,
        lineno: event.lineno,
        colno: event.colno
      });
    });
  }

  // uni-app 全局错误回调
  uni.onError((error) => {
    log('error', 'uni-app 运行时错误', {
      message: error.message || error,
      stack: error.stack
    });
  });

  log('info', '全局调试工具已初始化', { platform: getPlatformName() });
}

// 获取平台名称
function getPlatformName(): string {
  // #ifdef APP-PLUS
  const systemInfo = uni.getSystemInfoSync();
  return `${systemInfo.platform} ${systemInfo.system} (App)`;
  // #endif
  // #ifdef H5
  return 'H5 (Web)';
  // #endif
  // #ifdef MP-WEIXIN
  return '微信小程序';
  // #endif
  return 'Unknown';
}

// 导出调试函数供其他模块使用
export function debugLog(type: 'page' | 'param' | 'error' | 'warn' | 'info', message: string, data?: any) {
  log(type, message, data);
}

// 导出页面信息获取函数
export function getPageInfo() {
  return getCurrentPageInfo();
}

// API 请求日志
export function debugApiRequest(method: string, url: string, data?: any) {
  log('api', `${method} ${url}`, {
    method,
    url,
    data: data ? (typeof data === 'object' ? data : JSON.parse(data)) : null,
    page: getCurrentPageInfo()
  });
}

// API 响应日志
export function debugApiResponse(method: string, url: string, response: any, duration?: number) {
  log('apiResponse', `${method} ${url}`, {
    method,
    url,
    status: response?.code,
    success: response?.code === 0,
    duration: duration ? `${duration}ms` : undefined,
    data: response?.data,
    message: response?.message,
    page: getCurrentPageInfo()
  });
}

// API 错误日志
export function debugApiError(method: string, url: string, error: any, duration?: number) {
  log('error', `${method} ${url} 失败`, {
    method,
    url,
    duration: duration ? `${duration}ms` : undefined,
    error: error?.message || error,
    page: getCurrentPageInfo()
  });
}

// 初始化调试功能
export function initDebug() {
  // 初始化错误处理
  initGlobalErrorHandler();

  // #ifdef APP-PLUS
  // 在 onShow 中记录页面切换
  onAppShow(() => {
    debugPageShow();
  });

  onAppShow(() => {
    log('info', 'App 从后台切换到前台');
  });

  onAppHide(() => {
    log('info', 'App 切换到后台');
  });
  // #endif

  // 拦截 navigateTo
  uni.addInterceptor('navigateTo', {
    invoke(options: any) {
      log('page', `navigateTo: /${options.url}`, {
        url: options.url,
        success: options.success,
        fail: options.fail
      });
      return options;
    },
    fail(err: any) {
      log('error', 'navigateTo 失败', err);
    }
  });

  // 拦截 redirectTo
  uni.addInterceptor('redirectTo', {
    invoke(options: any) {
      log('page', `redirectTo: /${options.url}`, { url: options.url });
      return options;
    },
    fail(err: any) {
      log('error', 'redirectTo 失败', err);
    }
  });

  // 拦截 switchTab
  uni.addInterceptor('switchTab', {
    invoke(options: any) {
      log('page', `switchTab: /${options.url}`, { url: options.url });
      return options;
    },
    fail(err: any) {
      log('error', 'switchTab 失败', err);
    }
  });

  // 拦截 reLaunch
  uni.addInterceptor('reLaunch', {
    invoke(options: any) {
      log('page', `reLaunch: /${options.url}`, { url: options.url });
      return options;
    },
    fail(err: any) {
      log('error', 'reLaunch 失败', err);
    }
  });

  // 拦截 navigateBack
  uni.addInterceptor('navigateBack', {
    invoke(options: any) {
      log('page', `navigateBack`, { delta: options.delta });
      return options;
    },
    fail(err: any) {
      log('error', 'navigateBack 失败', err);
    }
  });

  log('info', '导航拦截器已设置', [
    'navigateTo',
    'redirectTo',
    'switchTab',
    'reLaunch',
    'navigateBack'
  ]);
}

// App 生命周期监听
function onAppShow(callback: () => void) {
  // #ifdef APP-PLUS
  if (typeof plus !== 'undefined' && plus.App) {
    plus.App.addEventListener('resume', callback);
  }
  // #endif
}

function onAppHide(callback: () => void) {
  // #ifdef APP-PLUS
  if (typeof plus !== 'undefined' && plus.App) {
    plus.App.addEventListener('pause', callback);
  }
  // #endif
}

// 默认导出
export default {
  init: initDebug,
  log: debugLog,
  getPageInfo,
  apiRequest: debugApiRequest,
  apiResponse: debugApiResponse,
  apiError: debugApiError,
};