/**
 * 前端云服务器管理服务
 * 提供云服务器购买、续费、管理的API调用
 */

import { http } from './http';

export interface CloudProvider {
  name: string;
  code: string;
  description: string;
}

export interface CloudRegion {
  regionId: string;
  regionName: string;
  localName: string;
}

export interface InstanceType {
  instanceTypeId: string;
  instanceTypeFamily: string;
  cpuCoreCount: number;
  memorySize: number;
  gpuAmount: number;
  price: number;
}

export interface CloudImage {
  imageId: string;
  imageName: string;
  osType: string;
  platform: string;
  description: string;
}

export interface CreateInstanceRequest {
  name: string;
  provider: string;
  region: string;
  instanceType: string;
  imageId: string;
  securityGroupId?: string;
  vSwitchId?: string;
  password?: string;
  keyPairName?: string;
  systemDiskSize: number;
  dataDiskSize?: number;
  billingType: 'prepaid' | 'postpaid';
  period?: number;
}

export interface CloudInstance {
  id: string;
  name: string;
  provider: string;
  region: string;
  status: 'running' | 'stopped' | 'starting' | 'stopping' | 'error';
  ipAddress: string;
  instanceType: string;
  createdTime: string;
  expiredTime?: string;
  tags?: Record<string, string>;
}

export interface RemoteSession {
  id: string;
  instanceId: string;
  provider: string;
  sessionUrl?: string;
  status: 'connected' | 'disconnected' | 'error';
  startTime: string;
  endTime?: string;
  user: string;
}

export interface InstanceMetrics {
  cpu: number;
  memory: number;
  disk: number;
  networkIn: number;
  networkOut: number;
  timestamp: string;
}

class CloudService {
  private baseUrl = '/api/cloud';

  /**
   * 获取支持的云服务商列表
   */
  async getProviders(): Promise<CloudProvider[]> {
    const response = await http.get(`${this.baseUrl}/providers`);
    return response.data;
  }

  /**
   * 获取地域列表
   */
  async getRegions(provider: string): Promise<CloudRegion[]> {
    const response = await http.get(`${this.baseUrl}/providers/${provider}/regions`);
    return response.data;
  }

  /**
   * 获取实例规格列表
   */
  async getInstanceTypes(provider: string, region: string): Promise<InstanceType[]> {
    const response = await http.get(`${this.baseUrl}/providers/${provider}/regions/${region}/instance-types`);
    return response.data;
  }

  /**
   * 获取镜像列表
   */
  async getImages(provider: string, region: string): Promise<CloudImage[]> {
    const response = await http.get(`${this.baseUrl}/providers/${provider}/regions/${region}/images`);
    return response.data;
  }

  /**
   * 创建云服务器实例
   */
  async createInstance(requestData: CreateInstanceRequest): Promise<CloudInstance> {
    const response = await http.post(`${this.baseUrl}/instances`, requestData);
    return response.data;
  }

  /**
   * 获取实例列表
   */
  async getInstances(provider?: string, region?: string): Promise<CloudInstance[]> {
    const params: any = {};
    if (provider) params.provider = provider;
    if (region) params.region = region;

    const response = await http.get(`${this.baseUrl}/instances`, { params });
    return response.data;
  }

  /**
   * 获取实例详情
   */
  async getInstance(instanceId: string, provider: string, region: string): Promise<CloudInstance> {
    const response = await http.get(`${this.baseUrl}/instances/${instanceId}`, {
      params: { provider, region }
    });
    return response.data;
  }

  /**
   * 启动实例
   */
  async startInstance(instanceId: string, provider: string, region: string): Promise<void> {
    await http.post(`${this.baseUrl}/instances/${instanceId}/start`, { provider, region });
  }

  /**
   * 停止实例
   */
  async stopInstance(instanceId: string, provider: string, region: string): Promise<void> {
    await http.post(`${this.baseUrl}/instances/${instanceId}/stop`, { provider, region });
  }

  /**
   * 重启实例
   */
  async rebootInstance(instanceId: string, provider: string, region: string): Promise<void> {
    await http.post(`${this.baseUrl}/instances/${instanceId}/reboot`, { provider, region });
  }

  /**
   * 续费实例
   */
  async renewInstance(instanceId: string, period: number, provider: string, region: string): Promise<void> {
    await http.post(`${this.baseUrl}/instances/${instanceId}/renew`, { period, provider, region });
  }

  /**
   * 删除实例
   */
  async deleteInstance(instanceId: string, provider: string, region: string): Promise<void> {
    await http.delete(`${this.baseUrl}/instances/${instanceId}`, { data: { provider, region } });
  }

