/**
 * 轻量级客户端通信服务
 * 前端通过WebSocket与本地客户端exe程序通信
 */

interface ClientConnection {
  id: string;
  name: string;
  host: string;
  port: number;
  status: 'connected' | 'disconnected' | 'error';
  lastSeen: Date;
}

interface Command {
  type: 'authorize' | 'getProducts' | 'updatePrice' | 'getOrders';
  platform: string;
  data: any;
}

interface CommandResponse {
  success: boolean;
  data?: any;
  error?: string;
}

export class LightweightClientService {
  private connections: Map<string, WebSocket> = new Map();
  private clientList: ClientConnection[] = [];

  /**
   * 连接到本地客户端
   */
  async connectToClient(host: string = 'localhost', port: number = 8080): Promise<string> {
    const clientId = `${host}:${port}`;
    
    if (this.connections.has(clientId)) {
      return clientId; // 已连接
    }

    return new Promise((resolve, reject) => {
      try {
        const ws = new WebSocket(`ws://${host}:${port}`);
        
        ws.onopen = () => {
          console.log(`连接到客户端 ${clientId} 成功`);
          this.connections.set(clientId, ws);
          
          // 添加到客户端列表
          this.clientList.push({
            id: clientId,
            name: `客户端-${this.clientList.length + 1}`,
            host,
            port,
            status: 'connected',
            lastSeen: new Date()
          });
          
          resolve(clientId);
        };

        ws.onerror = (error) => {
          console.error(`连接客户端 ${clientId} 失败:`, error);
          reject(new Error(`无法连接到客户端: ${host}:${port}`));
        };

        ws.onclose = () => {
          console.log(`客户端 ${clientId} 连接关闭`);
          this.connections.delete(clientId);
          this.updateClientStatus(clientId, 'disconnected');
        };

        // 设置消息超时
        setTimeout(() => {
          if (!this.connections.has(clientId)) {
            reject(new Error('连接超时'));
          }
        }, 5000);

      } catch (error) {
        reject(error);
      }
    });
  }

  /**
   * 发送命令到客户端
   */
  async sendCommand(clientId: string, command: Command): Promise<CommandResponse> {
    const ws = this.connections.get(clientId);
    
    if (!ws) {
      throw new Error(`客户端 ${clientId} 未连接`);
    }

    return new Promise((resolve, reject) => {
      const messageId = Date.now().toString();
      
      const messageHandler = (event: MessageEvent) => {
        try {
          const response: CommandResponse = JSON.parse(event.data);
          
          // 移除消息监听器
          ws.removeEventListener('message', messageHandler);
          
          // 清除超时
          clearTimeout(timeoutId);
          
          resolve(response);
        } catch (error) {
          reject(error);
        }
      };

      const timeoutId = setTimeout(() => {
        ws.removeEventListener('message', messageHandler);
        reject(new Error('命令执行超时'));
      }, 30000); // 30秒超时

      ws.addEventListener('message', messageHandler);
      
      // 发送命令
      ws.send(JSON.stringify(command));
    });
  }

  /**
   * 平台授权
   */
  async authorizePlatform(clientId: string, platform: string, authData: any): Promise<CommandResponse> {
    return this.sendCommand(clientId, {
      type: 'authorize',
      platform,
      data: authData
    });
  }

  /**
   * 获取商品列表
   */
  async getProducts(clientId: string, platform: string, pageId: string, limit: number = 10): Promise<CommandResponse> {
    return this.sendCommand(clientId, {
      type: 'getProducts',
      platform,
      data: { pageId, limit }
    });
  }

  /**
   * 更新商品价格
   */
  async updateProductPrice(clientId: string, platform: string, pageId: string, productId: string, newPrice: number): Promise<CommandResponse> {
    return this.sendCommand(clientId, {
      type: 'updatePrice',
      platform,
      data: { pageId, productId, newPrice }
    });
  }

  /**
   * 获取订单列表
   */
  async getOrders(clientId: string, platform: string, pageId: string, limit: number = 10): Promise<CommandResponse> {
    return this.sendCommand(clientId, {
      type: 'getOrders',
      platform,
      data: { pageId, limit }
    });
  }

  /**
   * 断开连接
   */
  disconnect(clientId: string): void {
    const ws = this.connections.get(clientId);
    if (ws) {
      ws.close();
      this.connections.delete(clientId);
      this.updateClientStatus(clientId, 'disconnected');
    }
  }

  /**
   * 获取客户端列表
   */
  getClientList(): ClientConnection[] {
    return [...this.clientList];
  }

  /**
   * 检查客户端健康状态
   */
  async checkClientHealth(host: string, port: number): Promise<boolean> {
    try {
      const response = await fetch(`http://${host}:${port}/health`);
      return response.ok;
    } catch (error) {
      return false;
    }
  }

  private updateClientStatus(clientId: string, status: ClientConnection['status']): void {
    const client = this.clientList.find(c => c.id === clientId);
    if (client) {
      client.status = status;
      client.lastSeen = new Date();
    }
  }
}

// 单例模式
export const lightweightClientService = new LightweightClientService();