import store from '@/store'
import router from '@/router'
import { Message } from 'element-ui'
import {
  getRouteByCmdType,
  isOnCmdRoute,
  isOnOpwSubPage,
  TSB_WORKSPACE_ROUTE,
  OPW_CMD_SUB_PAGE
} from '@/utils/tsbCmdRoute'
import { navigateToWorkspace } from '@/utils/tsbWorkspaceNav'
import tsbWebSocket from '@/utils/tsbWebSocket'

function resolveWsData(msg) {
  if (!msg.data) {
    return null
  }
  if (typeof msg.data === 'string') {
    try {
      return JSON.parse(msg.data)
    } catch (e) {
      return null
    }
  }
  return msg.data
}

/**
 * 处理 WebSocket 推送：按 cmdType 跳转页面并缓存 data 供页面初始化
 */
export function handleTsbWsMessage(msg) {
  if (!msg || !msg.cmdType) {
    return
  }

  if (msg.cmdType === 'connect') {
    if (Number(msg.code) === 1) {
      tsbWebSocket.notifyConnectSuccess()
    } else {
      tsbWebSocket.notifyConnectFailed()
      if (msg.message) {
        Message.error(msg.message || 'WebSocket 连接失败')
      }
    }
    return
  }

  const currentSn = store.getters.tsbCurrentDeviceSn || tsbWebSocket.getCurrentDeviceSn()
  const deviceSn = msg._tsbDeviceSn != null ? String(msg._tsbDeviceSn)
    : (currentSn != null ? String(currentSn) : null)
  const isActiveDevice = deviceSn == null || deviceSn === String(currentSn)
  const routePath = getRouteByCmdType(msg.cmdType, deviceSn)
  if (!routePath) {
    return
  }

  if (Number(msg.code) !== 1) {
    Message.error(msg.message || '操作失败')
    return
  }

  const data = resolveWsData(msg)
  if (!data) {
    return
  }

  const opwSubPage = OPW_CMD_SUB_PAGE[msg.cmdType]
  if (opwSubPage && deviceSn != null && routePath === TSB_WORKSPACE_ROUTE) {
    store.commit('tsb/SET_DEVICE_PANEL', { deviceSn, panel: 'opw' })
    store.commit('tsb/SET_OPW_SUB_PAGE', { deviceSn, subPage: opwSubPage })
  } else if (msg.cmdType === 'common:tax' && deviceSn != null && routePath === TSB_WORKSPACE_ROUTE) {
    store.commit('tsb/SET_DEVICE_PANEL', { deviceSn, panel: 'tax' })
  }

  const devicePanel = (store.state.tsb.devicePanelMap || {})[String(deviceSn)] || 'home'
  const currentOpwSub = (store.state.tsb.opwSubPageMap || {})[String(deviceSn)] || 'main'
  const onTargetPage = opwSubPage
    ? isOnOpwSubPage(router.currentRoute.path, msg.cmdType, devicePanel, currentOpwSub)
    : isOnCmdRoute(router.currentRoute.path, msg.cmdType, deviceSn, devicePanel)

  store.commit('tsb/SET_WS_PAGE_DATA', {
    cmdType: msg.cmdType,
    data,
    navigate: isActiveDevice && !onTargetPage,
    deviceSn
  })

  if (isActiveDevice && !onTargetPage) {
    if (routePath === TSB_WORKSPACE_ROUTE) {
      navigateToWorkspace().catch(() => {})
    } else {
      router.push(routePath).catch(() => {})
    }
  }
}

/**
 * 注册全局 WebSocket 消息路由（登录后调用一次）
 */
export function initTsbWsRouter(onMessage) {
  onMessage(handleTsbWsMessage)
}
