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

/** 存储设备服务项 */
export interface StorageItem {
  id: number
  created_at: string
  updated_at: string
  deleted_at: string | null
  service_identity: string
  oid: string
  server_identity: string
  name: string
  category: string
  type: string
  description: string
  enabled: boolean
  interval: number
  extra: string
  tags: string
  status_url: string
  agent_config: string
  collect_method: 'api' | 'snmp'
  snmp_target: string
  snmp_port: number
  snmp_version: 'v2c' | 'v3'
  snmp_community: string
  snmp_v3_security_level: string
  snmp_v3_security_name: string
  snmp_v3_auth_protocol: string
  snmp_v3_auth_password: string
  snmp_v3_priv_protocol: string
  snmp_v3_priv_password: string
  snmp_v3_context_name: string
  snmp_timeout_ms: number
  snmp_retries: number
  snmp_oids: string
  collect_on: boolean
  collect_args: string
  collect_interval: number
  collect_last_result: string
  status: string
  status_code: number
  status_message: string
  response_time: number
  last_check_time: string
  last_online_time: string | null
  last_offline_time: string | null
  continuous_errors: number
  uptime: number
}

/** 存储设备列表响应 */
export interface StorageListResponse {
  total: number
  page: number
  page_size: number
  data: StorageItem[]
}

/** 存储设备列表请求参数 */
export interface StorageListParams {
  page?: number
  size?: number
  keyword?: string
  enabled?: boolean
}

/** 创建存储设备请求参数 */
export interface StorageCreateData {
  service_identity?: string
  name: string
  category?: string
  type: string
  oid?: string
  server_identity?: string
  description?: string
  enabled?: boolean
  interval?: number
  extra?: string
  tags?: string
  status_url?: string
  agent_config?: string
  collect_method?: 'api' | 'snmp'
  snmp_target?: string
  snmp_port?: number
  snmp_version?: 'v2c' | 'v3'
  snmp_community?: string
  snmp_v3_security_level?: string
  snmp_v3_security_name?: string
  snmp_v3_auth_protocol?: string
  snmp_v3_auth_password?: string
  snmp_v3_priv_protocol?: string
  snmp_v3_priv_password?: string
  snmp_v3_context_name?: string
  snmp_timeout_ms?: number
  snmp_retries?: number
  snmp_oids?: string
  collect_on?: boolean
  collect_args?: string
  collect_interval?: number
  policy_ids?: number[]
}

/** 更新存储设备请求参数 */
export interface StorageUpdateData {
  service_identity?: string
  oid?: string
  server_identity?: string
  name?: string
  category?: string
  type?: string
  description?: string
  enabled?: boolean
  interval?: number
  extra?: string
  tags?: string
  status_url?: string
  agent_config?: string
  collect_method?: 'api' | 'snmp'
  snmp_target?: string
  snmp_port?: number
  snmp_version?: 'v2c' | 'v3'
  snmp_community?: string
  snmp_v3_security_level?: string
  snmp_v3_security_name?: string
  snmp_v3_auth_protocol?: string
  snmp_v3_auth_password?: string
  snmp_v3_priv_protocol?: string
  snmp_v3_priv_password?: string
  snmp_v3_context_name?: string
  snmp_timeout_ms?: number
  snmp_retries?: number
  snmp_oids?: string
  collect_on?: boolean
  collect_args?: string
  collect_interval?: number
  collect_last_result?: string
  status?: string
  status_code?: number
  status_message?: string
  response_time?: number
  last_check_time?: string
  last_online_time?: string | null
  last_offline_time?: string | null
  continuous_errors?: number
  uptime?: number
  policy_ids?: number[]
}

/** 指标项 */
export interface StorageMetricItem {
  metric_name: string
  metric_value: number
  metric_unit: string
}

/** 最新指标响应 */
export interface StorageMetricsLatestResponse {
  service_identity: string
  latest_timestamp: string | null
  count: number
  metrics: StorageMetricItem[]
}

/** 获取存储设备服务列表（匿名接口） */
export const fetchStorageList = (params?: StorageListParams) => {
  return request.get<StorageListResponse>('/DC-Control/v1/storage', { params })
}

/** 获取存储设备服务详情 */
export const fetchStorageDetail = (id: number) => {
  return request.get<StorageItem>(`/DC-Control/v1/storage/${id}`)
}

/** 创建存储设备服务 */
export const createStorage = (data: StorageCreateData) => {
  return request.post<{ message: string; id: number }>('/DC-Control/v1/storage', data)
}

/** 更新存储设备服务 */
export const updateStorage = (id: number, data: StorageUpdateData) => {
  return request.put<{ message: string }>(`/DC-Control/v1/storage/${id}`, data)
}

/** 删除存储设备服务 */
export const deleteStorage = (id: number) => {
  return request.delete<{ message: string }>(`/DC-Control/v1/storage/${id}`)
}

/** 查询最新一批时序指标 */
export const fetchStorageMetricsLatest = (serviceIdentity: string) => {
  return request.get<StorageMetricsLatestResponse>('/DC-Control/v1/storage/metrics/latest', {
    params: { service_identity: serviceIdentity },
  })
}

