import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import * as api from '@/api/screen'

export const useNavigationStore = defineStore('navigation', () => {
  // 目的地列表
  const destinations = ref([])

  // 当前导航任务
  const currentTask = ref(null)

  // 导航状态
  const navigationStatus = ref({
    taskId: '',
    status: 'idle',
    currentPoint: '',
    targetName: '',
    progress: 0,
    estimatedTime: ''
  })

  // 导航历史
  const navigationHistory = ref([])

  // 计算属性
  const isNavigating = computed(() => {
    return ['starting', 'navigating', 'arriving'].includes(navigationStatus.value.status)
  })

  const hasActiveTask = computed(() => !!currentTask.value)

  // 按分类分组的目的地
  const destinationsByCategory = computed(() => {
    const grouped = {}
    destinations.value.forEach(dest => {
      if (!grouped[dest.category]) {
        grouped[dest.category] = []
      }
      grouped[dest.category].push(dest)
    })
    return grouped
  })

  // 方法
  async function fetchDestinations() {
    try {
      const res = await api.getDestinations()
      destinations.value = res
    } catch (e) {
      console.error('Failed to fetch destinations:', e)
      destinations.value = []
    }
  }

  async function startNavigation(destination) {
    try {
      const res = await api.startNavigation({ destinationId: destination.destinationId })
      currentTask.value = {
        ...destination,
        taskId: res.taskId,
        startTime: Date.now()
      }
      navigationStatus.value = {
        taskId: res.taskId,
        status: 'starting',
        currentPoint: '起点',
        targetName: destination.name,
        progress: 0,
        estimatedTime: destination.estimatedTime || '3分钟'
      }
      return res
    } catch (e) {
      if (import.meta.env.DEV) {
        setMockNavigationTask(destination)
        return
      }
      throw e
    }
  }

  function setMockNavigationTask(destination) {
    const dest = destination || {
      destinationId: 'mock-front-desk',
      name: '前台',
      floor: '1楼',
      description: '综合服务前台',
      estimatedTime: '2分钟'
    }
    currentTask.value = {
      taskId: `mock_nav_${Date.now()}`,
      destinationId: dest.destinationId,
      destinationName: dest.name,
      targetName: dest.name,
      name: dest.name,
      floor: dest.floor,
      description: dest.description,
      estimatedTime: dest.estimatedTime || '2分钟',
      status: 'navigating',
      progress: 0,
      startTime: new Date().toISOString()
    }
    navigationStatus.value = {
      taskId: currentTask.value.taskId,
      status: 'navigating',
      targetName: dest.name,
      floor: dest.floor,
      description: dest.description,
      progress: 0,
      estimatedTime: dest.estimatedTime || '2分钟'
    }
    return currentTask.value
  }

  async function fetchNavigationStatus() {
    if (!currentTask.value) return null
    try {
      const res = await api.getNavigationStatus({ taskId: currentTask.value.taskId })
      navigationStatus.value = res
      return res
    } catch (e) {
      console.error('Failed to fetch navigation status:', e)
      return null
    }
  }

  async function cancelNavigation() {
    if (!currentTask.value) return
    try {
      await api.cancelNavigation({ taskId: currentTask.value.taskId })
      addToHistory(currentTask.value)
      currentTask.value = null
      navigationStatus.value = {
        taskId: '',
        status: 'idle',
        currentPoint: '',
        targetName: '',
        progress: 0,
        estimatedTime: ''
      }
    } catch (e) {
      console.error('Failed to cancel navigation:', e)
      throw e
    }
  }

  function addToHistory(task) {
    navigationHistory.value.unshift({
      ...task,
      endTime: Date.now(),
      duration: task.startTime ? Date.now() - task.startTime : 0
    })
    if (navigationHistory.value.length > 10) {
      navigationHistory.value.pop()
    }
  }

  function clearNavigation() {
    currentTask.value = null
    navigationStatus.value = {
      taskId: '',
      status: 'idle',
      currentPoint: '',
      targetName: '',
      progress: 0,
      estimatedTime: ''
    }
  }

  // 模拟导航进度（用于演示）
  function simulateNavigation() {
    if (!currentTask.value) return

    const steps = [
      { status: 'starting', progress: 10, message: '正在规划路线...' },
      { status: 'navigating', progress: 30, message: '开始带路' },
      { status: 'navigating', progress: 50, message: '请跟我来' },
      { status: 'navigating', progress: 70, message: '前方转弯' },
      { status: 'navigating', progress: 85, message: '即将到达' },
      { status: 'arriving', progress: 100, message: '已到达目的地' }
    ]

    let stepIndex = 0
    const interval = setInterval(() => {
      if (stepIndex < steps.length) {
        const step = steps[stepIndex]
        navigationStatus.value = {
          ...navigationStatus.value,
          status: step.status,
          progress: step.progress
        }
        stepIndex++
      } else {
        clearInterval(interval)
      }
    }, 2000)
  }

  return {
    destinations,
    currentTask,
    navigationStatus,
    navigationHistory,
    isNavigating,
    hasActiveTask,
    destinationsByCategory,
    fetchDestinations,
    startNavigation,
    setMockNavigationTask,
    fetchNavigationStatus,
    cancelNavigation,
    addToHistory,
    clearNavigation,
    simulateNavigation
  }
})
