package com.datacenter.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.datacenter.entity.stat.StatContractPnl;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 合约盈亏统计 Mapper。
 *
 * follow 参数含义：
 *   0 = 自主合约（follow_position_id IS NULL / follow_id IS NULL）
 *   1 = 跟单合约（follow_position_id IS NOT NULL / follow_id IS NOT NULL）
 *
 * ii = includeInternal：
 *   0 = 排除 member.is_internal=1 的内部账户
 *   1 = 全部账户
 */
@Mapper
public interface StatContractPnlMapper extends BaseMapper<StatContractPnl> {

    // ── 当前持仓原始数据（用于 Java 侧结合实时价格计算浮盈亏） ──────────────────

    /**
     * 返回所有 USDT 本位开仓的持仓行，每行包含 symbol、direction、open_price、avail_qty、share_number。
     * 由 Service 结合实时价格在 Java 层计算浮盈/浮亏，避免 SQL 依赖 current_price（开仓时写入后不更新）。
     */
    @Select("SELECT p.member_id, c.symbol, p.direction, p.money_type, p.open_price, p.share_number, " +
            "  GREATEST(p.total_position - p.closed_position, 0) AS avail_qty " +
            "FROM member_contract_position p " +
            "INNER JOIN contract_coin c ON p.contract_id = c.id " +
            "WHERE p.status <> 2 " +
            "  AND p.experience_record_id IS NULL " +
            "  AND (#{follow} = 0 AND p.follow_position_id IS NULL OR #{follow} = 1 AND p.follow_position_id IS NOT NULL) " +
            "  AND (#{ii} = 1 OR p.member_id NOT IN (SELECT id FROM member WHERE is_internal = 1))")
    List<Map<String, Object>> listOpenPositions(@Param("follow") int follow, @Param("ii") int ii);

    // ── 今日平仓盈亏（contract_order_entrust） ────────────────────────────────

    /**
     * 今日平仓盈利：今日成交的平仓单中 profit_and_loss > 0 的总和。
     * deal_time 为毫秒时间戳。
     */
    @Select("SELECT COALESCE(SUM(profit_and_loss), 0) " +
            "FROM contract_order_entrust " +
            "WHERE entrust_type = 1 AND status = 3 " +
            "  AND profit_and_loss > 0 " +
            "  AND experience_record_id IS NULL " +
            "  AND deal_time >= #{startMs} AND deal_time < #{endMs} " +
            "  AND (#{follow} = 0 AND follow_id IS NULL OR #{follow} = 1 AND follow_id IS NOT NULL) " +
            "  AND (#{ii} = 1 OR member_id NOT IN (SELECT id FROM member WHERE is_internal = 1))")
    BigDecimal sumTodayCloseProfit(@Param("follow") int follow,
                                   @Param("startMs") long startMs,
                                   @Param("endMs")   long endMs,
                                   @Param("ii")      int ii);

    /**
     * 今日平仓亏损：今日成交的平仓单中 profit_and_loss < 0 绝对值的总和。
     */
    @Select("SELECT COALESCE(SUM(ABS(profit_and_loss)), 0) " +
            "FROM contract_order_entrust " +
            "WHERE entrust_type = 1 AND status = 3 " +
            "  AND profit_and_loss < 0 " +
            "  AND experience_record_id IS NULL " +
            "  AND deal_time >= #{startMs} AND deal_time < #{endMs} " +
            "  AND (#{follow} = 0 AND follow_id IS NULL OR #{follow} = 1 AND follow_id IS NOT NULL) " +
            "  AND (#{ii} = 1 OR member_id NOT IN (SELECT id FROM member WHERE is_internal = 1))")
    BigDecimal sumTodayCloseLoss(@Param("follow") int follow,
                                 @Param("startMs") long startMs,
                                 @Param("endMs")   long endMs,
                                 @Param("ii")      int ii);

    // ── 历史平仓盈亏（全量） ──────────────────────────────────────────────────

    /**
     * 历史累计平仓盈利（不限日期）。
     */
    @Select("SELECT COALESCE(SUM(profit_and_loss), 0) " +
            "FROM contract_order_entrust " +
            "WHERE entrust_type = 1 AND status = 3 " +
            "  AND profit_and_loss > 0 " +
            "  AND experience_record_id IS NULL " +
            "  AND (#{follow} = 0 AND follow_id IS NULL OR #{follow} = 1 AND follow_id IS NOT NULL) " +
            "  AND (#{ii} = 1 OR member_id NOT IN (SELECT id FROM member WHERE is_internal = 1))")
    BigDecimal sumTotalCloseProfit(@Param("follow") int follow, @Param("ii") int ii);

    /**
     * 历史累计平仓亏损绝对值（不限日期）。
     */
    @Select("SELECT COALESCE(SUM(ABS(profit_and_loss)), 0) " +
            "FROM contract_order_entrust " +
            "WHERE entrust_type = 1 AND status = 3 " +
            "  AND profit_and_loss < 0 " +
            "  AND experience_record_id IS NULL " +
            "  AND (#{follow} = 0 AND follow_id IS NULL OR #{follow} = 1 AND follow_id IS NOT NULL) " +
            "  AND (#{ii} = 1 OR member_id NOT IN (SELECT id FROM member WHERE is_internal = 1))")
    BigDecimal sumTotalCloseLoss(@Param("follow") int follow, @Param("ii") int ii);
}
