/**
 * API 封装层 - 迎宾机器人屏幕端
 *
 * 所有接口统一在此文件封装
 * 使用真实的后端接口，失败时降级到 Mock 数据
 */

import { http } from '@/utils/request'
import {
  mockRobotStatus,
  mockScreenConfig,
  mockPlayPlan,
  mockWelcomeContent,
  mockBroadcastState,
  mockBroadcastContent,
  mockCommands,
  mockAppointments,
  mockIdCardResult,
  mockRecognitionResult,
  mockDestinations,
  mockNotices,
  mockNavigationStatus,
  mockSystemInfo,
  mockScreenTheme
} from '@/mock/screen'

// ============================================
// 屏幕配置与状态
// ============================================

/**
 * 获取屏幕配置
 */
export async function getScreenConfig() {
  try {
    return await http.get('/robot-ops/screen/config')
  } catch (error) {
    console.warn('使用 Mock 数据：getScreenConfig')
    return { ...mockScreenConfig }
  }
}

/**
 * 获取机器人状态
 */
export async function getRobotStatus() {
  try {
    return await http.get('/robot-ops/robot/status')
  } catch (error) {
    console.warn('使用 Mock 数据：getRobotStatus')
    return { ...mockRobotStatus }
  }
}

/**
 * 获取播放方案
 */
export async function getPlayPlan() {
  try {
    return await http.get('/robot-ops/screen/play-plan/current')
  } catch (error) {
    console.warn('使用 Mock 数据：getPlayPlan')
    return { ...mockPlayPlan }
  }
}

/**
 * 获取欢迎页兜底内容
 */
export async function getWelcomeContent() {
  try {
    return await http.get('/robot-ops/screen/welcome-content')
  } catch (error) {
    console.warn('使用 Mock 数据：getWelcomeContent')
    return { ...mockWelcomeContent }
  }
}

/**
 * 获取屏幕主题配置
 */
export async function getScreenTheme() {
  try {
    return await http.get('/robot-ops/screen/theme')
  } catch (error) {
    console.warn('使用 Mock 数据：getScreenTheme')
    return { ...mockScreenTheme }
  }
}

/**
 * 获取播报状态
 */
export async function getBroadcastState() {
  try {
    return await http.get('/robot-ops/broadcast/state')
  } catch (error) {
    console.warn('使用 Mock 数据：getBroadcastState')
    return { ...mockBroadcastState }
  }
}

/**
 * 获取播报内容
 */
export async function getBroadcastContent() {
  try {
    return await http.get('/robot-ops/broadcast/content')
  } catch (error) {
    console.warn('使用 Mock 数据：getBroadcastContent')
    return { ...mockBroadcastContent }
  }
}

// ============================================
// 播报插播
// ============================================

// 开发测试开关：启用后跳过真实接口，始终返回 Mock 播报数据
// 正式环境应设置为 false，使用真实后端接口
const ENABLE_BROADCAST_MOCK = false

/**
 * 获取当前播报状态
 * 后端生成/缓存 MP3，屏幕端播放 MP3
 */
export async function getCurrentBroadcast() {
  if (ENABLE_BROADCAST_MOCK) {
    return {
      code: 200,
      msg: 'Mock 播报中',
      data: {
        broadcasting: true,
        taskId: 999,
        contentId: 1001,
        taskName: '播报插播测试任务',
        title: '临时通知',
        content: '欢迎使用迎宾巡逻安防机器人，当前正在测试播报插播功能。播报结束后，系统将自动恢复原来的待机播放状态。',
        contentType: 'notice',
        level: 'normal',
        audioUrl: 'http://192.168.0.30:8080/profile/audio/tts/315e916026ab49e8aeeb7e25a2713c29.wav',
        audioDuration: 8,
        playMode: 'once',
        startTime: new Date().toISOString(),
        estimatedEndTime: '',
        version: 'mock-broadcast-001'
      },
      timestamp: new Date().toISOString().replace('T', ' ').substring(0, 19)
    }
  }

  try {
    return await http.get('/robot-ops/screen/broadcast/current')
  } catch (error) {
    console.warn('使用 Mock 数据：getCurrentBroadcast')
    // 一期返回无播报状态
    return {
      code: 200,
      msg: '当前无播报',
      data: {
        broadcasting: false,
        taskId: null,
        contentId: null,
        taskName: '',
        title: '',
        content: '',
        contentType: '',
        level: 'normal',
        audioUrl: '',
        audioDuration: null,
        playMode: 'once',
        startTime: null,
        estimatedEndTime: null,
        version: ''
      },
      timestamp: new Date().toISOString().replace('T', ' ').substring(0, 19)
    }
  }
}

