/**
 * 状态查询相关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 }, { silent: true });
};

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

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

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

/**
 * 轮询设备状态
 * @param deviceId 设备ID
 * @param timeout 超时时间（毫秒）
 * @param interval 轮询间隔（毫秒）
 */
export const pollDeviceStatus = (
  deviceId: string,
  timeout: number = 60000,
  interval: number = 3000,
  maxConsecutiveFailures: number = 3
): Promise<DeviceStatusResponse> => {
  return new Promise((resolve, reject) => {
    const startTime = Date.now();
    let timerId: ReturnType<typeof setTimeout> | null = null;
    let settled = false;
    let failCount = 0;

    const cleanup = () => {
      if (timerId !== null) {
        clearTimeout(timerId);
        timerId = null;
      }
    };

    const done = (result: DeviceStatusResponse | null, err?: Error) => {
      if (settled) return;
      settled = true;
      cleanup();
      if (err) {
        reject(err);
      } else if (result) {
        resolve(result);
      }
    };

    const poll = async () => {
      if (settled) return;

      try {
        const response = await queryDeviceStatus(deviceId);

        if (settled) return;

        // 成功一次就重置失败计数
        failCount = 0;

        if (response && response.doorStatus && response.doorStatus !== 'unknown') {
          const statusTime = parseInt(response.timestamp) || 0;
          if (statusTime > startTime - 10000) {
            done(response);
            return;
          }
        }

        if (Date.now() - startTime >= timeout) {
          done(null, new Error('轮询超时'));
          return;
        }

        timerId = setTimeout(poll, interval);
      } catch (error: any) {
        if (settled) return;

        // 认证失败立即中止，不重试
        if (error?.isAuthError) {
          done(null, new Error('登录已过期，请重新登录'));
          return;
        }

        failCount++;

        if (failCount >= maxConsecutiveFailures) {
          done(null, new Error('网络异常，轮询中断'));
          return;
        }

        if (Date.now() - startTime >= timeout) {
          done(null, new Error('轮询超时'));
          return;
        }

        timerId = setTimeout(poll, interval);
      }
    };

    poll();
  });
};

/**
 * 轮询识别结果
 * @param activityId 活动ID
 * @param timeout 超时时间（毫秒）
 * @param interval 轮询间隔（毫秒）
 */
export const pollRecognizeResult = (
  activityId: string,
  timeout: number = 30000,
  interval: number = 3000,
  maxConsecutiveFailures: number = 3
): Promise<RecognizeResultResponse> => {
  return new Promise((resolve, reject) => {
    const startTime = Date.now();
    let timerId: ReturnType<typeof setTimeout> | null = null;
    let settled = false;
    let failCount = 0;

    const cleanup = () => {
      if (timerId !== null) {
        clearTimeout(timerId);
        timerId = null;
      }
    };

    const done = (result: RecognizeResultResponse | null, err?: Error) => {
      if (settled) return;
      settled = true;
      cleanup();
      if (err) {
        reject(err);
      } else if (result) {
        resolve(result);
      }
    };

    const poll = async () => {
      if (settled) return;

      try {
        const result = await queryRecognizeResult(activityId);

        if (settled) return;

        failCount = 0;

        if (result && result.result) {
          done(result);
          return;
        }

        if (Date.now() - startTime >= timeout) {
          done(null, new Error('识别超时'));
          return;
        }

        timerId = setTimeout(poll, interval);
      } catch (error: any) {
        if (settled) return;

        // 认证失败立即中止，不重试
        if (error?.isAuthError) {
          done(null, new Error('登录已过期，请重新登录'));
          return;
        }

        failCount++;

        if (failCount >= maxConsecutiveFailures) {
          done(null, new Error('网络异常，轮询中断'));
          return;
        }

        if (Date.now() - startTime >= timeout) {
          done(null, new Error('识别超时'));
          return;
        }

        timerId = setTimeout(poll, interval);
      }
    };

    poll();
  });
};

/**
 * 轮询订单信息
 * @param activityId 活动ID
 * @param timeout 超时时间（毫秒）
 * @param interval 轮询间隔（毫秒）
 */
export const pollOrderInfo = (
  activityId: string,
  timeout: number = 30000,
  interval: number = 3000,
  maxConsecutiveFailures: number = 3
): Promise<OrderInfoResponse> => {
  return new Promise((resolve, reject) => {
    const startTime = Date.now();
    let timerId: ReturnType<typeof setTimeout> | null = null;
    let settled = false;
    let failCount = 0;

    const cleanup = () => {
      if (timerId !== null) {
        clearTimeout(timerId);
        timerId = null;
      }
    };

    const done = (result: OrderInfoResponse | null, err?: Error) => {
      if (settled) return;
      settled = true;
      cleanup();
      if (err) {
        reject(err);
      } else if (result) {
        resolve(result);
      }
    };

    const poll = async () => {
      if (settled) return;

      try {
        const order = await queryOrderInfo(undefined, activityId);

        if (settled) return;

        failCount = 0;

        if (order && order.orderId) {
          done(order);
          return;
        }

        if (Date.now() - startTime >= timeout) {
          done(null, new Error('获取订单超时'));
          return;
        }

        timerId = setTimeout(poll, interval);
      } catch (error: any) {
        if (settled) return;

        // 认证失败立即中止，不重试
        if (error?.isAuthError) {
          done(null, new Error('登录已过期，请重新登录'));
          return;
        }

        failCount++;

        if (failCount >= maxConsecutiveFailures) {
          done(null, new Error('网络异常，轮询中断'));
          return;
        }

        if (Date.now() - startTime >= timeout) {
          done(null, new Error('获取订单超时'));
          return;
        }

        timerId = setTimeout(poll, interval);
      }
    };

    poll();
  });
};