package com.bizzan.bitrade.vo;

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

import com.bizzan.bitrade.entity.ExchangeWallet;
import com.bizzan.bitrade.util.DateUtil;

import lombok.Data;

@Data
public class ExchangeAccount {

	private List<ExchangeWallet> wallets;
	
	private Map<String, BigDecimal> priceMap;
	
	private Map<String, BigDecimal> clearPriceMap;
	
	public BigDecimal getCurrentValue() {
		if(wallets == null) {
			return BigDecimal.ZERO;
		}
		double currentValue = 0;
		for(ExchangeWallet wallet : wallets) {
			if(wallet.getCoinId().equals("USDT")) {
				currentValue += wallet.getBalance().doubleValue();
			} else if (priceMap!=null && priceMap.containsKey(wallet.getCoinId()+"/USDT")) {
				currentValue += wallet.getBalance().add(wallet.getFrozenBalance()).doubleValue() * priceMap.get(wallet.getCoinId()+"/USDT").doubleValue();
			} else if (wallet.getOpenPrice()!=null){
				currentValue += wallet.getBalance().add(wallet.getFrozenBalance()).doubleValue() * wallet.getOpenPrice().doubleValue();
			}
		}
		return BigDecimal.valueOf(currentValue);
	}
	
	/**
	 * 降级估算：仅在昨日无快照数据时使用。
	 * 对今日新建仓位：盈亏 = qty * (currentPrice - openPrice)
	 * 对昨日已有仓位：以 clearPriceMap（零点价格）为基准计算当日浮动
	 */
	public BigDecimal getTodayProfit() {
		if (wallets == null || priceMap == null) {
			return BigDecimal.ZERO;
		}
		double profit = 0;
		for (ExchangeWallet wallet : wallets) {
			BigDecimal currentPrice = null;
			if ("USDT".equalsIgnoreCase(wallet.getCoinId())) {
				// USDT 本身不浮动，盈亏为 0
				continue;
			} else {
				currentPrice = priceMap.get(wallet.getCoinId() + "/USDT");
			}
			if (currentPrice == null || currentPrice.compareTo(BigDecimal.ZERO) == 0) continue;

			BigDecimal basePrice;
			if (wallet.getOpenTime() != null && wallet.getOpenTime().compareTo(DateUtil.getClearTime()) < 0) {
				// 昨日持仓：以零点清算价为基准
				basePrice = (clearPriceMap != null && clearPriceMap.containsKey(wallet.getCoinId() + "/USDT"))
						? clearPriceMap.get(wallet.getCoinId() + "/USDT")
						: currentPrice; // clearPriceMap 无数据则视为无盈亏
			} else {
				// 今日新建仓位：以建仓价为基准
				basePrice = (wallet.getOpenPrice() != null && wallet.getOpenPrice().compareTo(BigDecimal.ZERO) > 0)
						? wallet.getOpenPrice()
						: currentPrice;
			}
			profit += wallet.getBalance().add(wallet.getFrozenBalance()).doubleValue()
					* (currentPrice.doubleValue() - basePrice.doubleValue());
		}
		return BigDecimal.valueOf(profit);
	}
}
