/**
 * 设备模拟模块 API 调用封装
 *
 * @author czj
 * @date 2026-07-29
 */

import request from '@/utils/request'
import type {
  EnvConfig,
  EnvConfigCreate,
  EnvConfigUpdate,
  EnvConfigListResponse,
  Simulator,
  SimulatorCreate,
  SimulatorUpdate,
  SimulatorListResponse,
  ReportLogListResponse,
  ManualReportRequest,
  TestConnectionResponse,
  TopicTemplateListResponse,
  DeviceImportResponse,
} from '@/types/device'

const BASE = '/api/device-sim'

// ==================== 环境配置 API ====================

/** 获取环境配置列表 */
export function listEnvConfigs(params?: { skip?: number; limit?: number }): Promise<EnvConfigListResponse> {
  return request.get(`${BASE}/env-configs`, { params })
}

/** 获取环境配置详情 */
export function getEnvConfig(id: string): Promise<EnvConfig> {
  return request.get(`${BASE}/env-configs/${id}`)
}

/** 创建环境配置 */
export function createEnvConfig(data: EnvConfigCreate): Promise<EnvConfig> {
  return request.post(`${BASE}/env-configs`, data)
}

/** 更新环境配置 */
export function updateEnvConfig(id: string, data: EnvConfigUpdate): Promise<EnvConfig> {
  return request.put(`${BASE}/env-configs/${id}`, data)
}

/** 删除环境配置 */
export function deleteEnvConfig(id: string): Promise<void> {
  return request.delete(`${BASE}/env-configs/${id}`)
}

/** 测试 MQTT 连接 */
export function testEnvConnection(id: string): Promise<TestConnectionResponse> {
  return request.post(`${BASE}/env-configs/${id}/test`)
}

// ==================== 模拟设备 API ====================

/** 获取模拟设备列表 */
export function listSimulators(params?: {
  skip?: number
  limit?: number
  deviceType?: string
  envConfigId?: string
  status?: string
}): Promise<SimulatorListResponse> {
  // 转换参数名为 snake_case（后端要求）
  const snakeParams: Record<string, any> = {}
  if (params?.skip !== undefined) snakeParams.skip = params.skip
  if (params?.limit !== undefined) snakeParams.limit = params.limit
  if (params?.deviceType !== undefined) snakeParams.device_type = params.deviceType
  if (params?.envConfigId !== undefined) snakeParams.env_config_id = params.envConfigId
  if (params?.status !== undefined) snakeParams.status = params.status
  return request.get(`${BASE}/devices`, { params: snakeParams })
}

/** 获取模拟设备详情 */
export function getSimulator(id: string): Promise<Simulator> {
  return request.get(`${BASE}/devices/${id}`)
}

/** 创建模拟设备 */
export function createSimulator(data: SimulatorCreate): Promise<Simulator> {
  return request.post(`${BASE}/devices`, data)
}

/** 更新模拟设备 */
export function updateSimulator(id: string, data: SimulatorUpdate): Promise<Simulator> {
  return request.put(`${BASE}/devices/${id}`, data)
}

/** 删除模拟设备 */
export function deleteSimulator(id: string): Promise<void> {
  return request.delete(`${BASE}/devices/${id}`)
}

/** 启动模拟设备 */
export function startSimulator(id: string): Promise<{ message: string; id: string; status: string }> {
  return request.post(`${BASE}/devices/${id}/start`)
}

/** 停止模拟设备 */
export function stopSimulator(id: string): Promise<{ message: string; id: string; status: string }> {
  return request.post(`${BASE}/devices/${id}/stop`)
}

/** 切换中控设备类型 */
export function switchDeviceType(id: string, deviceTypeName: string): Promise<{
  device_id: string
  device_type: string
  was_running: boolean
  message: string
}> {
  return request.patch(`${BASE}/devices/${id}/type`, null, {
    params: { device_type_name: deviceTypeName }
  })
}

/** 手动触发上报 */
export function manualReport(id: string, data: ManualReportRequest): Promise<{ message: string; success: boolean }> {
  return request.post(`${BASE}/devices/${id}/report`, data)
}

// ==================== 上报记录 API ====================

/** 获取上报记录列表 */
export function listReportLogs(params?: {
  deviceId?: string
  direction?: string
  skip?: number
  limit?: number
  startTime?: string
  endTime?: string
}): Promise<ReportLogListResponse> {
  return request.get(`${BASE}/report-logs`, { params })
}

/** 清理过期上报记录 */
export function cleanupReportLogs(days: number = 7): Promise<{ message: string; cleanedCount: number }> {
  return request.delete(`${BASE}/report-logs/cleanup`, { params: { days } })
}

// ==================== 主题模板 API ====================

/** 获取设备类型的主题模板 */
export function getTopicTemplates(deviceType: string): Promise<TopicTemplateListResponse> {
  return request.get(`${BASE}/topic-templates/${deviceType}`)
}

// ==================== 批量操作 API ====================

/** 批量启动设备 */
export function batchStartDevices(deviceIds: string[]): Promise<{successCount: number, failedCount: number, failedIds: string[], message: string}> {
  return request.post(`${BASE}/devices/batch/start`, { deviceIds })
}

/** 批量停止设备 */
export function batchStopDevices(deviceIds: string[]): Promise<{successCount: number, failedCount: number, failedIds: string[], message: string}> {
  return request.post(`${BASE}/devices/batch/stop`, { deviceIds })
}

/** 批量删除设备 */
export function batchDeleteDevices(deviceIds: string[]): Promise<{successCount: number, failedCount: number, failedIds: string[], message: string}> {
  return request.delete(`${BASE}/devices/batch`, { data: { deviceIds } })
}

// ==================== WebSocket 消息流 ====================

/** 设备消息类型 */
export interface DeviceMessage {
  event: string
  data?: {
    device_id: string
    device_name: string
    device_type: string
    topic: string
    direction: 'publish' | 'subscribe'
    payload: Record<string, any>
    timestamp: string
  }
  message?: string
}

/** 创建 WebSocket 连接获取实时消息 */
export function createMessageStream(
  onMessage: (msg: DeviceMessage) => void,
  onError?: (error: Event) => void
): WebSocket {
  const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
  const host = window.location.host
  const ws = new WebSocket(`${protocol}//${host}/api/device-sim/ws/messages`)

  ws.onmessage = (event) => {
    try {
      const msg = JSON.parse(event.data) as DeviceMessage
      onMessage(msg)
    } catch (e) {
      console.error('解析 WebSocket 消息失败', e)
    }
  }

  ws.onerror = (error) => {
    console.error('WebSocket 错误', error)
    onError?.(error)
  }

  return ws
}

// ==================== 批量导入 API ====================

/** 批量导入设备（Excel） */
export function importDevices(file: File, deviceType: string): Promise<DeviceImportResponse> {
  const formData = new FormData()
  formData.append('file', file)
  return request.post(`${BASE}/devices/import`, formData, {
    params: { device_type: deviceType },
    headers: { 'Content-Type': 'multipart/form-data' },
    timeout: 120000,  // 2 minutes for large imports
  })
}

/** 下载设备导入模板 */
export function downloadImportTemplate(deviceType: string): Promise<Blob> {
  return request.get(`${BASE}/devices/import/template`, {
    params: { device_type: deviceType },
    responseType: 'blob',
  })
}