/**
 * 播报播放完成回执
 * @param {Object} data { taskId, contentId, resultStatus, resultMsg, playTime }
 */
export async function ackBroadcast(data) {
  try {
    return await http.post('/robot-ops/screen/broadcast/ack', data)
  } catch (error) {
    console.warn('[API] ackBroadcast failed:', error)
    return { success: false }
  }
}

// ============================================
// 语音指令
// ============================================

/**
 * 获取最新指令
 */
export async function getLatestCommand() {
  try {
    return await http.get('/robot-ops/commands/latest')
  } catch (error) {
    console.warn('使用 Mock 数据：getLatestCommand')
    if (Math.random() > 0.9) {
      return mockCommands[Math.floor(Math.random() * mockCommands.length)]
    }
    return null
  }
}

/**
 * 指令回执
 */
export async function ackCommand(commandId) {
  try {
    return await http.post(`/robot-ops/commands/${commandId}/ack`)
  } catch (error) {
    console.warn('使用 Mock 数据：ackCommand')
    return { success: true, commandId }
  }
}

// ============================================
// 访客登记
// ============================================

/**
 * 读取身份证
 */
export async function readIdCard() {
  try {
    return await http.post('/robot-ops/id-card/read')
  } catch (error) {
    console.error('读取身份证失败:', error)
    throw error
  }
}

/**
 * 预约查询
 */
export async function queryAppointment(params) {
  // #region debug log
  fetch('http://127.0.0.1:7870/ingest/a84a825e-d3f2-4bc0-99e9-e2345f77eced',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'ce506e'},body:JSON.stringify({sessionId:'ce506e',location:'screen.js:queryAppointment',message:'API queryAppointment 被调用',data:{params},timestamp:Date.now()})}).catch(()=>{});
  // #endregion
  try {
    const queryString = new URLSearchParams(params).toString()
    const url = queryString ? `/robot-ops/appointments/query?${queryString}` : '/robot-ops/appointments/query'
    // #region debug log
    fetch('http://127.0.0.1:7870/ingest/a84a825e-d3f2-4bc0-99e9-e2345f77eced',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'ce506e'},body:JSON.stringify({sessionId:'ce506e',location:'screen.js:queryAppointment',message:'请求 URL',data:{url},timestamp:Date.now()})}).catch(()=>{});
    // #endregion
    const result = await http.get(url)
    // #region debug log
    fetch('http://127.0.0.1:7870/ingest/a84a825e-d3f2-4bc0-99e9-e2345f77eced',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'ce506e'},body:JSON.stringify({sessionId:'ce506e',location:'screen.js:queryAppointment',message:'API 返回结果',data:{result},timestamp:Date.now()})}).catch(()=>{});
    // #endregion
    return result
  } catch (error) {
    // #region debug log
    fetch('http://127.0.0.1:7870/ingest/a84a825e-d3f2-4bc0-99e9-e2345f77eced',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'ce506e'},body:JSON.stringify({sessionId:'ce506e',location:'screen.js:queryAppointment',message:'API 请求失败',data:{error:error?.message||error},timestamp:Date.now()})}).catch(()=>{});
    // #endregion
    console.error('预约查询失败:', error)
    throw error
  }
}

/**
 * 提交访客登记
 */
export async function submitVisitorRegistration(data) {
  try {
    return await http.post('/robot-ops/visitors/register', data)
  } catch (error) {
    console.error('提交访客登记失败:', error)
    throw error
  }
}

/**
 * 获取最新识别结果
 */
export async function getRecognitionResult() {
  try {
    return await http.get('/robot-ops/face/result/latest')
  } catch (error) {
    console.warn('使用 Mock 数据：getRecognitionResult')
    return { ...mockRecognitionResult }
  }
}

