/**
 * 设备管理相关API
 */

import { USE_MOCK } from '@/utils/config';
import { mockDeviceList, mockDeviceDetail } from '@/mock';

export interface DeviceQueryParams {
  page?: number;
  pageSize?: number;
  deviceNo?: string;
  status?: number;
  shopId?: number;
}

export interface DeviceListResponse {
  list: any[];
  total: number;
  page: number;
  pageSize: number;
}

/**
 * 获取设备列表
 */
export async function getDeviceList(params: DeviceQueryParams = {}): Promise<DeviceListResponse> {
  if (USE_MOCK) {
    const { page = 1, pageSize = 10, status, deviceNo, shopId } = params;
    let list = [...mockDeviceList];
    
    // 状态筛选
    if (status !== undefined && status !== -1) {
      list = list.filter(item => item.status === status);
    }
    
    // 设备号搜索
    if (deviceNo) {
      list = list.filter(item => item.deviceNo.includes(deviceNo) || item.name.includes(deviceNo));
    }
    
    // 门店筛选
    if (shopId) {
      list = list.filter(item => item.shopId === shopId);
    }
    
    const total = list.length;
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    
    return Promise.resolve({
      list: list.slice(startIndex, endIndex),
      total,
      page,
      pageSize
    });
  }
  
  const { get } = await import('@/utils/request');
  return get('/devices', params);
}

/**
 * 获取设备详情
 */
export async function getDeviceDetail(deviceId: number): Promise<any> {
  if (USE_MOCK) {
    return Promise.resolve(mockDeviceDetail);
  }
  
  const { get } = await import('@/utils/request');
  return get(`/devices/${deviceId}`);
}

/**
 * 获取设备统计数据
 */
export async function getDeviceStats(): Promise<any> {
  if (USE_MOCK) {
    return Promise.resolve({
      totalCount: 50,
      onlineCount: 48,
      offlineCount: 2,
      maintenanceCount: 1,
      errorCount: 0
    });
  }
  
  const { get } = await import('@/utils/request');
  return get('/devices/stats');
}

/**
 * 设置设备温度
 */
export async function setDeviceTemperature(deviceId: number, temperature: number): Promise<void> {
  if (USE_MOCK) {
    return Promise.resolve();
  }
  
  const { post } = await import('@/utils/request');
  await post(`/devices/${deviceId}/temperature`, { temperature });
}

/**
 * 设置设备音量
 */
export async function setDeviceVolume(deviceId: number, volume: number): Promise<void> {
  if (USE_MOCK) {
    return Promise.resolve();
  }
  
  const { post } = await import('@/utils/request');
  await post(`/devices/${deviceId}/volume`, { volume });
}

/**
 * 重启设备
 */
export async function rebootDevice(deviceId: number): Promise<void> {
  if (USE_MOCK) {
    return Promise.resolve();
  }
  
  const { post } = await import('@/utils/request');
  await post(`/devices/${deviceId}/reboot`);
}
