/**
 * filekorolheader: 企业信息API接口 - 企业详细信息获取和更新接口服务
 * 功能：API请求封装、数据转换、错误处理、企业信息管理
 * 路径：/central-config/tenant/enterprise-info/components/enterpriseInfoApi
 * 规范：遵循crop-x/docs/开发项目规范.md，使用SDK API调用，TypeScript类型安全
 */

import { getAuthToken } from "@/utils/token";
import { getCurrentTenantApiV1TenantsMeGet, submitTenantAuditApiV1TenantsSubmitPost } from "@/lib/api/sdk.gen";
import { Enterprise } from '../types';

// API返回的租户数据类型（根据实际API返回定义）
export interface TenantApiData {
  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;
}

// 提交审核请求参数接口
export interface SubmitAuditRequest {
  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;
  bank_permit_image: string | null;
  social_credit_code: string | null;
  business_license_image: string | null;
  legal_person_name: string | null;
  id_card_front_image: string | null;
  id_card_back_image: string | null;
  company_scale: string | null;
  registered_capital: number | null;
  established_date: string | null;
  invoice_type: string | null;
  business_scope: string | null;
}

/**
 * 获取企业详细信息
 */
export async function fetchEnterpriseInfo(tenantId: string): Promise<Enterprise | null> {
  try {
    const token = getAuthToken();
    console.log('🏢 获取企业信息API调用，租户ID:', tenantId);

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

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

    const data = response.data as TenantApiData;
    console.log('🏢 获取企业信息API响应:', data);

    return transformTenantData(data);
  } catch (error) {
    console.error('🏢 获取企业信息失败:', error);
    throw error;
  }
}

/**
 * 更新企业信息
 * 注意：此功能待开发，当前不做任何操作
 */
export async function updateEnterpriseInfo(tenantId: string, formData: Partial<Enterprise>): Promise<Enterprise | null> {
  console.log('🏢 更新企业信息功能待开发，租户ID:', tenantId, '数据:', formData);

  // 暂时返回null，等待更新API接口开发完成
  return null;
}

/**
 * 提交企业审核
 * @param tenantId 租户ID
 * @param data 提交审核的数据
 * @returns 提交结果
 */
export async function submitEnterpriseAudit(tenantId: string, data: SubmitAuditRequest): Promise<void> {
  try {
    const token = getAuthToken();
    console.log('🏢 提交企业审核API调用，租户ID:', tenantId, '数据:', data);

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

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

    console.log('🏢 提交企业审核API成功');
  } catch (error) {
    console.error('🏢 提交企业审核失败:', error);
    throw error;
  }
}

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

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

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