// ============================================
// 路线引导
// ============================================

/**
 * 获取目的地列表
 */
export async function getDestinations() {
  try {
    return await http.get('/robot-ops/destinations')
  } catch (error) {
    console.warn('使用 Mock 数据：getDestinations')
    return [...mockDestinations]
  }
}

/**
 * 开始导航
 */
export async function startNavigation(params) {
  try {
    return await http.post('/robot-ops/navigation/start', params)
  } catch (error) {
    console.error('开始导航失败:', error)
    throw error
  }
}

/**
 * 获取导航状态
 */
export async function getNavigationStatus(params) {
  try {
    return await http.get(`/robot-ops/navigation/${params.taskId}/status`)
  } catch (error) {
    console.warn('使用 Mock 数据：getNavigationStatus')
    return { ...mockNavigationStatus, taskId: params.taskId }
  }
}

/**
 * 取消导航
 */
export async function cancelNavigation(params) {
  try {
    return await http.post(`/robot-ops/navigation/${params.taskId}/cancel`)
  } catch (error) {
    console.error('取消导航失败:', error)
    throw error
  }
}

// ============================================
// 通知公告
// ============================================

/**
 * 获取通知公告列表
 */
export async function getNotices() {
  try {
    return await http.get('/robot-ops/notices')
  } catch (error) {
    console.warn('使用 Mock 数据：getNotices')
    return [...mockNotices]
  }
}

/**
 * 获取通知详情
 */
export async function getNoticeDetail(id) {
  try {
    return await http.get(`/robot-ops/notices/${id}`)
  } catch (error) {
    console.warn('使用 Mock 数据：getNoticeDetail')
    const notice = mockNotices.find(n => n.id === id)
    if (notice) {
      return { ...notice }
    }
    throw new Error('公告不存在')
  }
}

// ============================================
// 呼叫工作人员
// ============================================

/**
 * 呼叫工作人员
 */
export async function callStaff(params) {
  try {
    return await http.post('/robot-ops/staff/call', params)
  } catch (error) {
    console.error('呼叫工作人员失败:', error)
    throw error
  }
}

// ============================================
// 系统信息
// ============================================

/**
 * 获取系统信息
 */
export async function getSystemInfo() {
  try {
    return await http.get('/robot-ops/system/info')
  } catch (error) {
    console.warn('使用 Mock 数据：getSystemInfo')
    return { ...mockSystemInfo }
  }
}

// ============================================
// 摄像头
// ============================================

/**
 * 获取摄像头预览地址
 */
export async function getCameraPreviewUrl() {
  try {
    return await http.get('/robot-ops/camera/preview-url')
  } catch (error) {
    console.warn('使用 Mock 数据：getCameraPreviewUrl')
    return {
      streamUrl: 'rtsp://localhost:8554/camera',
      streamType: 'rtsp',
      expireTime: Date.now() + 300000
    }
  }
}

// ============================================
// 音量控制
// ============================================

/**
 * 音量控制
 */
export async function setAudioControl(params) {
  try {
    return await http.post('/robot-ops/audio/control', params)
  } catch (error) {
    console.error('音量控制失败:', error)
    throw error
  }
}

// ============================================
// 事件上报
// ============================================

/**
 * 上报屏幕事件
 */
export async function reportEvent(data) {
  try {
    return await http.post('/robot-ops/events/report', data)
  } catch (error) {
    console.error('事件上报失败:', error)
    return { success: true }
  }
}

// 导出所有 API 方法
export default {
  getScreenConfig,
  getRobotStatus,
  getPlayPlan,
  getWelcomeContent,
  getScreenTheme,
  getBroadcastState,
  getBroadcastContent,
  getCurrentBroadcast,
  ackBroadcast,
  getLatestCommand,
  ackCommand,
  readIdCard,
  queryAppointment,
  submitVisitorRegistration,
  getRecognitionResult,
  getDestinations,
  startNavigation,
  getNavigationStatus,
  cancelNavigation,
  getNotices,
  getNoticeDetail,
  callStaff,
  getSystemInfo,
  getCameraPreviewUrl,
  setAudioControl,
  reportEvent
}