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

// API响应数据类型定义
import { getAuthToken } from "@/utils/token.ts";
import {
  listTenantsApiV1TenantsGet,
  enableTenantApiV1TenantsTenantIdEnablePatch,
  disableTenantApiV1TenantsTenantIdDisablePatch,
  createTenantApiV1TenantsPost
} from "@/lib/api/sdk.gen";
export interface TenantData {
  id: string;
  tenant_code: string;
  is_active: boolean;
  company_name: string;
  company_type: string | null;
  province: string | null;
  city: string | null;
  district: string | null;
  detailed_address: string | null;
  registrant: string | null;
  contact_phone: string | null;
  bank_account: string | null;
  bank_name: string | null;
  bank_full_name: string | null;
  bank_address: string | null;
  social_credit_code: string | null;
  legal_person_name: string | null;
  company_scale: string | null;
  registered_capital: string | null;
  established_date: string | null;
  invoice_type: string | null;
  business_scope: string | null;
  submit_time: string | null;
  audit_time: string | null;
  auditor: string | null;
  audit_status: string;
  audit_comment: string | null;
  created_at: string;
  updated_at: string;
}

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

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

// 新建企业请求参数接口
export interface CreateEnterpriseRequest {
  company_name: string;
  tenant_code: string;
  company_type: string;
}

// 企业页面数据类型（转换后的）
export interface Enterprise {
  id: string;
  name: string;
  code: string;
  type: string;
  status: 'active' | 'inactive';
  auditStatus: 'not_submitted' | 'pending' | 'approved' | 'rejected' | 'draft';
  createdAt: string;
  updatedAt: string;
  contact?: string;
  phone?: string;
  contactPhone?: string;
  province?: string;
  city?: string;
  district?: string;
  address?: string;
  registrant?: string;
  companySize?: string;
  registeredCapital?: string;
  establishmentDate?: string;
  invoiceType?: string;
  socialCreditCode?: string;
  businessScope?: string;
  legalPerson?: string;
  bankAccount?: string;
  bankName?: string;
  bankFullName?: string;
  bankAddress?: string;
  submitTime?: string;
  auditTime?: string;
  auditor?: string;
  auditComment?: string;
}

/**
 * 获取企业列表数据
 */
