/**
 * 状态查询相关API
 * 用于查询设备状态、识别结果和订单信息
 */

import { post } from '../utils/request';

/**
 * 设备状态响应
 */
export interface DeviceStatusResponse {
  deviceId: string;
  doorStatus: 'open' | 'close' | 'error' | 'busy' | 'unknown';
  activityId: string;
  userId: string;
  status: string;
  openType: string;
  timestamp: string;
}

/**
 * 识别结果响应
 */
export interface RecognizeResultResponse {
  activityId: string;
  deviceId: string;
  userId: string;
  nobuy: string;
  result: string;
  skuList: string;
  resourceInfo: string;
  timestamp: string;
}

/**
 * 订单信息响应
 */
export interface OrderInfoResponse {
  orderId: string;
  activityId: string;
  deviceId: string;
  userId: string;
  orderName: string;
  totalAmount: string;
  products: string;
  timestamp: string;
}

/**
 * 综合状态响应
 */
export interface AllStatusResponse {
  deviceStatus: DeviceStatusResponse;
  recognizeResult?: RecognizeResultResponse;
  orderInfo?: OrderInfoResponse;
}

/**
 * 查询设备状态
 * @param deviceId 设备ID
 */
export const queryDeviceStatus = (deviceId: string): Promise<DeviceStatusResponse> => {
  return post<DeviceStatusResponse>('/status/device', { deviceId });
};

/**
 * 查询识别结果
 * @param activityId 活动ID
 */
export const queryRecognizeResult = (activityId: string): Promise<RecognizeResultResponse> => {
  return post<RecognizeResultResponse>('/status/recognize', { activityId });
};

/**
 * 查询订单信息
 * @param orderId 订单ID
 * @param activityId 活动ID（与orderId二选一）
 */
export const queryOrderInfo = (orderId?: string, activityId?: string): Promise<OrderInfoResponse> => {
  return post<OrderInfoResponse>('/status/order', { orderId, activityId });
};

/**
 * 综合状态查询
 * @param deviceId 设备ID
 */
export const queryAllStatus = (deviceId: string): Promise<AllStatusResponse> => {
  return post<AllStatusResponse>('/status/all', { deviceId });
};

/**
 * 轮询设备状态
 * @param deviceId 设备ID
 * @param timeout 超时时间（毫秒）
 * @param interval 轮询间隔（毫秒）
 */
export const pollDeviceStatus = (
  deviceId: string,
  timeout: number = 120000,
  interval: number = 2000
): Promise<DeviceStatusResponse> => {
  return new Promise((resolve, reject) => {
    const startTime = Date.now();
    
    const poll = async () => {
      try {
        const response = await queryDeviceStatus(deviceId);
        
        // 检查是否有有效的状态更新
        if (response && response.doorStatus && response.doorStatus !== 'unknown') {
          const statusTime = parseInt(response.timestamp) || 0;
          // 如果状态更新时间在开始轮询之后，说明是新状态
          if (statusTime > startTime - 10000) {
            resolve(response);
            return;
          }
        }
        
        // 检查是否超时
        if (Date.now() - startTime >= timeout) {
          reject(new Error('轮询超时'));
          return;
        }
        
        // 继续轮询
        setTimeout(poll, interval);
      } catch (error) {
        // 查询失败，继续轮询
        if (Date.now() - startTime >= timeout) {
          reject(new Error('轮询超时'));
          return;
        }
        setTimeout(poll, interval);
      }
    };
    
    poll();
  });
};

/**
 * 轮询识别结果
 * @param activityId 活动ID
 * @param timeout 超时时间（毫秒）
 * @param interval 轮询间隔（毫秒）
 */
export const pollRecognizeResult = (
  activityId: string,
  timeout: number = 60000,
  interval: number = 1000
): Promise<RecognizeResultResponse> => {
  return new Promise((resolve, reject) => {
    const startTime = Date.now();
    
    const poll = async () => {
      try {
        const result = await queryRecognizeResult(activityId);
        
        // 检查是否有识别结果
        if (result && result.result) {
          resolve(result);
          return;
        }
        
        // 检查是否超时
        if (Date.now() - startTime >= timeout) {
          reject(new Error('识别超时'));
          return;
        }
        
        // 继续轮询
        setTimeout(poll, interval);
      } catch (error) {
        // 查询失败，继续轮询
        if (Date.now() - startTime >= timeout) {
          reject(new Error('识别超时'));
          return;
        }
        setTimeout(poll, interval);
      }
    };
    
    poll();
  });
};

/**
 * 轮询订单信息
 * @param activityId 活动ID
 * @param timeout 超时时间（毫秒）
 * @param interval 轮询间隔（毫秒）
 */
export const pollOrderInfo = (
  activityId: string,
  timeout: number = 60000,
  interval: number = 1000
): Promise<OrderInfoResponse> => {
  return new Promise((resolve, reject) => {
    const startTime = Date.now();
    
    const poll = async () => {
      try {
        const order = await queryOrderInfo(undefined, activityId);
        
        // 检查是否有订单信息
        if (order && order.orderId) {
          resolve(order);
          return;
        }
        
        // 检查是否超时
        if (Date.now() - startTime >= timeout) {
          reject(new Error('获取订单超时'));
          return;
        }
        
        // 继续轮询
        setTimeout(poll, interval);
      } catch (error) {
        // 查询失败，继续轮询
        if (Date.now() - startTime >= timeout) {
          reject(new Error('获取订单超时'));
          return;
        }
        setTimeout(poll, interval);
      }
    };
    
    poll();
  });
};