<?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.ga.core.mapper.settle.ChargebackMapper">

    <resultMap id="CBMap" type="com.ga.core.vo.settle.ChargebackVO"/>

    <insert id="insert" parameterType="com.ga.core.vo.settle.ChargebackVO" useGeneratedKeys="true" keyProperty="cbId">
        INSERT INTO chargeback (contract_id, agent_id, policy_no, lapse_month, cb_rate,
                                cb_amount, paid_amount, remain_amount, settle_month,
                                installment_no, max_installments, status, created_at)
        VALUES (#{contractId}, #{agentId}, #{policyNo}, #{lapseMonth}, #{cbRate},
                #{cbAmount}, COALESCE(#{paidAmount}, 0), #{remainAmount}, #{settleMonth},
                #{installmentNo}, #{maxInstallments}, COALESCE(#{status},'NEW'), NOW())
    </insert>

    <insert id="insertBatch">
        INSERT INTO chargeback (contract_id, agent_id, policy_no, lapse_month, cb_rate,
                                cb_amount, remain_amount, settle_month, status, created_at)
        VALUES
        <foreach collection="list" item="r" separator=",">
            (#{r.contractId}, #{r.agentId}, #{r.policyNo}, #{r.lapseMonth}, #{r.cbRate},
             #{r.cbAmount}, #{r.remainAmount}, #{r.settleMonth}, COALESCE(#{r.status},'NEW'), NOW())
        </foreach>
    </insert>

    <select id="selectByAgent" resultMap="CBMap">
        SELECT * FROM chargeback
        WHERE agent_id = #{agentId}
        <if test="settleMonth != null and settleMonth != ''">AND settle_month = #{settleMonth}</if>
        ORDER BY created_at DESC
    </select>

    <update id="updatePaid">
        UPDATE chargeback SET
            paid_amount = paid_amount + #{paidAmount},
            remain_amount = cb_amount - (paid_amount + #{paidAmount}),
            status = #{status}
        WHERE cb_id = #{cbId}
    </update>

    <select id="aggregateByAgent" resultType="map">
        SELECT agent_id AS "agentId", SUM(cb_amount) AS "total"
        FROM chargeback WHERE settle_month = #{settleMonth} GROUP BY agent_id
    </select>

    <select id="sumByMonth" resultType="java.math.BigDecimal">
        SELECT COALESCE(SUM(cb_amount), 0) FROM chargeback WHERE settle_month = #{settleMonth}
    </select>

</mapper>
