package com.erp.order.settlement.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.erp.order.settlement.entity.OrderSettlement;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

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

/**
 * 订单结算Repository
 */
@Mapper
public interface OrderSettlementRepository extends BaseMapper<OrderSettlement> {

    /**
     * 根据结算单号查询
     */
    @Select("SELECT * FROM order_settlement WHERE settlement_no = #{settlementNo} AND deleted_at IS NULL")
    OrderSettlement findBySettlementNo(@Param("settlementNo") String settlementNo);

    /**
     * 根据订单ID查询结算信息
     */
    @Select("SELECT * FROM order_settlement WHERE order_id = #{orderId} AND deleted_at IS NULL")
    OrderSettlement findByOrderId(@Param("orderId") Long orderId);

    /**
     * 根据店铺ID和结算状态查询
     */
    @Select("SELECT * FROM order_settlement WHERE shop_id = #{shopId} AND settlement_status = #{status} AND deleted_at IS NULL")
    List<OrderSettlement> findByShopIdAndStatus(@Param("shopId") Long shopId, @Param("status") String status);

    /**
     * 根据结算周期查询待结算订单
     */
    @Select("SELECT * FROM order_settlement WHERE settlement_period_id = #{periodId} AND settlement_status = #{status} AND deleted_at IS NULL")
    List<OrderSettlement> findByPeriodIdAndStatus(@Param("periodId") Long periodId, @Param("status") String status);

    /**
     * 根据平台和日期范围查询
     */
    @Select("SELECT * FROM order_settlement WHERE platform = #{platform} AND payment_time BETWEEN #{startTime} AND #{endTime} AND deleted_at IS NULL")
    List<OrderSettlement> findByPlatformAndDateRange(@Param("platform") String platform, @Param("startTime") LocalDateTime startTime, @Param("endTime") LocalDateTime endTime);

    /**
     * 批量更新结算状态
     */
    @Update("<script>" +
            "UPDATE order_settlement SET settlement_status = #{status}, updated_at = NOW() " +
            "WHERE id IN <foreach collection='ids' item='id' open='(' separator=',' close=')'>#{id}</foreach> " +
            "AND deleted_at IS NULL" +
            "</script>")
    int batchUpdateStatus(@Param("ids") List<Long> ids, @Param("status") String status);

    /**
     * 统计店铺待结算金额
     */
    @Select("SELECT COALESCE(SUM(settlement_amount), 0) FROM order_settlement WHERE shop_id = #{shopId} AND settlement_status = 'pending' AND deleted_at IS NULL")
    BigDecimal sumPendingSettlementByShop(@Param("shopId") Long shopId);

    /**
     * 统计平台待结算金额
     */
    @Select("SELECT COALESCE(SUM(settlement_amount), 0) FROM order_settlement WHERE platform = #{platform} AND settlement_status = 'pending' AND deleted_at IS NULL")
    BigDecimal sumPendingSettlementByPlatform(@Param("platform") String platform);
}
