package com.erp.finance.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.erp.finance.dto.*;
import com.erp.finance.entity.PaymentRecord;
import com.erp.finance.service.PaymentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import com.erp.common.core.model.ApiResponse;
import com.erp.common.core.model.PageResponse;

/**
 * 付款记录API
 */
@Slf4j
@RestController
@RequestMapping("/api/finance/payment")
@RequiredArgsConstructor
public class PaymentController {

    private final PaymentService paymentService;

    /**
     * 创建付款记录
     */
    @PostMapping("/create")
    public FinanceApiResponse<PaymentRecordResponse> create(@RequestBody PaymentService.PaymentCreateRequest request) {
        try {
            PaymentRecord record = paymentService.createPaymentRecord(request);
            return FinanceApiResponse.success(toResponse(record));
        } catch (Exception e) {
            log.error("[API] 创建付款记录失败", e);
            return FinanceApiResponse.error(500, e.getMessage());
        }
    }

    /**
     * 确认付款
     */
    @PutMapping("/{id}/confirm")
    public FinanceApiResponse<PaymentRecordResponse> confirmPayment(@PathVariable Long id,
                                                                      @RequestParam(required = false) String operator) {
        try {
            PaymentRecord record = paymentService.confirmPayment(id, operator);
            return FinanceApiResponse.success(toResponse(record));
        } catch (Exception e) {
            log.error("[API] 确认付款失败 id={}", id, e);
            return FinanceApiResponse.error(500, e.getMessage());
        }
    }

    /**
     * 取消付款
     */
    @PutMapping("/{id}/cancel")
    public FinanceApiResponse<?> cancelPayment(@PathVariable Long id,
                                               @RequestParam String reason,
                                               @RequestParam(required = false) String operator) {
        try {
            paymentService.cancelPayment(id, reason, operator);
            return FinanceApiResponse.success("取消成功");
        } catch (Exception e) {
            log.error("[API] 取消付款失败 id={}", id, e);
            return FinanceApiResponse.error(500, e.getMessage());
        }
    }

    /**
     * 分页查询付款记录
     */
    @GetMapping("/page")
    public FinanceApiResponse<PageResponse<PaymentRecordResponse>> queryPage(
            @RequestParam(required = false) String apNo,
            @RequestParam(required = false) String purchaseOrderNo,
            @RequestParam(required = false) Long supplierId,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String purpose,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") String startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") String endDate,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer pageSize) {
        PaymentQueryRequest request = new PaymentQueryRequest();
        request.setApNo(apNo);
        request.setPurchaseOrderNo(purchaseOrderNo);
        request.setSupplierId(supplierId);
        request.setStatus(status);
        request.setPurpose(purpose);
        request.setStartDate(startDate);
        request.setEndDate(endDate);
        request.setPage(page);
        request.setPageSize(pageSize);

        IPage<PaymentRecord> result = paymentService.query(request);
        return FinanceApiResponse.success(PageResponse.of(
                result.getTotal(),
                (int) result.getCurrent(),
                (int) result.getSize(),
                result.getRecords().stream().map(PaymentController::toResponse).toList()
        ));
    }

    /**
     * 根据ID查询
     */
    @GetMapping("/{id}")
    public FinanceApiResponse<PaymentRecordResponse> getById(@PathVariable Long id) {
        PaymentRecord record = paymentService.getById(id);
        if (record == null) {
            return FinanceApiResponse.notFound("付款记录不存在");
        }
        return FinanceApiResponse.success(toResponse(record));
    }

    /**
     * 根据付款单号查询
     */
    @GetMapping("/no/{paymentNo}")
    public FinanceApiResponse<PaymentRecordResponse> getByPaymentNo(@PathVariable String paymentNo) {
        PaymentRecord record = paymentService.getByPaymentNo(paymentNo);
        if (record == null) {
            return FinanceApiResponse.notFound("付款记录不存在");
        }
        return FinanceApiResponse.success(toResponse(record));
    }

    private static PaymentRecordResponse toResponse(PaymentRecord p) {
        return PaymentRecordResponse.builder()
                .id(p.getId())
                .paymentNo(p.getPaymentNo())
                .apNo(p.getApNo())
                .apId(p.getApId())
                .purchaseOrderNo(p.getPurchaseOrderNo())
                .supplierId(p.getSupplierId())
                .supplierName(p.getSupplierName())
                .amount(p.getAmount())
                .paymentMethod(p.getPaymentMethod())
                .fromAccount(p.getFromAccount())
                .toAccount(p.getToAccount())
                .paymentTime(p.getPaymentTime())
                .bankFlowNo(p.getBankFlowNo())
                .status(p.getStatus())
                .purpose(p.getPurpose())
                .relatedId(p.getRelatedId())
                .relatedType(p.getRelatedType())
                .operator(p.getOperator())
                .remark(p.getRemark())
                .createTime(p.getCreateTime())
                .build();
    }
}
