package com.erp.aftersale.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.erp.aftersale.entity.AfterSale;
import com.erp.aftersale.entity.AfterSaleItem;
import com.erp.aftersale.entity.AfterSaleOperationLog;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import java.util.Map;

@Mapper
public interface AfterSaleMapper extends BaseMapper<AfterSale> {

    @Select("SELECT * FROM after_sales WHERE id = #{id} AND deleted = 0")
    AfterSale selectById(@Param("id") Long id);

    @Select("SELECT * FROM after_sales WHERE short_id = #{shortId} AND deleted = 0")
    AfterSale selectByShortId(@Param("shortId") String shortId);

    @Select("SELECT * FROM after_sale_items WHERE after_sale_id = #{afterSaleId} AND deleted = 0")
    List<AfterSaleItem> selectItemsByAfterSaleId(@Param("afterSaleId") Long afterSaleId);

    @Select("SELECT * FROM after_sale_logs WHERE after_sale_id = #{afterSaleId} AND deleted = 0 ORDER BY created_at DESC")
    List<AfterSaleOperationLog> selectLogsByAfterSaleId(@Param("afterSaleId") Long afterSaleId);

    @Select("SELECT COUNT(*) FROM after_sales WHERE deleted = 0 AND status = #{status}")
    Long countByStatus(@Param("status") String status);

    @Select("SELECT COALESCE(SUM(actual_refund), 0) FROM after_sales WHERE deleted = 0 AND actual_refund IS NOT NULL")
    java.math.BigDecimal sumActualRefund();

    @Select("SELECT COALESCE(SUM(apply_amount), 0) FROM after_sales WHERE deleted = 0")
    java.math.BigDecimal sumApplyAmount();

    @Select("SELECT type, COUNT(*) as count FROM after_sales WHERE deleted = 0 GROUP BY type")
    List<Map<String, Object>> countGroupByType();

    @Select("SELECT status, COUNT(*) as count FROM after_sales WHERE deleted = 0 GROUP BY status")
    List<Map<String, Object>> countGroupByStatus();
}
