<?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="cn.cordys.crm.opportunity.mapper.ExtOpportunityStageConfigMapper">

    <select id="getStageConfigList" resultType="cn.cordys.crm.opportunity.dto.response.StageConfigResponse">
        select id, name, type, rate, afoot_roll_back, end_roll_back, pos
        from opportunity_stage_config
        where organization_id = #{orgId}
        order by pos asc
    </select>


    <select id="countStageConfig" resultType="java.lang.Integer">
        select count(id)
        from opportunity_stage_config
        where organization_id = #{orgId}
    </select>

    <update id="moveUpStageConfig">
        update opportunity_stage_config
        set pos = pos + #{pos}
        where pos &gt;= #{start}
          and organization_id = #{orgId}
    </update>

    <update id="moveDownStageConfig">
        update opportunity_stage_config
        set pos = pos + #{pos}
        where pos &gt; #{start}
          and organization_id = #{orgId}
    </update>

    <update id="updateRollBack">
        UPDATE opportunity_stage_config
        <set>
            <if test="request.afootRollBack != null">
                afoot_roll_back =#{request.afootRollBack},
            </if>
            <if test="request.endRollBack != null">
                end_roll_back = #{request.endRollBack},
            </if>
        </set>
        WHERE organization_id = #{orgId}
    </update>


    <update id="updateStageConfig">
        update opportunity_stage_config
        set name        = #{request.name},
            rate        = #{request.rate},
            update_user = #{userId},
            update_time = unix_timestamp() * 1000
        where id = #{request.id}
    </update>

    <select id="getAllStageConfigList" resultType="cn.cordys.crm.opportunity.domain.OpportunityStageConfig">
        select id, name, organization_id, type, rate from opportunity_stage_config
    </select>


    <update id="moveUp">
        update opportunity_stage_config set pos = pos - 1 where pos &gt; #{start} and pos &lt;= #{end}
    </update>

    <update id="moveDown">
        update opportunity_stage_config set pos = pos + 1 where pos &gt;= #{start} and pos &lt; #{end}
    </update>


    <update id="updatePos">
        update opportunity_stage_config set pos = #{pos} where id = #{id}
    </update>

    <select id="countByType" resultType="java.lang.Integer">
        select count(id)
        from opportunity_stage_config
        where type = #{type} and organization_id = #{orgId}
    </select>
</mapper>