/**
 * PTZ 云台控制 API
 * 通过独立的 PTZ 后端服务调用 ONVIF 标准协议
 * 支持厂家: HIKVISION (海康威视), ANPVIZ
 */

// ==================== 类型定义 ====================

// 支持的摄像头厂家
export type CameraVendor = 'HIKVISION' | 'ANPVIZ' | 'DAHUA' | 'CT-IP500' | 'SVBC'

export interface PTZConfig {
  host: string
  username: string
  password: string
  channel?: number
  cameraId?: number
  vendor?: CameraVendor
}

export interface PTZCommand {
  pan: number
  tilt: number
  zoom: number
}

export interface PTZResult {
  success: boolean
  error?: string
  data?: unknown
}

// ==================== 常量 ====================

const PTZ_API_BASE = 'http://localhost:3002'
const DEFAULT_SPEED = 50

// 方向预设值 (单位向量)
export const PTZ_DIRECTIONS = {
  UP: { pan: 0, tilt: 1 },
  DOWN: { pan: 0, tilt: -1 },
  LEFT: { pan: -1, tilt: 0 },
  RIGHT: { pan: 1, tilt: 0 },
  UP_LEFT: { pan: -1, tilt: 1 },
  UP_RIGHT: { pan: 1, tilt: 1 },
  DOWN_LEFT: { pan: -1, tilt: -1 },
  DOWN_RIGHT: { pan: 1, tilt: -1 },
  STOP: { pan: 0, tilt: 0 }
} as const

// 缩放预设值 (单位向量)
export const PTZ_ZOOM_DIRECTIONS = {
  IN: { zoom: 1 },
  OUT: { zoom: -1 },
  STOP: { zoom: 0 }
} as const

export type PTZDirectionKey = keyof typeof PTZ_DIRECTIONS
export type PTZZoomKey = keyof typeof PTZ_ZOOM_DIRECTIONS

// PTZ 方向命令
export type PTZCommandType =
  | 'up'
  | 'down'
  | 'left'
  | 'right'
  | 'up_left'
  | 'up_right'
  | 'down_left'
  | 'down_right'
  | 'stop'

// ==================== 核心 API ====================

/**
 * 发送 PTZ 控制命令 (ONVIF 统一接口)
 * 支持: HIKVISION, ANPVIZ
 */
async function sendPTZCommand(
  config: PTZConfig,
  command: PTZCommandType,
  speed: number = DEFAULT_SPEED
): Promise<PTZResult> {
  try {
    const response = await fetch(`${PTZ_API_BASE}/ptz/control`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        host: config.host,
        username: config.username,
        password: config.password,
        channel: config.channel || 1,
        cameraId: config.cameraId,
        vendor: config.vendor || 'HIKVISION',
        command,
        speed
      })
    })

    const data = await response.json()
    return data.code === 200
      ? { success: true, data: data.data }
      : { success: false, error: data.msg || 'Unknown error' }
  } catch (error) {
    return { success: false, error: String(error) }
  }
}

/**
 * 发送 PTZ 控制命令 (旧接口 - 使用 pan/tilt/zoom)
 * 注意: 缩放功能可能仅部分摄像头支持
 */
async function sendCommand(config: PTZConfig, command: PTZCommand): Promise<PTZResult> {
  try {
    const response = await fetch(`${PTZ_API_BASE}/ptz/control`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        host: config.host,
        username: config.username,
        password: config.password,
        channel: config.channel || 1,
        cameraId: config.cameraId,
        vendor: config.vendor || 'HIKVISION',
        pan: command.pan,
        tilt: command.tilt,
        zoom: command.zoom
      })
    })

    const data = await response.json()
    return data.code === 200
      ? { success: true, data: data.data }
      : { success: false, error: data.msg || 'Unknown error' }
  } catch (error) {
    return { success: false, error: String(error) }
  }
}

/**
 * 获取 PTZ 状态
 */
export async function getPTZStatus(config: PTZConfig): Promise<PTZResult & { data?: string }> {
  try {
    const response = await fetch(`${PTZ_API_BASE}/ptz/status`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        host: config.host,
        username: config.username,
        password: config.password,
        channel: config.channel || 1
      })
    })

    const data = await response.json()
    return data.code === 200
      ? { success: true, data: data.data?.raw }
      : { success: false, error: data.msg || 'Unknown error' }
  } catch (error) {
    return { success: false, error: String(error) }
  }
}

// ==================== 方向控制 ====================

// 方向键映射到命令
const DIRECTION_TO_COMMAND: Record<PTZDirectionKey, PTZCommandType> = {
  UP: 'up',
  DOWN: 'down',
  LEFT: 'left',
  RIGHT: 'right',
  UP_LEFT: 'up_left',
  UP_RIGHT: 'up_right',
  DOWN_LEFT: 'down_left',
  DOWN_RIGHT: 'down_right',
  STOP: 'stop'
}

/**
 * 开始 PTZ 移动
 * @param direction 方向: UP, DOWN, LEFT, RIGHT, UP_LEFT, UP_RIGHT, DOWN_LEFT, DOWN_RIGHT, STOP
 * @param speed 速度 1-100，默认 50
 */
export function startPTZ(
  config: PTZConfig,
  direction: PTZDirectionKey,
  speed: number = DEFAULT_SPEED
): Promise<PTZResult> {
  // 使用新的 command 接口，支持所有厂家
  const command = DIRECTION_TO_COMMAND[direction]
  return sendPTZCommand(config, command, speed)
}

/**
 * 停止 PTZ 移动
 */
export function stopPTZ(config: PTZConfig): Promise<PTZResult> {
  return sendPTZCommand(config, 'stop')
}

// ==================== 缩放控制 ====================

/**
 * 开始缩放
 * @param direction 缩放方向: IN, OUT, STOP
 * @param speed 速度 1-100，默认 50
 */
export function startZoom(config: PTZConfig, direction: PTZZoomKey, speed: number = DEFAULT_SPEED): Promise<PTZResult> {
  const zoom = PTZ_ZOOM_DIRECTIONS[direction]
  return sendCommand(config, {
    pan: 0,
    tilt: 0,
    zoom: zoom.zoom * speed
  })
}

/**
 * 停止缩放
 */
export function stopZoom(config: PTZConfig): Promise<PTZResult> {
  return startZoom(config, 'STOP')
}

// ==================== 便捷方法 ====================

export const zoomIn = (config: PTZConfig, speed?: number) => startZoom(config, 'IN', speed)
export const zoomOut = (config: PTZConfig, speed?: number) => startZoom(config, 'OUT', speed)
export const zoomStop = stopZoom
