<?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.crm.manager.dao.mapper.SalesCommissionRecordMapper">

    <select id="countSearch" parameterType="com.crm.rely.backend.core.entity.sales.SalesCommissionRecordListEntity" resultType="Integer">
        select count(scr.id)
        from sales_commission_record scr
        inner join sales_commission_rule rule on scr.rule_id = rule.id
        inner join user_info leader on scr.sales_leader_id = leader.id
        <include refid="whereSql"></include>
    </select>

    <select id="listSearch" parameterType="com.crm.rely.backend.core.entity.sales.SalesCommissionRecordListEntity" resultType="com.crm.rely.backend.core.pojo.view.SalesCommissionRecordView">
        select scr.*,rule.rule_name,leader.ib_no sales_leader_no
        from sales_commission_record scr
        inner join sales_commission_rule rule on scr.rule_id = rule.id
        inner join user_info leader on scr.sales_leader_id = leader.id
        <include refid="whereSql"></include>
        order by scr.add_time desc
        <if test="page != null">
            limit #{page.offset},#{page.row}
        </if>
    </select>


    <update id="updateAmountBySalesIdAndYm" parameterType="com.crm.rely.backend.core.pojo.table.SalesCommissionRecordTable">
        update sales_commission_record
        <set>
            salary_amount = #{salaryAmount} + ifnull(salary_amount,0),
            personal_volume_amount = #{personalVolumeAmount} + ifnull(personal_volume_amount,0),
            team_volume_amount = #{teamVolumeAmount} + ifnull(team_volume_amount,0),
            kpi_amount = #{kpiAmount} + ifnull(kpi_amount,0)
        </set>
        where sales_id=#{salesId} and ym = #{ym}
    </update>


    <sql id="whereSql">
        <where>
            scr.ym = #{ym}
            <if test="salesNo != null and salesNo != ''">
                and scr.sales_no like concat('%',#{salesNo},'%')
            </if>
            <if test="salesType == 1">
                and scr.sales_id = #{salesId}
            </if>
            <if test="salesType == 2">
                and scr.sales_leader_id = #{salesId}
            </if>
            <if test="salesType == 0">
                and scr.sales_id_stamp like concat(#{salesIdStamp},'%')
            </if>
        </where>
    </sql>
</mapper>