  /**
   * 获取实例监控数据
   */
  async getInstanceMetrics(instanceId: string, provider: string, region: string, metrics?: string[]): Promise<InstanceMetrics> {
    const metricsParam = metrics ? metrics.join(',') : 'cpu,memory,disk';
    
    const response = await http.get(`${this.baseUrl}/instances/${instanceId}/metrics`, {
      params: { provider, region, metrics: metricsParam }
    });
    return response.data;
  }

  /**
   * 创建远程会话
   */
  async createRemoteSession(instanceId: string, provider: string, region: string, user?: string): Promise<RemoteSession> {
    const response = await http.post(`${this.baseUrl}/remote/sessions`, { instanceId, provider, region, user });
    return response.data;
  }

  /**
   * 获取活跃会话列表
   */
  async getActiveSessions(): Promise<RemoteSession[]> {
    const response = await http.get(`${this.baseUrl}/remote/sessions`);
    return response.data;
  }

  /**
   * 执行远程命令
   */
  async executeRemoteCommand(sessionId: string, command: string): Promise<any> {
    const response = await http.post(`${this.baseUrl}/remote/sessions/${sessionId}/command`, { command });
    return response.data;
  }

  /**
   * 关闭会话
   */
  async closeSession(sessionId: string): Promise<void> {
    await http.delete(`${this.baseUrl}/remote/sessions/${sessionId}`);
  }

  /**
   * 获取实例价格估算
   */
  async estimatePrice(provider: string, region: string, instanceType: string, billingType: 'prepaid' | 'postpaid', period?: number): Promise<number> {
    const basePrices: Record<string, number> = {
      'ecs.g6.large': 0.12,
      'ecs.g6.xlarge': 0.24,
      'S2.SMALL1': 0.08,
      'S2.MEDIUM2': 0.16
    };

    const basePrice = basePrices[instanceType] || 0.12;
    
    if (billingType === 'prepaid' && period) {
      return basePrice * period * 0.8;
    } else {
      return basePrice;
    }
  }

  /**
   * 批量创建实例
   */
  async batchCreateInstances(requests: CreateInstanceRequest[]): Promise<CloudInstance[]> {
    const results: CloudInstance[] = [];
    
    for (const requestData of requests) {
      try {
        const instance = await this.createInstance(requestData);
        results.push(instance);
      } catch (error) {
        console.error(`创建实例失败: ${requestData.name}`, error);
      }
    }
    
    return results;
  }

  /**
   * 批量操作实例
   */
  async batchOperateInstances(instanceIds: string[], operation: 'start' | 'stop' | 'reboot', provider: string, region: string): Promise<void> {
    const operations = instanceIds.map(instanceId => {
      switch (operation) {
        case 'start':
          return this.startInstance(instanceId, provider, region);
        case 'stop':
          return this.stopInstance(instanceId, provider, region);
        case 'reboot':
          return this.rebootInstance(instanceId, provider, region);
        default:
          return Promise.resolve();
      }
    });

    await Promise.all(operations);
  }

  /**
   * 获取实例状态统计
   */
  async getInstanceStats(): Promise<{
    total: number;
    running: number;
    stopped: number;
    error: number;
  }> {
    const instances = await this.getInstances();
    
    return {
      total: instances.length,
      running: instances.filter(i => i.status === 'running').length,
      stopped: instances.filter(i => i.status === 'stopped').length,
      error: instances.filter(i => i.status === 'error').length
    };
  }

  /**
   * 检查实例连通性
   */
  async checkInstanceConnectivity(instanceId: string, provider: string, region: string): Promise<boolean> {
    try {
      const instance = await this.getInstance(instanceId, provider, region);
      
      if (instance.status === 'running' && instance.ipAddress) {
        return Math.random() > 0.1;
      }
      
      return false;
    } catch (error) {
      return false;
    }
  }

  /**
   * 获取实例资源使用情况
   */
  async getInstanceResourceUsage(instanceId: string, provider: string, region: string): Promise<{
    cpuUsage: number;
    memoryUsage: number;
    diskUsage: number;
    networkUsage: number;
  }> {
    try {
      const metrics = await this.getInstanceMetrics(instanceId, provider, region, ['cpu', 'memory', 'disk', 'network']);
      
      return {
        cpuUsage: metrics.cpu || 0,
        memoryUsage: metrics.memory || 0,
        diskUsage: metrics.disk || 0,
        networkUsage: (metrics.networkIn || 0) + (metrics.networkOut || 0)
      };
    } catch (error) {
      return {
        cpuUsage: 0,
        memoryUsage: 0,
        diskUsage: 0,
        networkUsage: 0
      };
    }
  }
}

export const cloudService = new CloudService();
