<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.erp.tenant.repository.finance.FinanceRecordRepository">

    <!-- 财务记录分页 -->
    <select id="findPage" resultType="com.erp.tenant.entity.finance.FinanceRecord">
        SELECT fr.* FROM finance_records fr
        WHERE fr.tenant_id = #{tenantId} AND fr.deleted_at IS NULL
        <if test="type != null and type != ''">
            AND fr.type = #{type}
        </if>
        <if test="status != null">
            AND fr.status = #{status}
        </if>
        <if test="startDate != null and startDate != ''">
            AND fr.payment_time &gt;= #{startDate}
        </if>
        <if test="endDate != null and endDate != ''">
            AND fr.payment_time &lt;= #{endDate}
        </if>
        ORDER BY fr.created_at DESC
    </select>

    <!-- 按类型统计金额 -->
    <select id="sumAmountByType" resultType="java.math.BigDecimal">
        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 startDate != ''">
            AND payment_time &gt;= #{startDate}
        </if>
        <if test="endDate != null and endDate != ''">
            AND payment_time &lt;= #{endDate}
        </if>
    </select>

    <!-- 更新记录状态 -->
    <update id="updateStatus">
        UPDATE finance_records 
        SET status = #{status}, confirmed_at = NOW(), 
            confirmed_by = #{confirmedBy}, remark = #{remark}
        WHERE id = #{id} AND tenant_id = #{tenantId}
    </update>

</mapper>
