package com.datacenter.mapper;

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

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * 平台每日盈亏统计 Mapper。
 * follow=0: 自主合约（follow_id IS NULL）
 * follow=1: 跟单（follow_id IS NOT NULL）
 * ii: includeInternal 0=排除内部账户 1=含
 */
@Mapper
public interface StatPlatformDailyPnlMapper extends BaseMapper<StatPlatformDailyPnl> {

    // ── 充值 / 提现（复用与 TodayOverview 相同的 SQL）────────────────────────────

    @Select("SELECT COALESCE(SUM(amount), 0) " +
            "FROM member_deposit " +
            "WHERE create_time >= #{start} AND create_time < #{end} " +
            "  AND unit LIKE '%USDT%' " +
            "  AND (#{ii} = 1 OR member_id NOT IN (SELECT id FROM member WHERE is_internal = 1))")
    BigDecimal sumDeposit(@Param("start") LocalDateTime start,
                          @Param("end")   LocalDateTime end,
                          @Param("ii")    int ii);

    @Select("SELECT COALESCE(SUM(total_amount), 0) " +
            "FROM withdraw_record " +
            "WHERE status = 3 " +
            "  AND deal_time >= #{start} AND deal_time < #{end} " +
            "  AND coin_id LIKE '%USDT%' " +
            "  AND (#{ii} = 1 OR member_id NOT IN (SELECT id FROM member WHERE is_internal = 1))")
    BigDecimal sumWithdraw(@Param("start") LocalDateTime start,
                           @Param("end")   LocalDateTime end,
                           @Param("ii")    int ii);

    // ── 开仓次数 / 开仓金额 ────────────────────────────────────────────────────

    /**
     * follow=0: follow_id IS NULL（自主合约，含带单员）
     * follow=1: follow_id IS NOT NULL（跟单用户）
     */
    @Select("SELECT COUNT(*) " +
            "FROM contract_order_entrust " +
            "WHERE entrust_type = 0 AND status = 3 " +
            "  AND experience_record_id IS NULL " +
            "  AND (#{follow} = 0 AND follow_id IS NULL OR #{follow} = 1 AND follow_id IS NOT NULL) " +
            "  AND deal_time >= #{startMs} AND deal_time < #{endMs} " +
            "  AND (#{ii} = 1 OR member_id NOT IN (SELECT id FROM member WHERE is_internal = 1))")
    int sumOpenCount(@Param("follow")  int follow,
                     @Param("startMs") long startMs,
                     @Param("endMs")   long endMs,
                     @Param("ii")      int ii);

    @Select("SELECT COALESCE(SUM(traded_volume * traded_price), 0) " +
            "FROM contract_order_entrust " +
            "WHERE entrust_type = 0 AND status = 3 " +
            "  AND experience_record_id IS NULL " +
            "  AND (#{follow} = 0 AND follow_id IS NULL OR #{follow} = 1 AND follow_id IS NOT NULL) " +
            "  AND deal_time >= #{startMs} AND deal_time < #{endMs} " +
            "  AND (#{ii} = 1 OR member_id NOT IN (SELECT id FROM member WHERE is_internal = 1))")
    BigDecimal sumOpenAmount(@Param("follow")  int follow,
                             @Param("startMs") long startMs,
                             @Param("endMs")   long endMs,
                             @Param("ii")      int ii);

    // ── 平仓盈利（profit_and_loss > 0）────────────────────────────────────────

    @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 deal_time >= #{startMs} AND deal_time < #{endMs} " +
            "  AND (#{ii} = 1 OR member_id NOT IN (SELECT id FROM member WHERE is_internal = 1))")
    BigDecimal sumCloseProfit(@Param("follow")  int follow,
                              @Param("startMs") long startMs,
                              @Param("endMs")   long endMs,
                              @Param("ii")      int ii);

    // ── 平仓亏损（profit_and_loss < 0，返回正值）─────────────────────────────────

    @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 deal_time >= #{startMs} AND deal_time < #{endMs} " +
            "  AND (#{ii} = 1 OR member_id NOT IN (SELECT id FROM member WHERE is_internal = 1))")
    BigDecimal sumCloseLoss(@Param("follow")  int follow,
                            @Param("startMs") long startMs,
                            @Param("endMs")   long endMs,
                            @Param("ii")      int ii);

    // ── 手续费（毛，扣返佣前）────────────────────────────────────────────────────

    /**
     * 用户侧支付的手续费（为负数账变，取反得平台毛收入）。
     * type=19 CONTRACT_FEE（自主合约）；type=37 FOLLOW_FEE（跟单）。
     */
    @Select("SELECT COALESCE(-SUM(amount), 0) " +
            "FROM member_transaction " +
            "WHERE type = #{feeType} " +
            "  AND create_time >= #{start} AND create_time < #{end} " +
            "  AND (#{ii} = 1 OR member_id NOT IN (SELECT id FROM member WHERE is_internal = 1))")
    BigDecimal sumGrossFee(@Param("feeType") int feeType,
                           @Param("start")   LocalDateTime start,
                           @Param("end")     LocalDateTime end,
                           @Param("ii")      int ii);

    /**
     * 代理/平级返佣总额（type∈{0,1,2}：OPEN/CLOSE/LEVEL），用于按比例分摊到自主和跟单。
     */
    @Select("SELECT COALESCE(SUM(num), 0) " +
            "FROM contract_reward_record " +
            "WHERE type IN (0, 1, 2) " +
            "  AND create_time >= #{start} AND create_time < #{end} " +
            "  AND (#{ii} = 1 OR from_member_id NOT IN (SELECT id FROM member WHERE is_internal = 1))")
    BigDecimal sumTotalRebates(@Param("start") LocalDateTime start,
                               @Param("end")   LocalDateTime end,
                               @Param("ii")    int ii);

    // ── 资金费率净收入 ──────────────────────────────────────────────────────────

    /**
     * type=26 合约资金费（CONTRACT_OVERNIGHT_FEE）；type=42 跟单资金费（FOLLOW_OVERNIGHT_FEE）。
     * 用户侧为负账变，取反得平台净收入。
     */
    @Select("SELECT COALESCE(-SUM(amount), 0) " +
            "FROM member_transaction " +
            "WHERE type = #{fundingType} " +
            "  AND create_time >= #{start} AND create_time < #{end} " +
            "  AND (#{ii} = 1 OR member_id NOT IN (SELECT id FROM member WHERE is_internal = 1))")
    BigDecimal sumFundingFee(@Param("fundingType") int fundingType,
                             @Param("start")       LocalDateTime start,
                             @Param("end")         LocalDateTime end,
                             @Param("ii")          int ii);
}
