<?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.StatCopyTradePositionMapper">

    <!--
        聚合带单者的活跃仓位（含普通/无损跟单分类）。
        带单者持仓量与跟单者持仓量分开子查询聚合，避免 LEFT JOIN 扇出导致带单者字段被重复累加。

        带单者识别：copytrade.customer.trader = 20
        普通跟单：is_special IS NULL OR is_special != 1
        无损跟单：is_special = 1
        活跃仓位：status != 2（2 = DONE）
    -->
    <select id="computeSnapshot" resultType="com.datacenter.entity.stat.StatCopyTradePosition">
        SELECT
            #{statTime}                                AS stat_time,
            tr.member_id                               AS trader_member_id,
            COALESCE(tl.name, '')                      AS trader_level,
            tr.symbol                                  AS symbol,
            tr.direction                               AS direction,
            tr.leverage_rate,
            tr.money_type,
            tr.share_number,
            tr.trader_qty,
            tr.trader_avg_open,
            tr.trader_total_principal,
            COALESCE(fn.normal_follow_count,    0)     AS normal_follow_count,
            COALESCE(fn.normal_follow_qty,      0)     AS normal_follow_qty,
            COALESCE(fn.normal_follow_avg_open, 0)     AS normal_follow_avg_open,
            COALESCE(fs.special_follow_count,   0)     AS special_follow_count,
            COALESCE(fs.special_follow_qty,     0)     AS special_follow_qty,
            COALESCE(fs.special_follow_avg_open,0)     AS special_follow_avg_open
        FROM (
            <!-- 带单者自身持仓单独聚合，不受跟单者 JOIN 影响 -->
            SELECT
                tp.member_id,
                cc.symbol,
                tp.direction,
                MAX(tp.leverage)     AS leverage_rate,
                MAX(tp.money_type)   AS money_type,
                MAX(tp.share_number) AS share_number,
                SUM(tp.total_position - COALESCE(tp.closed_position, 0))         AS trader_qty,
                SUM(tp.open_price * (tp.total_position - COALESCE(tp.closed_position, 0))) /
                    NULLIF(SUM(tp.total_position - COALESCE(tp.closed_position, 0)), 0)  AS trader_avg_open,
                COALESCE(SUM(tp.total_principal_amount), 0)                       AS trader_total_principal
            FROM member_contract_position tp
            JOIN contract_coin cc ON cc.id = tp.contract_id
            WHERE tp.status != 2
              AND tp.follow_position_id IS NULL
              AND tp.member_id IN (SELECT member_id FROM copytrade.customer WHERE trader = 20)
            GROUP BY tp.member_id, cc.symbol, tp.direction
        ) tr
        LEFT JOIN copytrade.customer cu     ON cu.member_id = tr.member_id
        LEFT JOIN copytrade.trader_level tl ON tl.id = cu.trader_level_id
        LEFT JOIN (
            <!-- 普通跟单持仓聚合（按带单仓位反查带单者） -->
            SELECT
                leader.member_id AS trader_member_id,
                cc2.symbol,
                leader.direction,
                COUNT(DISTINCT fp.id)                                                       AS normal_follow_count,
                COALESCE(SUM(fp.total_position - COALESCE(fp.closed_position, 0)), 0)       AS normal_follow_qty,
                CASE WHEN COALESCE(SUM(fp.total_position - COALESCE(fp.closed_position, 0)), 0) > 0
                     THEN SUM(fp.open_price * (fp.total_position - COALESCE(fp.closed_position, 0))) /
                          SUM(fp.total_position - COALESCE(fp.closed_position, 0))
                     ELSE 0 END                                                             AS normal_follow_avg_open
            FROM member_contract_position fp
            JOIN member_contract_position leader ON leader.id = fp.follow_position_id
            JOIN contract_coin cc2 ON cc2.id = leader.contract_id
            WHERE fp.status    != 2
              AND (fp.is_special IS NULL OR fp.is_special != 1)
              AND leader.status != 2
              AND leader.follow_position_id IS NULL
              AND leader.member_id IN (SELECT member_id FROM copytrade.customer WHERE trader = 20)
            GROUP BY leader.member_id, cc2.symbol, leader.direction
        ) fn ON fn.trader_member_id = tr.member_id AND fn.symbol = tr.symbol AND fn.direction = tr.direction
        LEFT JOIN (
            <!-- 无损跟单持仓聚合 -->
            SELECT
                leader.member_id AS trader_member_id,
                cc2.symbol,
                leader.direction,
                COUNT(DISTINCT fp.id)                                                        AS special_follow_count,
                COALESCE(SUM(fp.total_position - COALESCE(fp.closed_position, 0)), 0)        AS special_follow_qty,
                CASE WHEN COALESCE(SUM(fp.total_position - COALESCE(fp.closed_position, 0)), 0) > 0
                     THEN SUM(fp.open_price * (fp.total_position - COALESCE(fp.closed_position, 0))) /
                          SUM(fp.total_position - COALESCE(fp.closed_position, 0))
                     ELSE 0 END                                                              AS special_follow_avg_open
            FROM member_contract_position fp
            JOIN member_contract_position leader ON leader.id = fp.follow_position_id
            JOIN contract_coin cc2 ON cc2.id = leader.contract_id
            WHERE fp.status    != 2
              AND fp.is_special = 1
              AND leader.status != 2
              AND leader.follow_position_id IS NULL
              AND leader.member_id IN (SELECT member_id FROM copytrade.customer WHERE trader = 20)
            GROUP BY leader.member_id, cc2.symbol, leader.direction
        ) fs ON fs.trader_member_id = tr.member_id AND fs.symbol = tr.symbol AND fs.direction = tr.direction
    </select>

</mapper>