/** 监控大屏：下拉列表（JWT，模糊 keyword） */
export interface StorageMonitorOptionItem {
  service_identity: string
  name: string
  type: string
  server_identity: string
  status: string
}

/** 监控大屏：汇总 current.host（与后端 storage_monitor 一致） */
export interface StorageMonitorSummaryHost {
  has_data: boolean
  cpu_usage_percent?: number | null
  memory_usage_percent?: number | null
  swap_usage_percent?: number | null
  disk_root_used_percent?: number | null
  disk_root_avail_percent?: number | null
  host_server_identity?: string
  host_summary_timestamp?: string | null
}

export interface StorageMonitorSummaryCurrent {
  service_identity: string
  controller_status: string
  server_identity: string
  host?: StorageMonitorSummaryHost | null
}

export interface StorageMonitorSummaryPayload {
  total_devices: number
  online_count: number
  offline_count: number
  other_count: number
  current?: StorageMonitorSummaryCurrent | null
}

export const fetchStorageMonitorList = (params?: { keyword?: string; limit?: number }) => {
  return request.get<{
    code: number
    details?: { data: StorageMonitorOptionItem[]; count: number }
    message?: string
  }>('/DC-Control/v1/storage/monitor/list', { params })
}

export const fetchStorageMonitorSummary = (serviceIdentity?: string) => {
  return request.get<{
    code: number
    details?: StorageMonitorSummaryPayload
    message?: string
  }>('/DC-Control/v1/storage/monitor/summary', {
    params: serviceIdentity ? { service_identity: serviceIdentity } : {},
  })
}

/** 监控页：按存储设备 id 拉取最新一批中的指标名（趋势图下拉） */
export interface StorageMonitorCollectedMetricItem {
  metric_name: string
  metric_unit?: string
  type?: string
}

export interface StorageMonitorCollectedMetricsPayload {
  service_identity: string
  metrics: StorageMonitorCollectedMetricItem[]
  count: number
}

export const fetchStorageMonitorCollectedMetrics = (deviceId: number) => {
  return request.get<{
    code: number
    details?: StorageMonitorCollectedMetricsPayload
    message?: string
  }>(`/DC-Control/v1/storage/monitor/metrics/collected/${deviceId}`)
}

/** 存储指标匿名聚合（告警/大屏用） */
export interface StorageMetricsAggregateParams {
  service_identity: string
  metric_name: string
  start_time: string
  end_time: string
  aggregation: 'avg' | 'max' | 'min' | 'sum' | 'count'
}

export interface StorageMetricsAggregateDetails {
  aggregation: string
  value: number
  service_identity: string
  metric_name: string
  category?: string
  start_time: string
  end_time: string
}

/** 与 DC-Hardware GET /metrics/devices/:device_id 对齐：路径 service_identity，Query 可选 */
export interface StorageMetricsTimeseriesQuery {
  start_time?: string
  end_time?: string
  metric_name?: string
}

/** 原始样本（control_storage_metrics_data） */
export interface StorageMetricsRawRow {
  timestamp: string
  service_identity: string
  server_identity?: string
  type: string
  metric_name: string
  metric_value: number
  metric_unit?: string
}

export const fetchStorageMetricsAggregate = (params: StorageMetricsAggregateParams) => {
  return request.get<{ code: number; details?: StorageMetricsAggregateDetails; message?: string }>(
    '/DC-Control/v1/services/metrics/storage/aggregate',
    { params: { ...params, category: 'storage' } }
  )
}

/** 存储指标时序原始点（JWT）；路径为 service_identity，需 URL 编码 */
export const fetchStorageMetricsTimeseries = (serviceIdentity: string, params?: StorageMetricsTimeseriesQuery) => {
  const path = encodeURIComponent(serviceIdentity)
  return request.get<{
    code: number
    details?: {
      service_identity: string
      start_time: string
      end_time: string
      count: number
      metrics: StorageMetricsRawRow[]
    }
    message?: string
  }>(`/DC-Control/v1/storage/monitor/metrics/timeseries/${path}`, {
    params,
  })
}

/** 采集配置补丁 */
export interface StoragePatchData {
  collect_method?: 'api' | 'snmp'
  agent_config?: string
  snmp_target?: string
  snmp_port?: number
  snmp_version?: 'v2c' | 'v3'
  snmp_community?: string
  snmp_v3_security_level?: string
  snmp_v3_security_name?: string
  snmp_v3_auth_protocol?: string
  snmp_v3_auth_password?: string
  snmp_v3_priv_protocol?: string
  snmp_v3_priv_password?: string
  snmp_v3_context_name?: string
  snmp_timeout_ms?: number
  snmp_retries?: number
  snmp_oids?: string
  collect_on?: boolean
  collect_interval?: number
}

/** 采集配置补丁更新 */
export const patchStorage = (id: number, data: StoragePatchData) => {
  return request.patch<{ message: string }>(`/DC-Control/v1/storage/${id}/collect`, data)
}
