package com.erp.finance.controller;

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

import java.time.LocalDate;
import java.time.LocalDateTime;
import com.erp.common.core.model.ApiResponse;
import com.erp.common.core.model.PageResponse;

/**
 * 收款记录API
 */
@Slf4j
@RestController
@RequestMapping("/api/finance/income")
@RequiredArgsConstructor
public class IncomeController {

    private final IncomeService incomeService;

    /**
     * 记录收款（订单支付/完成时调用）
     */
    @PostMapping("/record")
    public FinanceApiResponse<IncomeRecordResponse> recordIncome(@RequestBody FinanceApiResponse.IncomeRecordRequest request) {
        try {
            log.info("[API] 接收收款记录请求 orderNo={}, amount={}", request.getOrderNo(), request.getAmount());
            IncomeRecord record = incomeService.recordIncome(request);
            return FinanceApiResponse.success(toResponse(record));
        } catch (Exception e) {
            log.error("[API] 记录收款失败 orderNo={}", request.getOrderNo(), e);
            return FinanceApiResponse.error(500, "记录收款失败: " + e.getMessage());
        }
    }

    /**
     * 确认收款
     */
    @PutMapping("/{id}/confirm")
    public FinanceApiResponse<IncomeRecordResponse> confirmIncome(@PathVariable Long id,
                                                                   @RequestParam(required = false) String operator) {
        try {
            IncomeRecord record = incomeService.confirmIncome(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<?> cancelIncome(@PathVariable Long id,
                                              @RequestParam String reason,
                                              @RequestParam(required = false) String operator) {
        try {
            incomeService.cancelIncome(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<IncomeRecordResponse>> queryPage(
            @RequestParam(required = false) String orderNo,
            @RequestParam(required = false) String shortId,
            @RequestParam(required = false) String platform,
            @RequestParam(required = false) Long shopId,
            @RequestParam(required = false) String status,
            @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) {
        IncomeQueryRequest request = new IncomeQueryRequest();
        request.setOrderNo(orderNo);
        request.setShortId(shortId);
        request.setPlatform(platform);
        request.setShopId(shopId);
        request.setStatus(status);
        request.setStartDate(startDate);
        request.setEndDate(endDate);
        request.setPage(page);
        request.setPageSize(pageSize);

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

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

    /**
     * 根据收款单号查询
     */
    @GetMapping("/no/{incomeNo}")
    public FinanceApiResponse<IncomeRecordResponse> getByIncomeNo(@PathVariable String incomeNo) {
        IncomeRecord record = incomeService.getByIncomeNo(incomeNo);
        if (record == null) {
            return FinanceApiResponse.notFound("收款记录不存在");
        }
        return FinanceApiResponse.success(toResponse(record));
    }

    private static IncomeRecordResponse toResponse(IncomeRecord r) {
        return IncomeRecordResponse.builder()
                .id(r.getId())
                .incomeNo(r.getIncomeNo())
                .orderNo(r.getOrderNo())
                .shortId(r.getShortId())
                .platform(r.getPlatform())
                .shopId(r.getShopId())
                .shopName(r.getShopName())
                .amount(r.getAmount())
                .discountAmount(r.getDiscountAmount())
                .actualAmount(r.getActualAmount())
                .paymentMethod(r.getPaymentMethod())
                .paymentTime(r.getPaymentTime())
                .transactionId(r.getTransactionId())
                .accountNo(r.getAccountNo())
                .accountName(r.getAccountName())
                .status(r.getStatus())
                .source(r.getSource())
                .remark(r.getRemark())
                .createTime(r.getCreateTime())
                .build();
    }
}
