import axios, { AxiosInstance } from 'axios';
import {
  FeiePrinter,
  CreatePrinterRequest,
  UpdatePrinterRequest,
  PrinterListResponse,
  PrinterQueryParams,
  FeiePrintTask,
  PrintTaskQueryParams,
  PrintTaskListResponse,
  SubmitPrintTaskRequest,
  SubmitPrintTaskResponse,
  RetryPrintTaskRequest,
  CancelPrintTaskRequest,
  FeieConfig,
  ConfigListResponse,
  UpdateConfigRequest,
  ApiResponse
} from '../types/feiePrinter';

/**
 * 生成API路径（不包含baseURL）
 */
function apiUrl(path: string): string {
  return path.startsWith('/') ? path : `/${path}`;
}

/**
 * 飞鹅打印API客户端配置
 */
export interface FeiePrinterClientConfig {
  baseURL: string;
  timeout?: number;
  headers?: Record<string, string>;
}

/**
 * 飞鹅打印API客户端
 */
export class FeiePrinterClient {
  private client: AxiosInstance;

  constructor(config: FeiePrinterClientConfig) {
    this.client = axios.create({
      baseURL: config.baseURL,
      timeout: config.timeout || 10000,
      headers: {
        'Content-Type': 'application/json',
        ...config.headers
      }
    });
  }

  /**
   * 设置认证token
   */
  setAuthToken(token: string): void {
    this.client.defaults.headers.common['Authorization'] = `Bearer ${token}`;
  }

  /**
   * 设置租户ID
   */
  setTenantId(tenantId: number): void {
    this.client.defaults.headers.common['X-Tenant-Id'] = tenantId.toString();
  }

  // ==================== 打印机管理API ====================

  /**
   * 查询打印机列表
   */
  async getPrinters(params?: PrinterQueryParams): Promise<PrinterListResponse> {
    const response = await this.client.get<ApiResponse<PrinterListResponse>>(apiUrl('/printers'), {
      params
    });
    // console.log("getPrintersresponse:",response);
    if (!response.data.success) {
      throw new Error(response.data.message || '获取打印机列表失败');
    }
    return response.data.data!;
  }

  /**
   * 添加打印机
   */
  async addPrinter(request: CreatePrinterRequest): Promise<FeiePrinter> {
    const response = await this.client.post<ApiResponse<FeiePrinter>>(apiUrl(`/printers`), request);
    if (!response.data.success) {
      throw new Error(response.data.message || '添加打印机失败');
    }
    return response.data.data!;
  }

  /**
   * 获取打印机详情
   */
  async getPrinter(printerSn: string): Promise<FeiePrinter> {
    const response = await this.client.get<ApiResponse<FeiePrinter>>(apiUrl(`/printers/${printerSn}`));
    if (!response.data.success) {
      throw new Error(response.data.message || '获取打印机详情失败');
    }
    return response.data.data!;
  }

  /**
   * 更新打印机
   */
  async updatePrinter(printerSn: string, request: UpdatePrinterRequest): Promise<FeiePrinter> {
    const response = await this.client.put<ApiResponse<FeiePrinter>>(apiUrl(`/printers/${printerSn}`), request);
    if (!response.data.success) {
      throw new Error(response.data.message || '更新打印机失败');
    }
    return response.data.data!;
  }

  /**
   * 删除打印机
   */
  async deletePrinter(printerSn: string): Promise<void> {
    const response = await this.client.delete<ApiResponse<void>>(apiUrl(`/printers/${printerSn}`));
    if (!response.data.success) {
      throw new Error(response.data.message || '删除打印机失败');
    }
  }

  /**
   * 获取打印机状态
   */
  async getPrinterStatus(printerSn: string): Promise<{ status: string; lastCheck: string }> {
    const response = await this.client.get<ApiResponse<{ status: string; lastCheck: string }>>(
      apiUrl(`/printers/${printerSn}/status`)
    );
    if (!response.data.success) {
      throw new Error(response.data.message || '获取打印机状态失败');
    }
    return response.data.data!;
  }

  /**
   * 设置默认打印机
   */
  async setDefaultPrinter(printerSn: string): Promise<FeiePrinter> {
    const response = await this.client.post<ApiResponse<FeiePrinter>>(
      apiUrl(`/printers/${printerSn}/set-default`)
    );
    if (!response.data.success) {
      throw new Error(response.data.message || '设置默认打印机失败');
    }
    return response.data.data!;
  }

  // ==================== 打印任务管理API ====================

  /**
   * 查询打印任务列表
   */
  async getPrintTasks(params?: PrintTaskQueryParams): Promise<PrintTaskListResponse> {
    const response = await this.client.get<ApiResponse<PrintTaskListResponse>>(apiUrl('/tasks'), {
      params
    });
    // console.log("taskresponse:",response);
    if (!response.data.success) {
      throw new Error(response.data.message || '获取打印任务列表失败');
    }
    return response.data.data!;
  }

