/**
 * 数据完整性校验工具
 * 确保财务与核心数据100%正确
 */

import { http } from '../api';

// ============================================================================
// 类型定义
// ============================================================================

export interface ValidationResult {
  isValid: boolean;
  errors: string[];
  warnings: string[];
}

export interface DataIntegrityReport {
  timestamp: string;
  checks: {
    planQuantity: CheckResult;
    paymentAmount: CheckResult;
    accountsPayable: CheckResult;
  };
  overallStatus: 'PASS' | 'FAIL';
  errorRate: number; // 万分比
}

interface CheckResult {
  totalRecords: number;
  inconsistentRecords: number;
  errorRate: number;
  status: 'PASS' | 'FAIL';
  details?: any[];
}

// ============================================================================
// 前端校验函数（写入前预检）
// ============================================================================

/**
 * 校验入库记录
 */
export function validateInventoryRecord(record: {
  quantity: number;
  rolls: number;
  price_per_meter?: number;
}): ValidationResult {
  const errors: string[] = [];
  const warnings: string[] = [];

  if (record.quantity < 0) {
    errors.push('入库数量不能为负数');
  }
  if (record.quantity === 0) {
    warnings.push('入库数量为0，请确认是否正确');
  }
  if (record.rolls < 0) {
    errors.push('入库匹数不能为负数');
  }
  if (record.price_per_meter !== undefined && record.price_per_meter < 0) {
    errors.push('单价不能为负数');
  }
  if (record.price_per_meter !== undefined && record.price_per_meter > 1000) {
    warnings.push(`单价 ${record.price_per_meter} 元/米异常偏高，请确认`);
  }

  return {
    isValid: errors.length === 0,
    errors,
    warnings,
  };
}

/**
 * 校验付款记录
 */
export function validatePayment(payment: {
  amount: number;
  quantity: number;
  price_per_meter: number;
}): ValidationResult {
  const errors: string[] = [];
  const warnings: string[] = [];
  const tolerance = 0.01;

  if (payment.amount < 0) {
    errors.push('付款金额不能为负数');
  }
  if (payment.quantity < 0) {
    errors.push('付款数量不能为负数');
  }
  if (payment.price_per_meter < 0) {
    errors.push('单价不能为负数');
  }

  // 验证金额一致性
  const expectedAmount = payment.quantity * payment.price_per_meter;
  const difference = Math.abs(payment.amount - expectedAmount);
  
  if (difference > tolerance) {
    errors.push(
      `付款金额不一致：期望 ${expectedAmount.toFixed(2)} 元 (数量 ${payment.quantity} × 单价 ${payment.price_per_meter})，实际 ${payment.amount.toFixed(2)} 元，差异 ${difference.toFixed(2)} 元`
    );
  }

  return {
    isValid: errors.length === 0,
    errors,
    warnings,
  };
}

/**
 * 校验计划完成数量
 */
export function validatePlanCompletion(plan: {
  target_quantity: number;
  completed_quantity: number;
}): ValidationResult {
  const errors: string[] = [];
  const warnings: string[] = [];

  if (plan.completed_quantity < 0) {
    errors.push('完成数量不能为负数');
  }
  if (plan.completed_quantity > plan.target_quantity * 1.1) {
    warnings.push(
      `完成数量 (${plan.completed_quantity}) 超过目标数量 (${plan.target_quantity}) 的10%，请确认`
    );
  }

  return {
    isValid: errors.length === 0,
    errors,
    warnings,
  };
}

// ============================================================================
// 数据库一致性检查（读取后验证）
// ============================================================================

/**
 * 检查计划数量一致性
 */
export async function checkPlanQuantityConsistency(planId: string): Promise<{
  isConsistent: boolean;
  completedQuantity: number;
  inventoryTotal: number;
  difference: number;
}> {
  const { data } = await http.get<any>(`/textile/plans/${planId}/consistency`);

  if (!data) {
    throw new Error(`查询计划一致性失败`);
  }

  return {
    isConsistent: data.is_consistent ?? Math.abs(data.difference) <= 0.01,
    completedQuantity: data.completed_quantity ?? 0,
    inventoryTotal: data.inventory_total ?? 0,
    difference: data.difference ?? 0,
  };
}

/**
 * 运行完整的数据完整性检查
 */
