import { requestClient } from '#/api/request';

// 文件上传相关接口
export interface UploadFile {
  id: string;
  original_name: string;
  filename: string;
  path: string;
  url: string;
  mime_type: string;
  size: number;
  driver: string;
  created_at: string;
}

export interface UploadResponse {
  file: UploadFile;
  url: string;
}

// 字典相关接口
export interface Dictionary {
  id: string;
  parent_id?: string;
  name: string;
  code: string;
  value?: string;
  sort: number;
  status: number;
  remark?: string;
  children?: Dictionary[];
  created_at: string;
  updated_at: string;
}

export interface CreateDictionaryDto {
  parent_id?: string;
  name: string;
  code: string;
  value?: string;
  sort: number;
  status: number;
  remark?: string;
}

export interface UpdateDictionaryDto {
  parent_id?: string;
  name?: string;
  code?: string;
  value?: string;
  sort?: number;
  status?: number;
  remark?: string;
}

export interface DictionaryListParams {
  page?: number;
  limit?: number;
  name?: string;
  code?: string;
  status?: number;
  parent_id?: string;
}

// 系统日志相关接口
export interface SystemLog {
  id: string;
  user_id?: string;
  username?: string;
  action: string;
  method: string;
  url: string;
  ip: string;
  user_agent: string;
  request_data?: any;
  response_data?: any;
  status_code: number;
  duration: number;
  created_at: string;
}

export interface LogListParams {
  page?: number;
  limit?: number;
  user_id?: string;
  username?: string;
  action?: string;
  method?: string;
  status_code?: number;
  start_date?: string;
  end_date?: string;
}

// 系统信息接口
export interface SystemInfo {
  server: {
    arch: string;
    memory_usage: {
      external: number;
      heapTotal: number;
      heapUsed: number;
      rss: number;
    };
    node_version: string;
    os: string;
    uptime: number;
  };
  database: {
    size: string;
    type: string;
    version: string;
  };
  redis?: {
    connected_clients: number;
    memory: string;
    version: string;
  };
  application: {
    environment: string;
    name: string;
    timezone: string;
    version: string;
  };
}

// API 接口定义

// 文件上传接口
export const uploadFileApi = (file: File, type?: string) => {
  const formData = new FormData();
  formData.append('file', file);
  if (type) {
    formData.append('type', type);
  }
  return requestClient.post<UploadResponse>('/api/system/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
};

export const uploadMultipleFilesApi = (files: File[], type?: string) => {
  const formData = new FormData();
  files.forEach((file) => {
    formData.append('files', file);
  });
  if (type) {
    formData.append('type', type);
  }
  return requestClient.post<UploadResponse[]>(
    '/api/system/upload/multiple',
    formData,
    {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    },
  );
};

export const getFileListApi = (params: {
  filename?: string;
  limit?: number;
  page?: number;
  type?: string;
}) => {
  return requestClient.get<{
    limit: number;
    list: UploadFile[];
    page: number;
    total: number;
  }>('/api/system/files', { params });
};

export const deleteFileApi = (id: string) => {
  return requestClient.delete(`/api/system/files/${id}`);
};

// 字典管理接口
export const getDictionaryListApi = (params: DictionaryListParams) => {
  return requestClient.get<{
    limit: number;
    list: Dictionary[];
    page: number;
    total: number;
  }>('/api/system/dictionaries', { params });
};

export const getDictionaryTreeApi = (code?: string) => {
  return requestClient.get<Dictionary[]>('/api/system/dictionaries/tree', {
    params: { code },
  });
};

export const getDictionaryByIdApi = (id: string) => {
  return requestClient.get<Dictionary>(`/api/system/dictionaries/${id}`);
};

export const getDictionaryByCodeApi = (code: string) => {
  return requestClient.get<Dictionary[]>(
    `/api/system/dictionaries/code/${code}`,
  );
};

export const createDictionaryApi = (data: CreateDictionaryDto) => {
  return requestClient.post<Dictionary>('/api/system/dictionaries', data);
};

export const updateDictionaryApi = (id: string, data: UpdateDictionaryDto) => {
  return requestClient.put<Dictionary>(`/api/system/dictionaries/${id}`, data);
};

export const deleteDictionaryApi = (id: string) => {
  return requestClient.delete(`/api/system/dictionaries/${id}`);
};

// 系统日志接口
export const getSystemLogListApi = (params: LogListParams) => {
  return requestClient.get<{
    limit: number;
    list: SystemLog[];
    page: number;
    total: number;
  }>('/api/system/logs', { params });
};

export const getSystemLogByIdApi = (id: string) => {
  return requestClient.get<SystemLog>(`/api/system/logs/${id}`);
};

export const clearSystemLogsApi = (days?: number) => {
  return requestClient.delete('/api/system/logs/clear', {
    params: { days },
  });
};

export const exportSystemLogsApi = (params: LogListParams) => {
  return requestClient.get('/api/system/logs/export', {
    params,
    responseType: 'blob',
  });
};

// 系统信息接口
export const getSystemInfoApi = () => {
  return requestClient.get<SystemInfo>('/api/system/info');
};

// 健康检查接口
export const getHealthCheckApi = () => {
  return requestClient.get<{
    checks: {
      database: { responseTime?: number; status: 'down' | 'up' };
      disk: { status: 'critical' | 'ok' | 'warning'; usage: number };
      memory: { status: 'critical' | 'ok' | 'warning'; usage: number };
      redis?: { responseTime?: number; status: 'down' | 'up' };
    };
    status: 'error' | 'ok';
    timestamp: string;
    uptime: number;
  }>('/api/system/health');
};

// 缓存管理接口
export const getCacheInfoApi = () => {
  return requestClient.get<{
    hits: number;
    keys: number;
    memory: string;
    misses: number;
  }>('/api/system/cache/info');
};

export const clearCacheApi = (pattern?: string) => {
  return requestClient.delete('/api/system/cache/clear', {
    params: { pattern },
  });
};

// 系统配置接口
export const getSystemConfigApi = () => {
  return requestClient.get<Record<string, any>>('/api/system/config');
};

export const updateSystemConfigApi = (data: Record<string, any>) => {
  return requestClient.put('/api/system/config', data);
};

// 数据备份接口
export const createBackupApi = () => {
  return requestClient.post<{
    created_at: string;
    filename: string;
    size: number;
  }>('/api/system/backup');
};

export const getBackupListApi = () => {
  return requestClient.get<
    {
      created_at: string;
      filename: string;
      size: number;
    }[]
  >('/api/system/backup/list');
};

export const downloadBackupApi = (filename: string) => {
  return requestClient.get(`/api/system/backup/download/${filename}`, {
    responseType: 'blob',
  });
};

export const deleteBackupApi = (filename: string) => {
  return requestClient.delete(`/api/system/backup/${filename}`);
};

// 系统通知接口
export interface SystemNotification {
  id: string;
  title: string;
  content: string;
  type: 'error' | 'info' | 'success' | 'warning';
  is_read: boolean;
  created_at: string;
}

export const getNotificationListApi = (params: {
  is_read?: boolean;
  limit?: number;
  page?: number;
}) => {
  return requestClient.get<{
    list: SystemNotification[];
    total: number;
    unread_count: number;
  }>('/api/system/notifications', { params });
};

export const markNotificationReadApi = (id: string) => {
  return requestClient.post(`/api/system/notifications/${id}/read`);
};

export const markAllNotificationsReadApi = () => {
  return requestClient.post('/api/system/notifications/read-all');
};

export const deleteNotificationApi = (id: string) => {
  return requestClient.delete(`/api/system/notifications/${id}`);
};
