package com.bizzan.bitrade.dao;

import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import com.bizzan.bitrade.constant.CertifiedBusinessStatus;
import com.bizzan.bitrade.dao.base.BaseDao;
import com.bizzan.bitrade.entity.MemberHistory;
import org.springframework.transaction.annotation.Transactional;

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

public interface MemberHistoryDao extends BaseDao<MemberHistory> {
    
    List<MemberHistory> findByMemberId(Long memberId);

    @Query(value="select sum(m.balance) as allAmount from member_history m where m.member_id = :memberId",nativeQuery = true)
    BigDecimal sumBalanceByMemberId(@Param("memberId") long memberId);
    
    @Query(value="select sum(m.follow_profit+m.follow_loss) as allAmount from member_history m where m.member_id = :memberId",nativeQuery = true)
    BigDecimal sumFollowRevenueByMemberId(@Param("memberId") long memberId);

    /**
     * 查询用户最近一条每日统计记录中的质押余额快照
     * 用于今日收益率基准计算，反映昨日末质押资产规模
     *
     * @param memberId 用户ID
     * @return 最新一条记录的质押余额，无记录返回 null
     */
    @Query(value="select m.staking_balance from member_history m where m.member_id = :memberId order by m.statistic_date desc limit 1",nativeQuery = true)
    BigDecimal getLatestStakingBalance(@Param("memberId") long memberId);
    
    @Query(value="select 0 as id, m.member_id, now() statistic_date, sum(m.balance) as balance, sum(m.recharge) as recharge, sum(m.withdraw) as withdraw, sum(m.transfer_in) as transfer_in, sum(m.transfer_out) as transfer_out, sum(m.activity_award) as activity_award, sum(m.promotion_award) as promotion_award, sum(m.dividend) as dividend, sum(m.admin_recharge) as admin_recharge, sum(m.award) as award, sum(m.profit) as profit, sum(m.loss) as loss, sum(m.fee) as fee, sum(m.overnight_fee_in) as overnight_fee_in, sum(m.overnight_fee_out) as overnight_fee_out, sum(m.follow_fee) as follow_fee, sum(m.follow_profit) as follow_profit, sum(m.follow_loss) as follow_loss, sum(m.follow_award) as follow_award, sum(m.follow_dividend_in) as follow_dividend_in, sum(m.follow_dividend_out) as follow_dividend_out, sum(m.follow_overnight_fee_in) as follow_overnight_fee_in, sum(m.follow_overnight_fee_out) as follow_overnight_fee_out, sum(m.exchange_profit) as exchange_profit, sum(m.exchange_loss) as exchange_loss, sum(m.exchange_fee) as exchange_fee, sum(m.exchange_award) as exchange_award, sum(m.staking_balance) as staking_balance, sum(m.fund_balance) as fund_balance from member_history m where m.member_id = :memberId",nativeQuery = true)
    MemberHistory sumMemberHistoryByMemberId(@Param("memberId") long memberId);
}
