/**
 * 合同管理服务
 * [2026-02-05] 新增：负责合同管理相关的 API 调用
 * 回滚方式：删除此文件
 */

import apiClient from '@/infrastructure/api/client';
import { API_ENDPOINTS } from '@/infrastructure/api/endpoints';

/**
 * 合同 DTO
 */
export interface ContractDto {
  orderNo: string;
  contractNo: string;
  userId: string;
  accountSequence: string;
  userRealName: string | null;
  userPhoneNumber: string | null;
  treeCount: number;
  totalAmount: number;
  provinceCode: string;
  provinceName: string;
  cityCode: string;
  cityName: string;
  status: string;
  signedAt: string | null;
  signedPdfUrl: string | null;
  createdAt: string;
}

/**
 * 合同列表响应
 */
export interface ContractsListResponse {
  items: ContractDto[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

/**
 * 合同统计响应
 */
export interface ContractStatisticsResponse {
  totalContracts: number;
  signedContracts: number;
  pendingContracts: number;
  expiredContracts: number;
}

/**
 * 合同查询参数
 */
export interface ContractQueryParams {
  signedAfter?: string;
  signedBefore?: string;
  provinceCode?: string;
  cityCode?: string;
  status?: string;
  page?: number;
  pageSize?: number;
  orderBy?: 'signedAt' | 'createdAt';
  orderDir?: 'asc' | 'desc';
}

/**
 * 批量下载请求
 */
export interface BatchDownloadRequest {
  filters?: {
    signedAfter?: string;
    signedBefore?: string;
    provinceCode?: string;
    cityCode?: string;
  };
  orderNos?: string[];
}

/**
 * 批量下载任务响应
 */
export interface BatchDownloadTaskResponse {
  taskId: string;
  taskNo: string;
  status: 'PENDING' | 'PROCESSING' | 'COMPLETED' | 'FAILED' | 'CANCELLED';
  totalContracts: number;
  downloadedCount: number;
  failedCount: number;
  progress: number;
  resultFileUrl: string | null;
  resultFileSize: string | null;
  errors: unknown | null;
  createdAt: string;
  startedAt: string | null;
  completedAt: string | null;
  expiresAt: string | null;
}

/**
 * 合同状态标签
 */
export const CONTRACT_STATUS_LABELS: Record<string, string> = {
  PENDING: '待签署',
  SCROLLED: '已阅读',
  ACKNOWLEDGED: '已确认',
  SIGNED: '已签署',
  EXPIRED: '已超时',
  TIMEOUT: '已超时',
};

/**
 * 获取合同状态对应的颜色类名
 */
export const getContractStatusColor = (status: string): string => {
  switch (status) {
    case 'SIGNED':
      return 'text-green-600';
    case 'PENDING':
    case 'SCROLLED':
    case 'ACKNOWLEDGED':
      return 'text-yellow-600';
    case 'EXPIRED':
    case 'TIMEOUT':
      return 'text-red-600';
    default:
      return 'text-gray-600';
  }
};

/**
 * 合同管理服务
 */
export const contractService = {
  /**
   * 获取合同列表
   */
  async getContracts(params?: ContractQueryParams): Promise<ContractsListResponse> {
    return apiClient.get(API_ENDPOINTS.CONTRACTS.LIST, { params });
  },

  /**
   * 获取合同统计信息
   */
  async getStatistics(params?: {
    provinceCode?: string;
    cityCode?: string;
  }): Promise<ContractStatisticsResponse> {
    return apiClient.get(API_ENDPOINTS.CONTRACTS.STATISTICS, { params });
  },

  /**
   * 获取单个合同详情
   */
  async getContract(orderNo: string): Promise<ContractDto> {
    return apiClient.get(API_ENDPOINTS.CONTRACTS.DETAIL(orderNo));
  },

  /**
   * 获取用户的合同列表
   */
  async getUserContracts(
    accountSequence: string,
    params?: { page?: number; pageSize?: number },
  ): Promise<ContractsListResponse> {
    return apiClient.get(API_ENDPOINTS.CONTRACTS.USER_CONTRACTS(accountSequence), { params });
  },

  /**
   * 下载合同 PDF
   * 返回下载 URL，前端直接打开进行下载
   */
  getDownloadUrl(orderNo: string): string {
    // 获取 API 基础 URL（与 .env.production 中的变量名一致）
    const baseUrl = process.env.NEXT_PUBLIC_API_BASE_URL || '';
    return `${baseUrl}${API_ENDPOINTS.CONTRACTS.DOWNLOAD(orderNo)}`;
  },

  /**
   * 创建批量下载任务
   */
  async createBatchDownload(request: BatchDownloadRequest): Promise<{
    success: boolean;
    taskId: string;
    taskNo: string;
    status: string;
    createdAt: string;
  }> {
    return apiClient.post(API_ENDPOINTS.CONTRACTS.BATCH_DOWNLOAD, request);
  },

  /**
   * 获取批量下载任务状态
   */
  async getBatchDownloadStatus(taskNo: string): Promise<BatchDownloadTaskResponse> {
    return apiClient.get(API_ENDPOINTS.CONTRACTS.BATCH_DOWNLOAD_STATUS(taskNo));
  },
};

export default contractService;
