import store from '@/store'

/** 页签内固定 ID（sessionStorage 同页签刷新保持不变） */
const TAB_ID_KEY = 'tsb_tab_id'
const REGISTRY_PREFIX = 'tsb_opened_devices_'
const HEARTBEAT_INTERVAL = 5000
/** 超过该时间未心跳则视为页签已关闭，允许其他页签接管 */
const ENTRY_TTL = 12000

let heartbeatTimer = null
let lifecycleInited = false

function getTabId() {
  try {
    let id = sessionStorage.getItem(TAB_ID_KEY)
    if (!id) {
      id = `${Date.now()}-${Math.random()}`
      sessionStorage.setItem(TAB_ID_KEY, id)
    }
    return id
  } catch (e) {
    return `${Date.now()}-${Math.random()}`
  }
}

function getUserId() {
  const id = store.getters.id
  return id != null && id !== '' ? String(id) : null
}

function registryKey(userId) {
  return `${REGISTRY_PREFIX}${userId}`
}

function loadRegistry(userId) {
  try {
    const raw = localStorage.getItem(registryKey(userId))
    return raw ? JSON.parse(raw) : {}
  } catch (e) {
    return {}
  }
}

function saveRegistry(userId, registry) {
  localStorage.setItem(registryKey(userId), JSON.stringify(registry))
}

function cleanExpired(registry) {
  const now = Date.now()
  const next = { ...registry }
  Object.keys(next).forEach((sn) => {
    if (!next[sn] || now - next[sn].ts > ENTRY_TTL) {
      delete next[sn]
    }
  })
  return next
}

function touchRegistryEntries(deviceSns) {
  const userId = getUserId()
  if (!userId) {
    return
  }
  const tabId = getTabId()
  const registry = loadRegistry(userId)
  let changed = false
  deviceSns.forEach((sn) => {
    const key = String(sn)
    if (registry[key] && registry[key].tabId === tabId) {
      registry[key].ts = Date.now()
      changed = true
    }
  })
  if (changed) {
    saveRegistry(userId, registry)
  }
}

export function registerDevice(deviceSn) {
  const userId = getUserId()
  if (!userId || deviceSn == null || deviceSn === '') {
    return
  }
  const registry = cleanExpired(loadRegistry(userId))
  registry[String(deviceSn)] = {
    tabId: getTabId(),
    ts: Date.now()
  }
  saveRegistry(userId, registry)
}

export function unregisterDevice(deviceSn) {
  const userId = getUserId()
  if (!userId || deviceSn == null || deviceSn === '') {
    return
  }
  const registry = loadRegistry(userId)
  const key = String(deviceSn)
  const entry = registry[key]
  if (entry && entry.tabId === getTabId()) {
    delete registry[key]
    saveRegistry(userId, registry)
  }
}

export function unregisterAllForCurrentTab() {
  const userId = getUserId()
  if (!userId) {
    return
  }
  const tabId = getTabId()
  const registry = loadRegistry(userId)
  let changed = false
  Object.keys(registry).forEach((sn) => {
    if (registry[sn] && registry[sn].tabId === tabId) {
      delete registry[sn]
      changed = true
    }
  })
  if (changed) {
    saveRegistry(userId, registry)
  }
}

export function syncOpenedDevices(devices) {
  const list = Array.isArray(devices) ? devices : []
  list.forEach((device) => {
    if (device && device.deviceSn != null) {
      registerDevice(device.deviceSn)
    }
  })
  startHeartbeat(list.map(d => d.deviceSn))
}

export function startHeartbeat(deviceSns) {
  stopHeartbeat()
  const sns = (deviceSns || []).filter(sn => sn != null && sn !== '').map(sn => String(sn))
  if (!sns.length) {
    return
  }
  touchRegistryEntries(sns)
  heartbeatTimer = setInterval(() => touchRegistryEntries(sns), HEARTBEAT_INTERVAL)
}

export function stopHeartbeat() {
  if (heartbeatTimer) {
    clearInterval(heartbeatTimer)
    heartbeatTimer = null
  }
}

export function refreshRegistryHeartbeat(deviceSns) {
  const sns = (deviceSns || []).filter(sn => sn != null && sn !== '')
  if (!sns.length) {
    stopHeartbeat()
    return
  }
  startHeartbeat(sns)
}

/**
 * 刷新页面仅停止心跳，不立刻删除注册（由 TTL 兜底；刷新后同页签会重新 sync）
 */
export function initTabRegistryLifecycle() {
  if (lifecycleInited) {
    return
  }
  lifecycleInited = true
  const onUnload = () => stopHeartbeat()
  window.addEventListener('pagehide', onUnload)
  window.addEventListener('beforeunload', onUnload)
}
