package com.erp.tenant.repository.finance;

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.tenant.entity.finance.FinanceRecord;
import org.apache.ibatis.annotations.*;

/**
 * 财务记录数据访问
 */
@Mapper
public interface FinanceRecordRepository extends BaseMapper<FinanceRecord> {

    @Select("SELECT * FROM finance_records WHERE id = #{id} AND tenant_id = #{tenantId} AND deleted_at IS NULL")
    FinanceRecord findById(@Param("id") Long id, @Param("tenantId") Long tenantId);

    @Select("<script>" +
            "SELECT fr.* FROM finance_records fr " +
            "WHERE fr.tenant_id = #{tenantId} AND fr.deleted_at IS NULL " +
            "<if test='type != null'> AND fr.type = #{type} </if>" +
            "<if test='status != null'> AND fr.status = #{status} </if>" +
            "<if test='startDate != null'> AND fr.payment_time &gt;= #{startDate} </if>" +
            "<if test='endDate != null'> AND fr.payment_time &lt;= #{endDate} </if>" +
            "ORDER BY fr.created_at DESC" +
            "</script>")
    IPage<FinanceRecord> findPage(Page<FinanceRecord> page,
                                   @Param("tenantId") Long tenantId,
                                   @Param("type") String type,
                                   @Param("status") Integer status,
                                   @Param("startDate") String startDate,
                                   @Param("endDate") String endDate);

    @Select("<script>" +
            "SELECT COALESCE(SUM(amount), 0) FROM finance_records " +
            "WHERE tenant_id = #{tenantId} AND type = #{type} AND status = 1 AND deleted_at IS NULL " +
            "<if test='startDate != null'> AND payment_time &gt;= #{startDate} </if>" +
            "<if test='endDate != null'> AND payment_time &lt;= #{endDate} </if>" +
            "</script>")
    java.math.BigDecimal sumAmountByType(@Param("tenantId") Long tenantId,
                                          @Param("type") String type,
                                          @Param("startDate") String startDate,
                                          @Param("endDate") String endDate);

    @Update("UPDATE finance_records SET status = #{status}, confirmed_at = NOW(), " +
            "confirmed_by = #{confirmedBy}, remark = #{remark} " +
            "WHERE id = #{id} AND tenant_id = #{tenantId}")
    int updateStatus(@Param("id") Long id,
                     @Param("tenantId") Long tenantId,
                     @Param("status") Integer status,
                     @Param("confirmedBy") Long confirmedBy,
                     @Param("remark") String remark);
}
