import { defineStore } from 'pinia'
import { ref } from 'vue'
import { deviceApi } from '@/api/device'
import type { Device } from '@/types'

export const useDeviceStore = defineStore('device', () => {
  // 状态
  const devices = ref<Device[]>([])
  const loading = ref(false)

  // 获取设备列表
  async function fetchDevices() {
    loading.value = true
    try {
      const response = await deviceApi.getDevices()
      if (response.success && response.data) {
        devices.value = response.data
      }
    } finally {
      loading.value = false
    }
  }

  // 更新设备名称
  async function updateDeviceName(id: string, deviceName: string) {
    const response = await deviceApi.updateDeviceName(id, deviceName)
    if (response.success && response.data) {
      const index = devices.value.findIndex(d => d.id === id)
      if (index !== -1) {
        devices.value[index] = response.data
      }
    }
    return response
  }

  // 删除设备
  async function deleteDevice(id: string) {
    const response = await deviceApi.deleteDevice(id)
    if (response.success) {
      devices.value = devices.value.filter(d => d.id !== id)
    }
    return response
  }

  // 设置管理员设备
  async function setAdminDevice(id: string) {
    const response = await deviceApi.setAdminDevice(id)
    if (response.success) {
      devices.value.forEach(d => {
        d.isAdmin = d.id === id
      })
    }
    return response
  }

  return {
    // 状态
    devices,
    loading,
    // 方法
    fetchDevices,
    updateDeviceName,
    deleteDevice,
    setAdminDevice
  }
})

