import { Request, Response } from 'express';
import { ReconciliationService } from '../../services/finance/reconciliationService';

export interface CreateReconciliationParams {
  tenantId: string;
  shopId: string;
  platform: string;
  periodStart: Date;
  periodEnd: Date;
  expectedAmount: number;
  actualAmount: number;
  traceId: string;
  taskId: string;
  businessType: 'TOC' | 'TOB';
}

export class ReconciliationController {
  /**
   * 创建对账记录
   */
  static async createReconciliation(req: Request, res: Response) {
    try {
      const { tenantId, shopId, traceId } = (req as any).traceContext;
      const { platform, periodStart, periodEnd, expectedAmount, actualAmount, businessType } = req.body;
      
      if (!platform || !periodStart || !periodEnd || expectedAmount === undefined || actualAmount === undefined || !businessType) {
        return res.status(400).json({ success: false, error: 'Missing required fields' });
      }
      
      const params: CreateReconciliationParams = {
        tenantId,
        shopId,
        platform,
        periodStart: new Date(periodStart),
        periodEnd: new Date(periodEnd),
        expectedAmount,
        actualAmount,
        traceId,
        taskId: `reconciliation_${Date.now()}`,
        businessType: businessType as 'TOC' | 'TOB'
      };
      
      const result = await ReconciliationService.createReconciliation(params);
      res.json({ success: true, data: result });
    } catch (error: any) {
      res.status(500).json({ success: false, error: error.message });
    }
  }

  /**
   * 获取对账记录列表
   */
  static async getReconciliations(req: Request, res: Response) {
    try {
      const { tenantId, shopId, traceId } = (req as any).traceContext;
      const { status, platform, startDate, endDate } = req.query;
      
      const reconciliations = await ReconciliationService.getReconciliations(
        tenantId,
        shopId,
        status as any,
        platform as string,
        startDate ? new Date(startDate as string) : undefined,
        endDate ? new Date(endDate as string) : undefined,
        traceId
      );
      
      res.json({ success: true, data: reconciliations });
    } catch (error: any) {
      res.status(500).json({ success: false, error: error.message });
    }
  }

  /**
   * 获取对账记录详情
   */
  static async getReconciliationById(req: Request, res: Response) {
    try {
      const { traceId } = (req as any).traceContext;
      const { id } = req.params;
      
      if (!id) {
        return res.status(400).json({ success: false, error: 'Missing reconciliation ID' });
      }
      
      const reconciliation = await ReconciliationService.getReconciliationById(id as string, traceId);
      if (!reconciliation) {
        return res.status(404).json({ success: false, error: 'Reconciliation not found' });
      }
      
      res.json({ success: true, data: reconciliation });
    } catch (error: any) {
      res.status(500).json({ success: false, error: error.message });
    }
  }

  /**
   * 处理异常对账
   */
  static async handleException(req: Request, res: Response) {
    try {
      const { traceId } = (req as any).traceContext;
      const { id } = req.params;
      const { action } = req.body;
      
      if (!id || !action) {
        return res.status(400).json({ success: false, error: 'Missing reconciliation ID or action' });
      }
      
      const result = await ReconciliationService.handleException(id as string, action, traceId);
      res.json({ success: true, data: result });
    } catch (error: any) {
      res.status(500).json({ success: false, error: error.message });
    }
  }

  /**
   * 批量对账
   */
  static async batchReconciliation(req: Request, res: Response) {
    try {
      const { tenantId, shopId, traceId } = (req as any).traceContext;
      const { platforms, periodStart, periodEnd } = req.body;
      
      if (!platforms || !Array.isArray(platforms) || !periodStart || !periodEnd) {
        return res.status(400).json({ success: false, error: 'Missing required fields' });
      }
      
      const results = await ReconciliationService.batchReconciliation(
        tenantId,
        shopId,
        platforms,
        new Date(periodStart),
        new Date(periodEnd),
        traceId
      );
      
      res.json({ success: true, data: results });
    } catch (error: any) {
      res.status(500).json({ success: false, error: error.message });
    }
  }

  /**
   * 获取对账汇总
   */
  static async getReconciliationSummary(req: Request, res: Response) {
    try {
      const { tenantId, shopId, traceId } = (req as any).traceContext;
      const { startDate, endDate } = req.query;
      
      if (!startDate || !endDate) {
        return res.status(400).json({ success: false, error: 'Missing startDate or endDate' });
      }
      
      const summary = await ReconciliationService.getReconciliationSummary(
        tenantId,
        shopId,
        new Date(startDate as string),
        new Date(endDate as string),
        traceId
      );
      
      res.json({ success: true, data: summary });
    } catch (error: any) {
      res.status(500).json({ success: false, error: error.message });
    }
  }

  /**
   * 自动对账任务
   */
  static async autoReconciliation(req: Request, res: Response) {
    try {
      const { tenantId, shopId, traceId } = (req as any).traceContext;
      const { platforms } = req.body;
      
      if (!platforms || !Array.isArray(platforms)) {
        return res.status(400).json({ success: false, error: 'Missing platforms' });
      }
      
      await ReconciliationService.autoReconciliationTask(tenantId, shopId, platforms, traceId);
      res.json({ success: true, message: 'Auto reconciliation task started' });
    } catch (error: any) {
      res.status(500).json({ success: false, error: error.message });
    }
  }

  /**
   * 导出对账报告
   */
  static async exportReconciliationReport(req: Request, res: Response) {
    try {
      const { tenantId, shopId, traceId } = (req as any).traceContext;
      const { startDate, endDate } = req.query;
      
      if (!startDate || !endDate) {
        return res.status(400).json({ success: false, error: 'Missing startDate or endDate' });
      }
      
      const report = await ReconciliationService.exportReconciliationReport(
        tenantId,
        shopId,
        new Date(startDate as string),
        new Date(endDate as string),
        traceId
      );
      
      res.setHeader('Content-Type', 'text/csv');
      res.setHeader('Content-Disposition', `attachment; filename=reconciliation_report_${new Date().toISOString().split('T')[0]}.csv`);
      res.send(report);
    } catch (error: any) {
      res.status(500).json({ success: false, error: error.message });
    }
  }

  /**
   * 初始化对账表
   */
  static async initReconciliationTable(req: Request, res: Response) {
    try {
      await ReconciliationService.initTable();
      res.json({ success: true, message: 'Reconciliation table initialized' });
    } catch (error: any) {
      res.status(500).json({ success: false, error: error.message });
    }
  }
}
