import { ref, computed } from 'vue'

// 摄像头厂家类型
export type CameraVendor = 'HIKVISION' | 'ANPVIZ' | 'DAHUA' | 'CT-IP500' | 'SVBC'

export interface GridSlot {
  position: number
  cameraId?: string
  cameraName?: string
  streamType: 'webrtc' | 'cloudflare'
  streamUrl?: string
  // PTZ 配置
  vendor?: CameraVendor
  ptzHost?: string
  ptzUsername?: string
  ptzPassword?: string
}

export interface MonitorTab {
  id: string
  name: string
  gridSize: 2 | 3 | 4
  slots: GridSlot[]
}

const STORAGE_KEY = 'monitor-tabs'

// 生成唯一 ID
function generateId(): string {
  return `tab-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
}

// 创建默认标签
function createDefaultTab(): MonitorTab {
  return {
    id: generateId(),
    name: 'Tab-1',
    gridSize: 2,
    slots: []
  }
}

// 全局状态
const tabs = ref<MonitorTab[]>([])
const activeTabId = ref<string>('')

export function useMonitorStore() {
  // 当前激活的标签
  const currentTab = computed(() => {
    return tabs.value.find((tab) => tab.id === activeTabId.value) || null
  })

  // 从 localStorage 加载
  function loadFromStorage() {
    try {
      const stored = localStorage.getItem(STORAGE_KEY)
      if (stored) {
        const parsed = JSON.parse(stored) as { tabs: MonitorTab[]; activeTabId: string }
        if (parsed.tabs && parsed.tabs.length > 0) {
          tabs.value = parsed.tabs
          activeTabId.value = parsed.activeTabId || parsed.tabs[0].id
          return
        }
      }
    } catch (e) {
      console.error('Failed to load monitor config from localStorage:', e)
    }

    // 如果没有存储数据或加载失败，创建默认标签
    const defaultTab = createDefaultTab()
    tabs.value = [defaultTab]
    activeTabId.value = defaultTab.id
  }

  // 保存到 localStorage
  function saveToStorage() {
    try {
      const data = {
        tabs: tabs.value,
        activeTabId: activeTabId.value
      }
      localStorage.setItem(STORAGE_KEY, JSON.stringify(data))
    } catch (e) {
      console.error('Failed to save monitor config to localStorage:', e)
    }
  }

  // 添加新标签
  function addTab() {
    const newTab: MonitorTab = {
      id: generateId(),
      name: `Tab ${tabs.value.length + 1}`,
      gridSize: 2,
      slots: []
    }
    tabs.value.push(newTab)
    activeTabId.value = newTab.id
    saveToStorage()
  }

  // 删除标签
  function removeTab(tabId: string) {
    if (tabs.value.length <= 1) return

    const index = tabs.value.findIndex((tab) => tab.id === tabId)
    if (index === -1) return

    tabs.value.splice(index, 1)

    // 如果删除的是当前激活的标签，切换到其他标签
    if (activeTabId.value === tabId) {
      activeTabId.value = tabs.value[Math.max(0, index - 1)].id
    }
    saveToStorage()
  }

  // 更新标签
  function updateTab(tabId: string, updates: Partial<MonitorTab>) {
    const tab = tabs.value.find((t) => t.id === tabId)
    if (tab) {
      Object.assign(tab, updates)
    }
  }

  // 重命名标签
  function renameTab(tabId: string, newName: string) {
    updateTab(tabId, { name: newName })
    saveToStorage()
  }

  // 清空标签的所有格子
  function clearTabSlots(tabId: string) {
    updateTab(tabId, { slots: [] })
    saveToStorage()
  }

  return {
    tabs,
    activeTabId,
    currentTab,
    loadFromStorage,
    saveToStorage,
    addTab,
    removeTab,
    updateTab,
    renameTab,
    clearTabSlots
  }
}
