<?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.datacenter.mapper.FollowerCleanupMapper">

    <resultMap id="candidateMap" type="com.datacenter.job.vo.FollowerCleanupCandidateVo">
        <result column="followId"    property="followId"/>
        <result column="customerId"  property="customerId"/>
        <result column="traderId"    property="traderId"/>
    </resultMap>

    <!--
        查询需要被移除的跟单员：
          - follow.status = 10（跟随中）
          - 跟单员账户余额 < 交易员配置的最小跟单金额（min_follow_amount，余额取 follow_wallet.balance）
          - 跟单员在该交易员下无未平仓/部分平仓仓位（position.status IN (10, 20)）
          - 交易员身份确认：customer.trader = 30
    -->
    <select id="findCandidates" resultMap="candidateMap">
        SELECT
            f.id          AS followId,
            f.customer_id AS customerId,
            f.trader_id   AS traderId
        FROM follow f
        INNER JOIN customer fc
            ON fc.id = f.customer_id
        INNER JOIN kucoin.follow_wallet fw
            ON fw.id = fc.member_id
        INNER JOIN customer tc
            ON tc.id = f.trader_id
            AND tc.trader = 20
        WHERE f.status = 10
          AND fw.balance &lt; tc.min_follow_amount
          AND NOT EXISTS (
              SELECT 1
              FROM position p
              WHERE p.customer_id = f.customer_id
                AND p.trader_id   = f.trader_id
                AND p.status      IN (10, 20)
          )
    </select>

</mapper>
