package com.erp.finance.controller;

import com.erp.finance.dto.*;
import com.erp.finance.service.FinanceReportService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import com.erp.common.core.model.ApiResponse;

/**
 * 财务报表API
 */
@Slf4j
@RestController
@RequestMapping("/api/finance/reports")
@RequiredArgsConstructor
public class ReportController {

    private final FinanceReportService reportService;

    /**
     * 获取财务概况（收支统计）
     */
    @GetMapping("/summary")
    public FinanceApiResponse<FinanceReportResponse> getSummary(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        try {
            FinanceReportResponse report = reportService.getFinanceSummary(startDate, endDate);
            return FinanceApiResponse.success(report);
        } catch (Exception e) {
            log.error("[API] 获取财务概况失败 startDate={}, endDate={}", startDate, endDate, e);
            return FinanceApiResponse.error(500, "获取财务概况失败: " + e.getMessage());
        }
    }

    /**
     * 获取收支报表
     */
    @GetMapping("/income-expense")
    public FinanceApiResponse<FinanceReportResponse> getIncomeExpenseReport(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        try {
            FinanceReportResponse report = reportService.getIncomeExpenseReport(startDate, endDate);
            return FinanceApiResponse.success(report);
        } catch (Exception e) {
            log.error("[API] 获取收支报表失败", e);
            return FinanceApiResponse.error(500, e.getMessage());
        }
    }

    /**
     * 获取采购付款报表
     */
    @GetMapping("/purchase-payment")
    public FinanceApiResponse<FinanceReportResponse> getPurchasePaymentReport(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        try {
            FinanceReportResponse report = reportService.getPurchasePaymentReport(startDate, endDate);
            return FinanceApiResponse.success(report);
        } catch (Exception e) {
            log.error("[API] 获取采购付款报表失败", e);
            return FinanceApiResponse.error(500, e.getMessage());
        }
    }

    /**
     * 今日统计概览
     */
    @GetMapping("/today")
    public FinanceApiResponse<FinanceReportResponse> getTodaySummary() {
        LocalDate today = LocalDate.now();
        return getSummary(today, today);
    }
}
