package com.yn.bftl.thirdparty.common.repository;

import com.yn.bftl.common.modules.order.entity.Refund;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 退款单Repository
 *
 * @author
 * @create 2024/3/2  15:23
 **/
@Repository
public interface RefundRepository extends JpaRepository<Refund, Long>, JpaSpecificationExecutor<Refund> {

    /**
     * 退款单-根据银联单号判断是否存在
     *
     * @param unionpayRefundSn:银联退款单号
     * @return true:存在、false:未存在
     * @author huabiao
     * @create 2022/9/5  14:14
     */
    Boolean existsByUnionpayRefundSn(String unionpayRefundSn);

    /**
     * 退款单-根据订单ID获取
     *
     * @param orderId 订单ID
     * @return 退款单列表
     * @author huabiao
     * @create 2023/4/3  21:22
     */
    List<Refund> findAllByOrdersId(Long orderId);

    /**
     * 退款单-根据退款单号查询
     *
     * @param refundSn 退款单号
     * @return 退款单
     * @author huabiao
     * @create 2023/5/4  18:15
     */
    Refund findFirstByRefundSn(String refundSn);

    /**
     * 退款-计算企业退款金额
     *
     * @param companyId 企业ID
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return 退款金额
     * @author huabiao
     * @create 2024/3/2  15:31
     */
    @Query(value = "SELECT COALESCE(SUM(refund.amount),0) FROM Refund refund WHERE refund.orders.buyerCompany.id = ?1 AND refund.refundTime BETWEEN ?2 AND ?3 ")
    BigDecimal computeCompanyRefundAmount(Long companyId, LocalDateTime startTime, LocalDateTime endTime);
}
