import { requestClient } from '#/api/request';

enum Api {
  config = '/crm/sync/config',
  start = '/crm/sync/start',
  stop = '/crm/sync/stop',
  cron = '/crm/sync/cron',
  execute = '/crm/sync/execute',
  logs = '/crm/sync/logs',
  alerts = '/crm/sync/alerts',
  stats = '/crm/sync/stats',
  tenants = '/crm/sync/tenants',
  tenantCompanies = '/crm/sync/tenant-companies',
  erpCompanies = '/crm/sync/erp-companies',
  bindCompany = '/crm/sync/tenant-companies/bind',
  unbindCompany = '/crm/sync/tenant-companies/unbind',
  resolveAlert = '/crm/sync/alerts',
}

/**
 * 获取同步配置
 */
export function getSyncConfig() {
  return requestClient.get<{ enabled: boolean; cron: string }>(Api.config);
}

/**
 * 启动定时任务
 */
export function startSyncTask() {
  return requestClient.post<string>(Api.start, {});
}

/**
 * 停止定时任务
 */
export function stopSyncTask() {
  return requestClient.post<string>(Api.stop, {});
}

/**
 * 设置Cron表达式
 */
export function setSyncCron(cron: string) {
  return requestClient.put<string>(Api.cron, null, { params: { cron } });
}

/**
 * 手动触发同步
 */
export function executeSync() {
  return requestClient.post<any>(Api.execute, {});
}

/**
 * 查询同步日志
 */
export function getSyncLogs(params: { pageNum: number; pageSize: number }) {
  return requestClient.get<{ rows: any[]; total: number }>(Api.logs, { params });
}

/**
 * 查询预警列表
 */
export function getSyncAlerts(params: { pageNum: number; pageSize: number; status?: string }) {
  return requestClient.get<{ rows: any[]; total: number }>(Api.alerts, { params });
}

/**
 * 处理预警
 */
export function resolveAlert(alertId: number, action: string, note?: string) {
  return requestClient.put<string>(`${Api.resolveAlert}/${alertId}`, null, { params: { action, note } });
}

/**
 * 获取同步统计数据
 */
export function getSyncStats() {
  return requestClient.get<any>(Api.stats);
}

/**
 * 获取租户列表（用于选择器）
 */
export function getTenants() {
  return requestClient.get<any[]>(Api.tenants);
}

/**
 * 获取所有租户的ERP公司映射列表
 */
export function getTenantCompanies() {
  return requestClient.get<any[]>(Api.tenantCompanies);
}

/**
 * 获取ERP所有公司列表
 */
export function getErpCompanies() {
  return requestClient.get<any[]>(Api.erpCompanies);
}

/**
 * 绑定ERP公司到租户
 */
export function bindCompany(tenantId: string, tenantName?: string, erpCompanyId?: string, erpCompanyName?: string) {
  return requestClient.post<string>(Api.bindCompany, null, { params: { tenantId, tenantName, erpCompanyId, erpCompanyName } });
}

/**
 * 解绑ERP公司
 */
export function unbindCompany(id: number) {
  return requestClient.post<string>(`${Api.unbindCompany}/${id}`, {});
}