package com.erp.finance.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.finance.entity.AccountsPayable;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;

@Mapper
public interface AccountsPayableRepository extends BaseMapper<AccountsPayable> {

    IPage<AccountsPayable> selectPageList(Page<AccountsPayable> page,
                                          @Param("apNo") String apNo,
                                          @Param("purchaseOrderNo") String purchaseOrderNo,
                                          @Param("supplierId") Long supplierId,
                                          @Param("status") String status,
                                          @Param("startDate") LocalDateTime startDate,
                                          @Param("endDate") LocalDateTime endDate);

    AccountsPayable findByApNo(@Param("apNo") String apNo);

    AccountsPayable findByPurchaseOrderNo(@Param("purchaseOrderNo") String purchaseOrderNo);

    AccountsPayable findByPurchaseOrderId(@Param("purchaseOrderId") Long purchaseOrderId);

    @Select("SELECT SUM(unpaid_amount) FROM fin_accounts_payable WHERE status IN ('pending','partial','overdue')")
    BigDecimal sumTotalUnpaid();

    @Select("SELECT SUM(unpaid_amount) FROM fin_accounts_payable WHERE status IN ('pending','partial','overdue') AND due_date < #{date}")
    BigDecimal sumOverdueAmount(@Param("date") LocalDate date);

    @Select("SELECT SUM(paid_amount) FROM fin_accounts_payable WHERE paid_date >= #{startDate} AND paid_date <= #{endDate}")
    BigDecimal sumPaidAmount(@Param("startDate") LocalDate startDate, @Param("endDate") LocalDate endDate);
}
