import request from '@/utils/request'
import type { ApiResponse } from '@/types'

// --- 模拟器数据模型 ---

/** 模拟器连接状态 */
export interface SimulatorPing {
  running: boolean
}

/** 数据库采集地址（模拟器返回） */
export interface SimulatorAddress {
  dbId: number
  name: string
  url: string
  machineCount: number
  machines: { id: number; deviceCode: string; name: string }[]
  isRunning: boolean
  runningPort: number
}

/** 模拟状态汇总 */
export interface SimulatorStatus {
  dbAddressId: number
  name: string
  port: number
  isRunning: boolean
  totalDevices: number
  onlineDevices: number
  requestCount: number
  dataChangeInterval: number
  totalParts: number
}

/** 设备状态 */
export interface DeviceStatus {
  deviceCode: string
  desc: string
  scenario: string
  isOnline: boolean
  programName: string
  partCount: number
  runStatus: number
  operateMode: number
  spindleSpeedSet: number
  spindleSpeedActual: number
  feedSpeedSet: number
  feedSpeedActual: number
  spindleLoad: number
  machiningStatus: string
  scenarioTick: number
  scenarioDuration: number
}

/** 单地址详情状态 */
export interface AddressStatus {
  name: string
  port: number
  isRunning: boolean
  requestCount: number
  successCount: number
  failCount: number
  totalDevices: number
  onlineDevices: number
  dataChangeInterval: number
  scenarioMode: string
  networkError: string
  startTime: string
  uptime: string
  devices: DeviceStatus[]
}

/** 零件统计 */
export interface AddressStats {
  totalDevices: number
  onlineDevices: number
  totalParts: number
  partsByDevice: Record<string, {
    desc: string
    totalParts: number
    currentProgram: string
    currentPartCount: number
    programs: Record<string, number>
  }>
}

/** 请求日志 */
export interface SimulatorLog {
  index: number
  timestamp: string
  deviceCount: number
  keyData: string
  duration: number
  fullJson: string
}

/** 事件历史 */
export interface EventHistory {
  timestamp: string
  deviceCode: string
  eventType: string
  oldProgram: string
  newProgram: string
  partCountBefore: number
  partCountAfter: number
  detail: string
}

// --- 网关API ---

/** 探测模拟器是否运行 */
export function pingSimulator() {
  return request.get<SimulatorPing>('/admin/simulator/ping')
}

/** 获取数据库采集地址列表 */
export function fetchSimulatorAddresses() {
  return request.get<SimulatorAddress[]>('/admin/simulator/addresses')
}

/** 获取所有模拟状态汇总 */
export function fetchSimulatorStatus() {
  return request.get<SimulatorStatus[]>('/admin/simulator/status')
}

/** 启动指定地址的模拟 */
export function startSimulator(data: { dbAddressId: number; deviceCodes?: string[] }) {
  return request.post('/admin/simulator/start', data)
}

/** 停止指定地址的模拟 */
export function stopSimulator(data: { dbAddressId: number }) {
  return request.post('/admin/simulator/stop', data)
}

/** 启动所有地址的模拟 */
export function startAllSimulators() {
  return request.post('/admin/simulator/start-all')
}

/** 停止所有地址的模拟 */
export function stopAllSimulators() {
  return request.post('/admin/simulator/stop-all')
}

/** 重新加载数据库配置 */
export function reloadSimulator() {
  return request.post('/admin/simulator/reload')
}

// --- 单地址API ---

/** 获取单地址状态 */
export function fetchAddressStatus(port: number) {
  return request.get<AddressStatus>(`/admin/simulator/address/${port}/status`)
}

/** 启动单地址数据模拟 */
export function startAddressSimulation(port: number) {
  return request.post(`/admin/simulator/address/${port}/start`)
}

/** 停止单地址数据模拟 */
export function stopAddressSimulation(port: number) {
  return request.post(`/admin/simulator/address/${port}/stop`)
}

/** 触发设备事件 */
export function triggerDeviceEvent(port: number, data: { deviceId: string; eventType: string }) {
  return request.post(`/admin/simulator/address/${port}/event`, data)
}

/** 修改数据变化频率 */
export function setAddressInterval(port: number, data: { value: number }) {
  return request.post(`/admin/simulator/address/${port}/interval`, data)
}

/** 设置网络异常类型 */
export function setNetworkError(port: number, data: { type: string }) {
  return request.post(`/admin/simulator/address/${port}/network`, data)
}

/** 切换剧本模式 */
export function setScenarioMode(port: number, data: { mode: string }) {
  return request.post(`/admin/simulator/address/${port}/mode`, data)
}

/** 获取请求日志 */
export function fetchAddressLogs(port: number) {
  return request.get<SimulatorLog[]>(`/admin/simulator/address/${port}/logs`)
}

/** 获取零件统计 */
export function fetchAddressStats(port: number) {
  return request.get<AddressStats>(`/admin/simulator/address/${port}/stats`)
}

/** 添加设备 */
export function addDevice(port: number, data: { deviceCode: string; desc: string }) {
  return request.post(`/admin/simulator/address/${port}/add-device`, data)
}

/** 移除设备 */
export function removeDevice(port: number, data: { deviceCode: string }) {
  return request.post(`/admin/simulator/address/${port}/remove-device`, data)
}

/** 获取事件历史 */
export function fetchEventHistory(port: number) {
  return request.get<EventHistory[]>(`/admin/simulator/address/${port}/event-history`)
}

/** 获取完整汇总 */
export function fetchFullSummary(port: number) {
  return request.get(`/admin/simulator/address/${port}/full-summary`)
}

/** 获取异常日志 */
export function fetchErrorLog(port: number) {
  return request.get(`/admin/simulator/address/${port}/error-log`)
}

export default {}
