import { request } from '@/api/request'

/** 服务器类型 */
export interface ServerItem {
  id: number
  created_at: string
  updated_at: string
  deleted_at: string | null
  server_identity: string
  name: string
  host: string
  ip_address: string
  description: string
  os: string
  os_version: string
  kernel: string
  server_type: string
  tags: string
  location: string
  asset_id?: number
  remote_access: string
  remote_port: number
  agent_config: string
  status: string
  last_check_time: string
  collect_on: boolean
  collect_args: string
  collect_interval: number
  collect_last_result: string
  is_ip_scan_server: boolean
  ip_scan_port: number
}

/** 服务器列表响应 */
export interface ServerListResponse {
  total: number
  page: number
  page_size: number
  data: ServerItem[]
}

/** 服务器列表请求参数 */
export interface ServerListParams {
  page?: number
  size?: number
  keyword?: string
  collect_on?: boolean
  is_ip_scan_server?: boolean
}

/** 创建/更新服务器请求参数 */
export interface ServerFormData {
  server_identity?: string
  name?: string
  host?: string
  ip_address?: string
  description?: string
  os?: string
  os_version?: string
  kernel?: string
  server_type?: string
  tags?: string
  location?: string
  asset_id?: number
  remote_access?: string
  remote_port?: number
  agent_config?: string
  status?: string
  last_check_time?: string
  collect_on?: boolean
  collect_args?: string
  collect_interval?: number
  collect_last_result?: string
  is_ip_scan_server?: boolean
  ip_scan_port?: number
}

/** 获取服务器列表（分页） */
export const fetchServerList = (params?: ServerListParams) => {
  return request.get<ServerListResponse>('/DC-Control/v1/servers', { params })
}

/** 获取服务器详情 */
export const fetchServerDetail = (id: number) => {
  return request.get<ServerItem>(`/DC-Control/v1/servers/${id}`)
}

/** 创建服务器 */
export const createServer = (data: ServerFormData) => {
  return request.post<ServerItem>('/DC-Control/v1/servers', data)
}

/** 更新服务器 */
export const updateServer = (id: number, data: Partial<ServerFormData>) => {
  return request.put<{ message: string }>(`/DC-Control/v1/servers/${id}`, data)
}

/** 删除服务器 */
export const deleteServer = (id: number) => {
  return request.delete<{ message: string }>(`/DC-Control/v1/servers/${id}`)
}

/** 主机最新指标摘要（统计卡片，与 dc-control /servers/metrics/summary 一致） */
export interface HostMetricsUseStat {
  total_bytes: number
  used_bytes: number
  free_bytes: number
  used_percent: number
}

export interface HostMetricsDiskMount {
  mount: string
  total_bytes: number
  used_bytes: number
  free_bytes: number
  used_percent: number
}

export interface HostMetricsCpuCard {
  usage_percent: number
  logical_cores_total: number
  socket_count?: number
  physical_cores_total?: number
  physical_threads_total?: number
  cores_per_socket?: number
  threads_per_core?: number
}

export interface HostMetricsSummary {
  server_identity: string
  timestamp?: string
  has_data: boolean
  memory?: HostMetricsUseStat
  /** Swap / 虚拟内存，与 dc-control /servers/metrics/summary 一致 */
  swap?: HostMetricsUseStat
  disk_root?: HostMetricsDiskMount
  data_disks?: HostMetricsDiskMount[]
  cpu?: HostMetricsCpuCard
}

export interface HostNetworkTrafficPoint {
  time: string
  recv_mbps: number
  send_mbps: number
}

export interface HostNetworkTrafficPayload {
  server_identity: string
  hours: number
  /** 时间窗内是否有主机采集写入的网络累计指标行 */
  has_data: boolean
  /** 是否已根据相邻采样差分算出速率曲线（至少两个采样点） */
  has_rate_series?: boolean
  points: HostNetworkTrafficPoint[]
  note: string
}

/** 最新一批主机指标（用于监控大屏卡片） */
export const fetchServerMetricsSummary = (serverIdentity: string) => {
  return request.get<{ code: number; details?: HostMetricsSummary; message?: string }>('/DC-Control/v1/servers/metrics/summary', {
    params: { server_identity: serverIdentity },
  })
}

/** 立即拉取一次主机指标并返回最新统计卡片 */
export const collectServerMetricsNow = (serverIdentity: string) => {
  return request.post<{ code: number; details?: HostMetricsSummary; message?: string }>('/DC-Control/v1/servers/metrics/collect', {
    server_identity: serverIdentity,
  })
}

/** 近 N 小时网络收/发速率（Mbps，相邻采样字节差分） */
export const fetchServerNetworkTraffic = (serverIdentity: string, hours = 6) => {
  return request.get<{ code: number; details?: HostNetworkTrafficPayload; message?: string }>(
    '/DC-Control/v1/servers/metrics/network-traffic',
    { params: { server_identity: serverIdentity, hours } }
  )
}

/** 虚拟机资产概览 */
export interface VirtualOverviewPayload {
  vm_total: number
  asset_group_total: number
  online_total: number
  latest_timestamp?: string
  latest_cpu_usage_avg?: number
  latest_mem_usage_avg?: number
}

/** 物理机 24h 趋势点 */
export interface PhysicalUsagePoint {
  hour: string
  cpu_used_percent_avg: number | null
  mem_used_percent_avg: number | null
}

export interface PhysicalUsageTrendPayload {
  hours: number
  points: PhysicalUsagePoint[]
}

/** 资源总量项 */
export interface ResourceTotalGroup {
  server_type: 'physical' | 'virtual'
  server_count: number
  total_vcpu: number
  total_mem_bytes: number
}

/** 最新资源总量汇总 */
export interface LatestResourceSummaryPayload {
  physical: ResourceTotalGroup
  virtual: ResourceTotalGroup
}

/** 按资产聚合项 */
export interface AssetMixedSummaryItem {
  asset_id: number
  virtual_count: number
  physical_count: number
  physical_latest_cpu_usage?: number | null
  physical_latest_mem_usage?: number | null
}

export interface AssetMixedSummaryPayload {
  total: number
  data: AssetMixedSummaryItem[]
}

/** 接口1：虚拟机资产概览（支持分类筛选） */
export const fetchVirtualOverview = (category?: string) => {
  return request.get<{ code: number; details?: VirtualOverviewPayload; message?: string }>(
    '/DC-Control/v1/servers/assets/virtual/overview',
    { params: { category } }
  )
}

/** 接口2：physical 近24小时 CPU/内存趋势 */
export const fetchPhysicalUsageTrend24h = () => {
  return request.get<{ code: number; details?: PhysicalUsageTrendPayload; message?: string }>(
    '/DC-Control/v1/servers/physical/usage/trend-24h'
  )
}

/** 接口3：physical/virtual 最新资源总量 */
export const fetchLatestResourceSummary = () => {
  return request.get<{ code: number; details?: LatestResourceSummaryPayload; message?: string }>(
    '/DC-Control/v1/servers/resources/latest/summary'
  )
}

/** 接口4：按资产汇总 virtual 数量与 physical 最新指标 */
export const fetchAssetMixedSummary = () => {
  return request.get<{ code: number; details?: AssetMixedSummaryPayload; message?: string }>('/DC-Control/v1/servers/assets/mixed/summary')
}
