package com.bizzan.bitrade.service;

import com.bizzan.bitrade.entity.FuturesKline;
import com.bizzan.bitrade.entity.KLine;
import com.bizzan.bitrade.mapper.market.FuturesKlineMapper;
import com.bizzan.bitrade.service.Base.BaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ContractMarketService extends BaseService {

    @Autowired
    private FuturesKlineMapper futuresKlineMapper;

    private Logger logger = LoggerFactory.getLogger(ContractMarketService.class);

    // "BTC/USDT" → "futures_kline_btcusdt"
    private String toTableName(String symbol) {
        return "futures_kline_" + symbol.replace("/", "").toLowerCase();
    }

    // FuturesKline (MySQL) → KLine (业务对象)
    private KLine toKLine(FuturesKline f) {
        KLine k = new KLine();
        k.setOpenPrice(f.getOpen());
        k.setClosePrice(f.getClose());
        k.setHighestPrice(f.getHigh());
        k.setLowestPrice(f.getLow());
        k.setVolume(f.getVolume());
        k.setTurnover(f.getTurnover());
        // begin_time 毫秒 → KLine.time 秒
        k.setTime(f.getBeginTime() / 1000);
        k.setPeriod(f.getPeriod());
        return k;
    }

    public List<KLine> findAllKLine(String symbol, String period) {
        return futuresKlineMapper.findAllKLine(toTableName(symbol), period)
                .stream().map(this::toKLine).collect(Collectors.toList());
    }

    public List<KLine> findAllKLine(String symbol, long fromTime, long toTime, String period) {
        return futuresKlineMapper.findKLineRange(toTableName(symbol), period, fromTime * 1000, toTime * 1000)
                .stream().map(this::toKLine).collect(Collectors.toList());
    }

    public long findMaxTimestamp(String symbol, String period) {
        Long maxMs = futuresKlineMapper.findMaxBeginTime(toTableName(symbol), period);
        return maxMs != null ? maxMs / 1000 : 0;
    }

    public KLine findLatest(String symbol, String period) {
        FuturesKline f = futuresKlineMapper.findLatest(toTableName(symbol), period);
        return f != null ? toKLine(f) : null;
    }
}