export async function runFullDataIntegrityCheck(): Promise<DataIntegrityReport> {
  const report: DataIntegrityReport = {
    timestamp: new Date().toISOString(),
    checks: {
      planQuantity: { totalRecords: 0, inconsistentRecords: 0, errorRate: 0, status: 'PASS' },
      paymentAmount: { totalRecords: 0, inconsistentRecords: 0, errorRate: 0, status: 'PASS' },
      accountsPayable: { totalRecords: 0, inconsistentRecords: 0, errorRate: 0, status: 'PASS' },
    },
    overallStatus: 'PASS',
    errorRate: 0,
  };

  try {
    const { data } = await http.post<any[]>('/common/data-integrity-check');

    if (data && Array.isArray(data)) {
      for (const check of data) {
        switch (check.check_type) {
          case 'plan_quantity': {
            const pqTotal = check.total_records ?? 0;
            const pqInconsistent = check.inconsistent_records ?? 0;
            report.checks.planQuantity = {
              totalRecords: pqTotal,
              inconsistentRecords: pqInconsistent,
              errorRate: pqTotal > 0 ? (Number(check.error_rate) || 0) : 0,
              status: pqTotal === 0 ? 'PASS' : (pqInconsistent > 0 ? 'FAIL' : 'PASS'),
            };
            break;
          }
          case 'payment_amount': {
            const paTotal = check.total_records ?? 0;
            const paInconsistent = check.inconsistent_records ?? 0;
            report.checks.paymentAmount = {
              totalRecords: paTotal,
              inconsistentRecords: paInconsistent,
              errorRate: paTotal > 0 ? (Number(check.error_rate) || 0) : 0,
              status: paTotal === 0 ? 'PASS' : (paInconsistent > 0 ? 'FAIL' : 'PASS'),
            };
            break;
          }
          case 'accounts_payable': {
            const apTotal = check.total_records ?? 0;
            const apInconsistent = check.inconsistent_records ?? 0;
            report.checks.accountsPayable = {
              totalRecords: apTotal,
              inconsistentRecords: apInconsistent,
              errorRate: apTotal > 0 ? (Number(check.error_rate) || 0) : 0,
              status: apTotal === 0 ? 'PASS' : (apInconsistent > 0 ? 'FAIL' : 'PASS'),
            };
            break;
          }
        }
      }
    }

    // 计算总体错误率
    const totalRecords = 
      report.checks.planQuantity.totalRecords +
      report.checks.paymentAmount.totalRecords +
      report.checks.accountsPayable.totalRecords;
    
    const totalInconsistent = 
      report.checks.planQuantity.inconsistentRecords +
      report.checks.paymentAmount.inconsistentRecords +
      report.checks.accountsPayable.inconsistentRecords;

    report.errorRate = totalRecords > 0 
      ? (totalInconsistent / totalRecords) * 10000 
      : 0;

    report.overallStatus = report.errorRate <= 1 ? 'PASS' : 'FAIL';

  } catch (err) {
    report.overallStatus = 'FAIL';
  }

  return report;
}

// ============================================================================
// 审计日志查询
// ============================================================================

/**
 * 获取最近的审计日志
 */
export async function getRecentAuditLogs(limit: number = 100) {
  const { data } = await http.get<any[]>('/common/audit-logs', { limit });
  return data;
}

export async function getFailedValidations(limit: number = 50) {
  const { data } = await http.get<any[]>('/common/audit-logs', { validation_passed: 'false', limit });
  return data;
}

export async function getErrorRateStats(days: number = 30) {
  const { data } = await http.get<any[]>('/common/error-rate-stats', { days });
  return data;
}

// ============================================================================
// 安全写入包装器
// ============================================================================

/**
 * 安全插入入库记录（带双重校验）
 */
export async function safeInsertInventoryRecord(record: {
  plan_id: string;
  warehouse_id: string;
  quantity: number;
  rolls: number;
  company_id: string;
  operator_id: string;
  price_per_meter?: number;
}) {
  const validation = validateInventoryRecord(record);
  if (!validation.isValid) {
    throw new Error(`数据校验失败: ${validation.errors.join(', ')}`);
  }

  const { data } = await http.post<any>(`/textile/plans/${record.plan_id}/inventory`, record);

  if (!data) {
    throw new Error('写入失败');
  }

  const consistencyCheck = await checkPlanQuantityConsistency(record.plan_id);
  if (!consistencyCheck.isConsistent) {
  }

  return data;
}

/**
 * 安全插入付款记录（带双重校验）
 */
export async function safeInsertPayment(payment: {
  plan_id: string;
  from_company_id: string;
  to_company_id: string;
  amount: number;
  quantity: number;
  price_per_meter: number;
  status: 'pending' | 'completed';
}) {
  const validation = validatePayment(payment);
  if (!validation.isValid) {
    throw new Error(`数据校验失败: ${validation.errors.join(', ')}`);
  }

  const { data } = await http.post<any>('/textile/payments', payment);

  if (!data) {
    throw new Error('写入失败');
  }

  return data;
}
