/**
 * 酒店客房送餐系统 - Vuex Store Module
 * 管理主题、订单状态等全局状态
 */

const state = {
  // 主题配置：blue(商务深蓝) / gold(暖金雅致) / green(墨绿清新)
  theme: localStorage.getItem('hotel_theme') || 'blue',
  
  // WebSocket连接状态
  wsConnected: false,
  wsToken: null,
  
  // 当前用户信息（餐厅/厨房/前台人员）
  currentUser: null,
  
  // 未读新订单通知
  unreadOrders: [],
  
  // 语音播报开关
  voiceEnabled: true
}

const mutations = {
  // 设置主题
  SET_THEME(state, theme) {
    state.theme = theme
    localStorage.setItem('hotel_theme', theme)
    // 更新HTML data-theme属性
    document.documentElement.setAttribute('data-theme', theme)
  },
  
  // 设置WebSocket连接状态
  SET_WS_CONNECTED(state, connected) {
    state.wsConnected = connected
  },
  
  // 设置WebSocket Token
  SET_WS_TOKEN(state, token) {
    state.wsToken = token
  },
  
  // 设置当前用户
  SET_CURRENT_USER(state, user) {
    state.currentUser = user
  },
  
  // 添加未读订单
  ADD_UNREAD_ORDER(state, order) {
    state.unreadOrders.unshift(order)
  },
  
  // 移除未读订单
  REMOVE_UNREAD_ORDER(state, orderId) {
    const index = state.unreadOrders.findIndex(o => o.id === orderId)
    if (index > -1) {
      state.unreadOrders.splice(index, 1)
    }
  },
  
  // 清空未读订单
  CLEAR_UNREAD_ORDERS(state) {
    state.unreadOrders = []
  },
  
  // 切换语音播报
  TOGGLE_VOICE(state) {
    state.voiceEnabled = !state.voiceEnabled
  }
}

const actions = {
  // 初始化主题
  initTheme({ commit }) {
    const savedTheme = localStorage.getItem('hotel_theme') || 'blue'
    commit('SET_THEME', savedTheme)
  },
  
  // 连接WebSocket
  connectWebSocket({ commit, state }) {
    if (!state.wsToken) {
      console.warn('WebSocket Token未获取，无法连接')
      return
    }
    
    const wsUrl = `ws://127.0.0.1:9529/ws/hotel?token=${state.wsToken}`
    const ws = new WebSocket(wsUrl)
    
    ws.onopen = () => {
      commit('SET_WS_CONNECTED', true)
      console.log('WebSocket连接成功')
    }
    
    ws.onmessage = (event) => {
      const message = JSON.parse(event.data)
      handleWebSocketMessage(message, commit)
    }
    
    ws.onerror = (error) => {
      console.error('WebSocket错误:', error)
      commit('SET_WS_CONNECTED', false)
    }
    
    ws.onclose = () => {
      commit('SET_WS_CONNECTED', false)
      console.log('WebSocket连接关闭，尝试重连...')
      // 3秒后重连
      setTimeout(() => {
        if (state.wsToken) {
          dispatch('connectWebSocket')
        }
      }, 3000)
    }
    
    // 将ws实例保存到window供全局访问
    window.hotelWS = ws
  },
  
  // 断开WebSocket
  disconnectWebSocket({ commit }) {
    if (window.hotelWS) {
      window.hotelWS.close()
      window.hotelWS = null
    }
    commit('SET_WS_CONNECTED', false)
  }
}

// 处理WebSocket消息
function handleWebSocketMessage(message, commit) {
  switch (message.type) {
    case 'NEW_ORDER':
      // 新订单通知
      commit('ADD_UNREAD_ORDER', message.data)
      playVoiceNotification(message.data)
      break
    case 'ORDER_STATUS_CHANGED':
      // 订单状态变更
      console.log('订单状态变更:', message.data)
      break
    default:
      console.log('未知消息类型:', message.type)
  }
}

// 语音播报新订单
function playVoiceNotification(order) {
  if (!('speechSynthesis' in window)) {
    console.warn('浏览器不支持Web Speech API')
    return
  }
  
  const text = `新订单！房号${order.roomNo}，金额${order.totalAmount}元`
  const utterance = new SpeechSynthesisUtterance(text)
  utterance.lang = 'zh-CN'
  utterance.rate = 1.0
  speechSynthesis.speak(utterance)
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
