package com.datacenter.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.datacenter.entity.stat.StatTodayOverview;
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。
 * ii = includeInternal (0 排除内部账户 / 1 含内部账户)
 * 当 ii=0 时，通过 NOT IN 子查询排除 member.is_internal=1 的账户。
 */
@Mapper
public interface StatTodayOverviewMapper extends BaseMapper<StatTodayOverview> {

    // ── 今日盈亏 ──────────────────────────────────────────────────────────────

    /**
     * 平仓盈亏（平台视角）= -(用户平仓 P&L 之和)。
     * 使用 deal_time（毫秒时间戳）过滤当日。
     */
    @Select("SELECT COALESCE(-SUM(profit_and_loss), 0) " +
            "FROM contract_order_entrust " +
            "WHERE entrust_type = 1 AND status = 3 " +
            "  AND experience_record_id IS 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 sumClosePl(@Param("startMs") long startMs,
                          @Param("endMs")   long endMs,
                          @Param("ii")      int ii);

    /**
     * 毛手续费（用户侧即时扣费）：type=19 合约手续费，type=37 跟单手续费。
     * 与定时批量任务无关，order 成交即写入，实时可查。
     */
    @Select("SELECT COALESCE(-SUM(amount), 0) " +
            "FROM member_transaction " +
            "WHERE type IN (19, 37) " +
            "  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("start") LocalDateTime start,
                           @Param("end")   LocalDateTime end,
                           @Param("ii")    int ii);

    /**
     * 代理/平级返佣总额（type∈{0,1,2}），从毛手续费中扣除得到平台实到手续费。
     * 统计表显示的 合约/跟单手续费 均已减去这部分，今日盈亏须保持一致。
     */
    @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 sumRebates(@Param("start") LocalDateTime start,
                          @Param("end")   LocalDateTime end,
                          @Param("ii")    int ii);


/**
     * 资金费净额（平台视角）= -(用户侧资金费账变之和)。
     * type=26 合约资金费率；type=42 跟单资金费率。
     */
    @Select("SELECT COALESCE(-SUM(amount), 0) " +
            "FROM member_transaction " +
            "WHERE type IN (26, 42) " +
            "  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 sumNetFundingFee(@Param("start") LocalDateTime start,
                                @Param("end")   LocalDateTime end,
                                @Param("ii")    int ii);

    // ── 今日充值 ──────────────────────────────────────────────────────────────

    @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);

    // ── 今日提现 ──────────────────────────────────────────────────────────────

    /**
     * status=3(SUCCESS)；deal_time 为处理完成时间；coin_id 即 coin.name（字符串主键）。
     */
    @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);

    // ── 今日交易额 ────────────────────────────────────────────────────────────

    /**
     * 开仓交易额(USDT) = volume(开仓数量) × traded_price(成交价)。
     * 含合约与跟单两个业务模块；entrust_type=0 开仓；status=3 成交；跟单单据同样写入此表，无需跨库。
     */
    @Select("SELECT COALESCE(SUM(traded_volume * traded_price), 0) " +
            "FROM contract_order_entrust " +
            "WHERE entrust_type = 0 AND status = 3 " +
            "  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 sumTradeVolume(@Param("startMs") long startMs,
                              @Param("endMs")   long endMs,
                              @Param("ii")      int ii);

    // ── 今日注册 / 登录 ────────────────────────────────────────────────────────

    @Select("SELECT COUNT(*) " +
            "FROM member " +
            "WHERE registration_time >= #{start} AND registration_time < #{end} " +
            "  AND (#{ii} = 1 OR COALESCE(is_internal, 0) != 1)")
    int countRegister(@Param("start") LocalDateTime start,
                      @Param("end")   LocalDateTime end,
                      @Param("ii")    int ii);

    @Select("SELECT COUNT(DISTINCT member_id) " +
            "FROM member_operation_log " +
            "WHERE operation_type = 'LOGIN' " +
            "  AND create_time >= #{start} AND create_time < #{end} " +
            "  AND (#{ii} = 1 OR member_id NOT IN (SELECT id FROM member WHERE is_internal = 1))")
    int countLogin(@Param("start") LocalDateTime start,
                   @Param("end")   LocalDateTime end,
                   @Param("ii")    int ii);
}
