import axios from 'axios'

const baseURL = import.meta.env.VITE_API_BASE_URL ?? '/api'

const dashboardApi = axios.create({
  baseURL,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器 - 添加认证头
dashboardApi.interceptors.request.use(
  (config) => {
    const apiKey = localStorage.getItem('apiKey')
    if (apiKey) {
      config.headers['X-API-Key'] = apiKey
    }
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  (error) => Promise.reject(error)
)

export interface KpiData {
  label: string
  value: number
  status: string
  hint: string
}

export interface ActivitySummary {
  id: number
  name: string
  startTime?: string
  endTime?: string
  participants: number
  shares: number
  conversions: number
}

export interface Alert {
  title: string
  detail: string
  type: string
  level: string
}

export interface Todo {
  id: string
  title: string
  description: string
  type: string
  link: string
  priority: string
}

export interface DashboardData {
  updatedAt: string
  kpis: KpiData[]
  activities: ActivitySummary[]
  alerts: Alert[]
  todos: Todo[]
}

interface ApiResponse<T> {
  code: number
  data: T
}

/**
 * 获取仪表盘数据
 */
export async function getDashboard(): Promise<DashboardData> {
  const response = await dashboardApi.get<ApiResponse<DashboardData>>('/dashboard')
  return response.data.data
}

/**
 * 获取KPI数据
 */
export async function getKpis(): Promise<KpiData[]> {
  const response = await dashboardApi.get<ApiResponse<KpiData[]>>('/dashboard/kpis')
  return response.data.data
}

/**
 * 获取活动统计
 */
export async function getActivitySummary() {
  const response = await dashboardApi.get('/dashboard/activities')
  return response.data
}

/**
 * 获取待办事项
 */
export async function getTodos(): Promise<Todo[]> {
  const response = await dashboardApi.get<ApiResponse<Todo[]>>('/dashboard/todos')
  return response.data.data
}

/**
 * 导出仪表盘数据
 */
export async function exportDashboard(format: string = 'csv'): Promise<Blob> {
  const response = await dashboardApi.get('/dashboard/export', {
    params: { format },
    responseType: 'blob'
  })
  return response as unknown as Blob
}

/**
 * 导出KPI数据
 */
export async function exportKpis(): Promise<Blob> {
  const response = await dashboardApi.get('/dashboard/kpis/export', {
    responseType: 'blob'
  })
  return response as unknown as Blob
}

/**
 * 导出活动数据
 */
export async function exportActivities(): Promise<Blob> {
  const response = await dashboardApi.get('/dashboard/activities/export', {
    responseType: 'blob'
  })
  return response as unknown as Blob
}

/**
 * 下载文件工具函数
 */
export function downloadBlob(blob: Blob, filename: string) {
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = filename
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  window.URL.revokeObjectURL(url)
}

export default {
  getDashboard,
  getKpis,
  getActivitySummary,
  getTodos,
  exportDashboard,
  exportKpis,
  exportActivities,
  downloadBlob
}