  /**
   * 获取打印任务详情
   */
  async getPrintTask(taskId: string): Promise<FeiePrintTask> {
    const response = await this.client.get<ApiResponse<FeiePrintTask>>(apiUrl(`/tasks/${taskId}`));
    if (!response.data.success) {
      throw new Error(response.data.message || '获取打印任务详情失败');
    }
    return response.data.data!;
  }

  /**
   * 提交打印任务
   */
  async submitPrintTask(request: SubmitPrintTaskRequest): Promise<SubmitPrintTaskResponse> {
    const response = await this.client.post<ApiResponse<SubmitPrintTaskResponse>>(apiUrl('/tasks'), request);
    if (!response.data.success) {
      throw new Error(response.data.message || '提交打印任务失败');
    }
    return response.data.data!;
  }

  /**
   * 获取打印任务状态
   */
  async getPrintTaskStatus(taskId: string): Promise<{ status: string; lastUpdate: string }> {
    const response = await this.client.get<ApiResponse<{ status: string; lastUpdate: string }>>(
      apiUrl(`/tasks/${taskId}/status`)
    );
    if (!response.data.success) {
      throw new Error(response.data.message || '获取打印任务状态失败');
    }
    return response.data.data!;
  }

  /**
   * 取消打印任务
   */
  async cancelPrintTask(request: CancelPrintTaskRequest): Promise<FeiePrintTask> {
    const response = await this.client.post<ApiResponse<FeiePrintTask>>(
      apiUrl(`/tasks/${request.taskId}/cancel`),
      { reason: request.reason }
    );
    if (!response.data.success) {
      throw new Error(response.data.message || '取消打印任务失败');
    }
    return response.data.data!;
  }

  /**
   * 重试打印任务
   */
  async retryPrintTask(request: RetryPrintTaskRequest): Promise<FeiePrintTask> {
    const response = await this.client.post<ApiResponse<FeiePrintTask>>(
      apiUrl(`/tasks/${request.taskId}/retry`)
    );
    if (!response.data.success) {
      throw new Error(response.data.message || '重试打印任务失败');
    }
    return response.data.data!;
  }

  // ==================== 打印配置管理API ====================

  /**
   * 查询打印配置列表
   */
  async getPrintConfigs(): Promise<ConfigListResponse> {
    const response = await this.client.get<ApiResponse<ConfigListResponse>>(apiUrl('/config'));
    if (!response.data.success) {
      throw new Error(response.data.message || '获取打印配置列表失败');
    }
    return response.data.data!;
  }

  /**
   * 更新打印配置
   */
  async updatePrintConfig(configKey: string, request: UpdateConfigRequest): Promise<FeieConfig> {
    const response = await this.client.put<ApiResponse<FeieConfig>>(
      apiUrl(`/config/${configKey}`),
      request
    );
    if (!response.data.success) {
      throw new Error(response.data.message || '更新打印配置失败');
    }
    return response.data.data!;
  }

  // ==================== 调度器管理API ====================

  /**
   * 获取调度器状态
   */
  async getSchedulerStatus(): Promise<{ running: boolean; lastRun: string; nextRun: string }> {
    const response = await this.client.get<ApiResponse<{ running: boolean; lastRun: string; nextRun: string }>>(
      apiUrl('/scheduler/status'));
    if (!response.data.success) {
      throw new Error(response.data.message || '获取调度器状态失败');
    }
    return response.data.data!;
  }

  /**
   * 启动调度器
   */
  async startScheduler(): Promise<void> {
    const response = await this.client.post<ApiResponse<void>>(apiUrl('/scheduler/start'));
    if (!response.data.success) {
      throw new Error(response.data.message || '启动调度器失败');
    }
  }

  /**
   * 停止调度器
   */
  async stopScheduler(): Promise<void> {
    const response = await this.client.post<ApiResponse<void>>(apiUrl('/scheduler/stop'));
    if (!response.data.success) {
      throw new Error(response.data.message || '停止调度器失败');
    }
  }

  /**
   * 获取调度器健康状态
   */
  async getSchedulerHealth(): Promise<{ healthy: boolean; message: string; timestamp: string }> {
    const response = await this.client.get<ApiResponse<{ healthy: boolean; message: string; timestamp: string }>>(
      apiUrl('/scheduler/health'));
    if (!response.data.success) {
      throw new Error(response.data.message || '获取调度器健康状态失败');
    }
    return response.data.data!;
  }
}

/**
 * 创建默认的飞鹅打印API客户端
 */
export function createFeiePrinterClient(baseURL: string = '/api/v1/feie'): FeiePrinterClient {
  return new FeiePrinterClient({
    baseURL,
    timeout: 10000
  });
}