export async function fetchTenants(params: TenantsQueryParams = {}): Promise<TenantsApiResponse> {
  try {
    // 构建查询参数对象
    const queryParams: any = {};

    if (params.search) queryParams.search = params.search;
    if (params.audit_status) queryParams.audit_status = params.audit_status;
    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;
    if (!params.sort_order) queryParams.sort_order = 'desc';

    // 使用SDK API调用企业查询接口，添加缓存破坏器和认证头部
    const token = getAuthToken();
    const response = await listTenantsApiV1TenantsGet({
      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;

    // 转换响应数据格式以匹配现有的接口
    // API返回的数据结构: { data: [...], total: 25, page: 1, size: 10, ... }
    return {
      data: data?.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 tenants:', error);
    throw error;
  }
}

/**
 * 启用企业
 */
export async function enableTenant(tenantId: string): Promise<TenantData> {
  try {
    const token = getAuthToken();
    console.log('启用企业API调用:', tenantId);

    const response = await enableTenantApiV1TenantsTenantIdEnablePatch({
      path: {
        tenant_id: tenantId,
      },
      headers: token ? {
        'Authorization': `Bearer ${token}`,
      } : undefined,
    });

    if (response.error) {
      throw new Error(`启用企业失败: ${response.error.message || 'Unknown error'}`);
    }

    const data = response.data as TenantData;
    console.log('启用企业API响应:', data);

    // 验证返回的数据中is_active是否为true
    if (data.is_active !== true) {
      throw new Error('启用企业失败：返回数据状态不正确');
    }

    return data;
  } catch (error) {
    console.error('Failed to enable tenant:', error);
    throw error;
  }
}

/**
 * 禁用企业
 */
export async function disableTenant(tenantId: string): Promise<TenantData> {
  try {
    const token = getAuthToken();
    console.log('禁用企业API调用:', tenantId);

    const response = await disableTenantApiV1TenantsTenantIdDisablePatch({
      path: {
        tenant_id: tenantId,
      },
      headers: token ? {
        'Authorization': `Bearer ${token}`,
      } : undefined,
    });

    if (response.error) {
      throw new Error(`禁用企业失败: ${response.error.message || 'Unknown error'}`);
    }

    const data = response.data as TenantData;
    console.log('禁用企业API响应:', data);

    // 验证返回的数据中is_active是否为false
    if (data.is_active !== false) {
      throw new Error('禁用企业失败：返回数据状态不正确');
    }

    return data;
  } catch (error) {
    console.error('Failed to disable tenant:', error);
    throw error;
  }
}

/**
 * 将API数据转换为页面所需的企业数据格式
 */
export function transformTenantData(tenant: TenantData): Enterprise {
  return {
    id: tenant.id,
    name: tenant.company_name,
    code: tenant.tenant_code,
    type: tenant.company_type || '未分类',
    status: tenant.is_active ? 'active' : 'inactive',
    auditStatus: mapAuditStatus(tenant.audit_status),
    createdAt: formatDate(tenant.created_at),
    updatedAt: formatDate(tenant.updated_at),
    contact: tenant.registrant,
    phone: tenant.contact_phone,
    contactPhone: tenant.contact_phone,
    province: tenant.province,
    city: tenant.city,
    district: tenant.district,
    address: tenant.detailed_address,
    registrant: tenant.registrant,
    companySize: tenant.company_scale,
    registeredCapital: tenant.registered_capital,
    establishmentDate: tenant.established_date ?
      new Date(tenant.established_date).toLocaleDateString('zh-CN') : undefined,
    invoiceType: tenant.invoice_type,
    socialCreditCode: tenant.social_credit_code,
    businessScope: tenant.business_scope,
    legalPerson: tenant.legal_person_name,
    bankAccount: tenant.bank_account,
    bankName: tenant.bank_name,
    bankFullName: tenant.bank_full_name,
    bankAddress: tenant.bank_address,
    submitTime: tenant.submit_time ? formatDate(tenant.submit_time) : undefined,
    auditTime: tenant.audit_time ? formatDate(tenant.audit_time) : undefined,
    auditor: tenant.auditor,
    auditComment: tenant.audit_comment,
  };
}

/**
 * 映射审核状态
 */
function mapAuditStatus(status: string): Enterprise['auditStatus'] {
  switch (status) {
    case '未提交':
    case '草稿':
      return 'draft';
    case '待审核':
      return 'pending';
    case '已通过':
    case '审核通过':
      return 'approved';
    case '已拒绝':
    case '已驳回':
      return 'rejected';
    default:
      return 'draft';
  }
}

/**
 * 创建新企业
 * @param data 企业创建数据
 * @returns 创建结果
 */
export async function createEnterprise(data: CreateEnterpriseRequest): Promise<TenantData> {
  try {
    console.log('🏢 创建企业API调用:', data);

    // 获取认证token
    const token = getAuthToken();

    // 使用SDK API调用创建企业接口
    const response = await createTenantApiV1TenantsPost({
      body: data,
      headers: token ? {
        'Authorization': `Bearer ${token}`,
      } : undefined,
    });

    if (response.error) {
      console.error('🏢 创建企业API错误:', response.error);
      throw new Error(`创建失败: ${response.error.message || '未知错误'}`);
    }

    const result = response.data as TenantData;
    console.log('🏢 创建企业API成功:', result);

    return result;

  } catch (error) {
    console.error('🏢 创建企业失败:', error);
    throw error;
  }
}

/**
 * 格式化日期
 */
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;
  }
}