/**
 * filekorolheader: 审核历史API接口 - 企业审核记录查询接口服务
 * 功能：API请求封装、数据转换、错误处理、分页查询
 * 路径：/central-config/tenant/audit-history/components/auditHistoryApi
 * 规范：遵循crop-x/docs/开发项目规范.md，使用SDK API调用，TypeScript类型安全
 */

// API响应数据类型定义
import { getAuthToken } from "@/utils/token.ts";
import {
  getTenantAuditLogsApiV1TenantsAuditLogsGet,
} from "@/lib/api/sdk.gen";

export interface AuditLogData {
  id: string;
  action: string;
  action_by: string;
  action_time: string;
  snapshot_company_name: string;
  snapshot_company_type: string | null;
  snapshot_province: string | null;
  snapshot_city: string | null;
  snapshot_district: string | null;
  snapshot_detailed_address: string | null;
  snapshot_registrant: string | null;
  snapshot_contact_phone: string | null;
  snapshot_bank_account: string | null;
  snapshot_bank_name: string | null;
  snapshot_bank_full_name: string | null;
  snapshot_bank_address: string | null;
  snapshot_social_credit_code: string | null;
  snapshot_legal_person_name: string | null;
  snapshot_audit_status: string;
  snapshot_audit_comment: string | null;
  snapshot_company_scale: string | null;
  snapshot_registered_capital: string | null;
  change_summary: string;
  ip_address: string | null;
  user_agent: string | null;
  request_id: string | null;
  created_at: string;
}

// API响应接口
export interface AuditLogsApiResponse {
  data: AuditLogData[];
  total: number;
  page: number;
  size: number;
  total_pages: number;
  has_next: boolean;
  has_prev: boolean;
}

// 查询参数接口
export interface AuditLogsQueryParams {
  tenant_id?: string;
  page?: number;
  size?: number;
  order_by?: string;
  sort_order?: 'asc' | 'desc';
}

// 审核记录页面数据类型（转换后的）
export interface AuditRecord {
  id: string;
  enterpriseId?: string;
  enterpriseName: string;
  action: 'SUBMIT' | 'AUDIT';
  auditType: 'register' | 'update';
  submitTime: string;
  actionTime: string;
  actionBy: string;
  result: 'pending' | 'approved' | 'rejected' | 'draft';
  auditStatus: string;
  auditComment?: string;
  changeSummary: string;
  ipAddress?: string;
  userAgent?: string;
  requestId?: string;
  createdAt: string;

  // 快照数据
  snapshot: {
    companyName: string;
    companyType: string | null;
    province: string | null;
    city: string | null;
    district: string | null;
    detailedAddress: string | null;
    registrant: string | null;
    contactPhone: string | null;
    bankAccount: string | null;
    bankName: string | null;
    bankFullName: string | null;
    bankAddress: string | null;
    socialCreditCode: string | null;
    legalPersonName: string | null;
    auditStatus: string;
    auditComment: string | null;
    companyScale: string | null;
    registeredCapital: string | null;
  };
}

/**
 * 获取审核历史记录数据
 */
export async function fetchAuditLogs(params: AuditLogsQueryParams = {}): Promise<AuditLogsApiResponse> {
  try {
    // 调用计数器
    console.log(`[API] fetchAuditLogs 调用次数: ${++fetchAuditLogs.callCount || (fetchAuditLogs.callCount = 1)}`, params);

    // 构建查询参数对象
    const queryParams: any = {};

    queryParams.tenant_id = "";
    if (params.page) queryParams.page = params.page;
    if (params.size) queryParams.size = params.size;
    if (params.order_by) queryParams.order_by = params.order_by;
    if (params.sort_order) queryParams.sort_order = params.sort_order;

    // 默认参数
    if (!params.page) queryParams.page = 1;
    if (!params.size) queryParams.size = 10;

    // 使用SDK API调用审核历史查询接口，添加缓存破坏器和认证头部
    const token = getAuthToken();
    const response = await getTenantAuditLogsApiV1TenantsAuditLogsGet({
      query: {
        ...queryParams,
        // 添加时间戳防止缓存
        _t: Date.now(),
      },
      headers: token ? {
        'Authorization': `Bearer ${token}`,
      } : undefined,
    });

    if (response.error) {
      throw new Error(`API error: ${response.error.message || 'Unknown error'}`);
    }

    const data = response.data as any;

    // 转换响应数据格式以匹配现有的接口
    return {
      data: data?.data || [],
      total: data?.total || 0,
      page: data?.page || 1,
      size: data?.size || 10,
      total_pages: data?.total_pages || 0,
      has_next: data?.has_next || false,
      has_prev: data?.has_prev || false,
    };
  } catch (error) {
    console.error('Failed to fetch audit logs:', error);
    throw error;
  }
}

/**
 * 将API数据转换为页面所需的审核记录格式
 */
export function transformAuditLogData(log: AuditLogData): AuditRecord {
  // 判断审核类型
  let auditType: 'register' | 'update' = 'register';
  if (log.change_summary.includes('更新') || log.change_summary.includes('修改')) {
    auditType = 'update';
  }

  // 映射审核状态
  let result: 'pending' | 'approved' | 'rejected' | 'draft' = 'pending';
  const status = log.snapshot_audit_status.toLowerCase();
  if (status.includes('草稿') || status.includes('draft')) {
    result = 'draft';
  } else if (status.includes('待审核') || status.includes('pending')) {
    result = 'pending';
  } else if (status.includes('已通过') || status.includes('approved')) {
    result = 'approved';
  } else if (status.includes('已拒绝') || status.includes('rejected')) {
    result = 'rejected';
  }

  return {
    id: log.id,
    enterpriseId: log.action_by, // 使用操作人作为企业ID关联
    enterpriseName: log.snapshot_company_name,
    action: log.action as 'SUBMIT' | 'AUDIT',
    auditType,
    submitTime: formatDate(log.action_time),
    actionTime: formatDate(log.action_time),
    actionBy: log.action_by,
    result,
    auditStatus: log.snapshot_audit_status,
    auditComment: log.snapshot_audit_comment,
    changeSummary: log.change_summary,
    ipAddress: log.ip_address,
    userAgent: log.user_agent,
    requestId: log.request_id,
    createdAt: formatDate(log.created_at),

    // 快照数据
    snapshot: {
      companyName: log.snapshot_company_name,
      companyType: log.snapshot_company_type,
      province: log.snapshot_province,
      city: log.snapshot_city,
      district: log.snapshot_district,
      detailedAddress: log.snapshot_detailed_address,
      registrant: log.snapshot_registrant,
      contactPhone: log.snapshot_contact_phone,
      bankAccount: log.snapshot_bank_account,
      bankName: log.snapshot_bank_name,
      bankFullName: log.snapshot_bank_full_name,
      bankAddress: log.snapshot_bank_address,
      socialCreditCode: log.snapshot_social_credit_code,
      legalPersonName: log.snapshot_legal_person_name,
      auditStatus: log.snapshot_audit_status,
      auditComment: log.snapshot_audit_comment,
      companyScale: log.snapshot_company_scale,
      registeredCapital: log.snapshot_registered_capital,
    },
  };
}

/**
 * 格式化日期
 */
function formatDate(dateString: string): string {
  try {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    }).replace(/\//g, '-');
  } catch (error) {
    return dateString;
  }
}