<?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.ai.da.mapper.primary.ReferralMapper">

    <!-- resources/mapper/ReferralMapper.xml -->
    <select id="selectReferralWithAffiliate" resultType="com.ai.da.model.vo.ReferralPageQueryVO">
        SELECT
        r.*,
        ac.user_name AS affiliateName
        FROM
        t_referral r
        LEFT JOIN
        t_account ac ON r.affiliate_account_id = ac.id
        ${ew.customSqlSegment} <!-- 动态条件 -->
    </select>

    <!-- Mapper.xml -->
    <update id="batchDeleteByIds">
        UPDATE t_referral
        SET is_deleted = 1
        WHERE id IN
        <foreach collection="ids" item="id" open="(" separator="," close=")">
            #{id}
        </foreach>
    </update>

    <!-- Mapper.xml -->
    <select id="sumAmount" resultType="java.math.BigDecimal">
        SELECT SUM(commission)
        FROM t_referral
        WHERE affiliate_id = #{affiliateId}
        <if test="statusList != null and statusList.size() > 0">
            AND status IN
            <foreach collection="statusList" item="status" open="(" separator="," close=")">
                #{status}
            </foreach>
        </if>
        <if test="startTime != null">
            AND create_time >= #{startTime}
        </if>
        <if test="endTime != null">
            AND create_time <![CDATA[<=]]> #{endTime}
        </if>
    </select>

    <select id="getPersonalMonthlyIncome" resultType="java.util.Map">
        SELECT
        DATE_FORMAT(create_time, '%m') as yearMonth,
        SUM(commission) AS totalCommission
        FROM
        t_referral
        WHERE
        YEAR(create_time) = #{year}
        and affiliate_account_id = #{affiliateAccountId}
        and is_deleted = 0
        and status in ("Paid", "Unpaid")
        GROUP BY
        yearMonth
        ORDER BY
        yearMonth
    </select>

    <select id="getMonthlyAffiliateIncome" resultType="java.util.Map">
        SELECT
        DATE_FORMAT(create_time, '%m') as yearMonth,
        SUM(amount) AS totalAmount,
        SUM(CASE WHEN status = 'Paid' THEN commission ELSE 0 END) AS paidCommission,
        SUM(CASE WHEN status = 'Unpaid' THEN commission ELSE 0 END) AS unpaidCommission
        FROM
        t_referral
        WHERE
        YEAR(create_time) = #{year}
        AND MONTH(create_time) = #{month}
        AND is_deleted = 0
        AND status IN ('Paid', 'Unpaid')
        GROUP BY
        yearMonth
        ORDER BY
        yearMonth
    </select>
</mapper>