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

export const useScreenStore = defineStore('screen', () => {
  // 机器人状态
  const robotStatus = ref({
    batteryLevel: 85,
    networkStatus: 'online',
    workStatus: 'idle',
    chargeStatus: 'not_charging',
    faultFlag: false
  })

  // 播放方案
  const playPlan = ref(null)
  const currentMediaIndex = ref(0)
  const isPlaying = ref(true)

  // 待机页模式: 'welcome' | 'playlist'
  const idleMode = ref('welcome')

  // 是否有播放方案（计算属性 + 手动覆盖）
  const hasPlayPlan = ref(false)

  // 强制模式覆盖（开发调试用）
  const forceMode = ref(null)

  // 播报状态
  const broadcastState = ref({
    broadcasting: false,
    title: '',
    content: '',
    startTime: null,
    endTime: null
  })

  // 语音指令
  const latestCommand = ref(null)

  // 全局提示
  const globalAlert = ref({
    show: false,
    type: 'info',
    title: '',
    message: '',
    duration: 3000
  })

  // 音量
  const volume = ref(80)
  const muted = ref(false)

  // 屏幕配置
  const screenConfig = ref({
    robotName: '智能迎宾机器人',
    logoUrl: '',
    idleTimeout: 60,
    theme: 'default'
  })

  // 待机页主题配置
  const screenTheme = ref(null)

  // 计算属性
  const isIdle = computed(() => robotStatus.value.workStatus === 'idle')
  const isCharging = computed(() => robotStatus.value.chargeStatus === 'charging')
  const hasFault = computed(() => robotStatus.value.faultFlag)
  const networkOk = computed(() => robotStatus.value.networkStatus === 'online')

  const currentMedia = computed(() => {
    if (!playPlan.value || !playPlan.value.items || playPlan.value.items.length === 0) {
      return null
    }
    return playPlan.value.items[currentMediaIndex.value] || null
  })

  // 实际的待机页展示模式
  const actualIdleMode = computed(() => {
    if (forceMode.value !== null) {
      return forceMode.value
    }
    return hasPlayPlan.value ? 'playlist' : 'welcome'
  })

  // 方法
  async function fetchScreenConfig() {
    try {
      const res = await api.getScreenConfig()
      screenConfig.value = res
    } catch (e) {
      console.error('Failed to fetch screen config:', e)
    }
  }

  async function fetchScreenTheme() {
    try {
      const res = await api.getScreenTheme()
      screenTheme.value = res
    } catch (e) {
      console.error('Failed to fetch screen theme:', e)
    }
  }

  async function fetchRobotStatus() {
    try {
      const res = await api.getRobotStatus()
      robotStatus.value = res
    } catch (e) {
      console.error('Failed to fetch robot status:', e)
    }
  }

  async function fetchPlayPlan() {
    try {
      const res = await api.getPlayPlan()
      playPlan.value = res
      currentMediaIndex.value = 0
      // 判断是否有有效的播放方案：enabled !== false 且 items 非空
      hasPlayPlan.value = !!(
        res &&
        res.enabled !== false &&
        Array.isArray(res.items) &&
        res.items.length > 0
      )
    } catch (e) {
      console.error('Failed to fetch play plan:', e)
      playPlan.value = null
      hasPlayPlan.value = false
    }
  }

  async function fetchBroadcastState() {
    try {
      const res = await api.getBroadcastState()
      broadcastState.value = res
    } catch (e) {
      console.error('Failed to fetch broadcast state:', e)
    }
  }

  async function fetchLatestCommand() {
    try {
      const res = await api.getLatestCommand()
      if (res && res.commandId !== latestCommand.value?.commandId) {
        latestCommand.value = res
        return res
      }
    } catch (e) {
      console.error('Failed to fetch latest command:', e)
    }
    return null
  }

  async function ackCommand(commandId) {
    try {
      await api.ackCommand(commandId)
    } catch (e) {
      console.error('Failed to ack command:', e)
    }
  }

  function nextMedia() {
    if (playPlan.value && playPlan.value.items && playPlan.value.items.length > 0) {
      currentMediaIndex.value = (currentMediaIndex.value + 1) % playPlan.value.items.length
    }
  }

  function showAlert(options) {
    const { type = 'info', title = '', message = '', duration = 3000 } = options
    globalAlert.value = { show: true, type, title, message, duration }
    if (duration > 0) {
      setTimeout(() => {
        globalAlert.value.show = false
      }, duration)
    }
  }

  function hideAlert() {
    globalAlert.value.show = false
  }

  function setVolume(val) {
    volume.value = Math.max(0, Math.min(100, val))
  }

  function toggleMute() {
    muted.value = !muted.value
  }

  function pausePlay() {
    isPlaying.value = false
  }

  function resumePlay() {
    isPlaying.value = true
  }

  function resetToIdle() {
    robotStatus.value.workStatus = 'idle'
  }

  // 切换待机页模式（开发调试用）
  function toggleIdleMode() {
    forceMode.value = actualIdleMode.value === 'welcome' ? 'playlist' : 'welcome'
  }

  // 重置强制模式
  function resetForceMode() {
    forceMode.value = null
  }

  return {
    // 状态
    robotStatus,
    playPlan,
    currentMediaIndex,
    isPlaying,
    broadcastState,
    latestCommand,
    globalAlert,
    volume,
    muted,
    screenConfig,
    screenTheme,
    idleMode,
    hasPlayPlan,
    forceMode,
    // 计算属性
    isIdle,
    isCharging,
    hasFault,
    networkOk,
    currentMedia,
    actualIdleMode,
    // 方法
    fetchScreenConfig,
    fetchScreenTheme,
    fetchRobotStatus,
    fetchPlayPlan,
    fetchBroadcastState,
    fetchLatestCommand,
    ackCommand,
    nextMedia,
    showAlert,
    hideAlert,
    setVolume,
    toggleMute,
    pausePlay,
    resumePlay,
    resetToIdle,
    toggleIdleMode,
    resetForceMode
  }
})
