package com.copy.trade.timmer;


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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.injector.methods.SelectById;
import com.copy.trade.constant.KafkaTopic;
import com.copy.trade.consumer.MarketListener;
import com.copy.trade.entity.dto.ContractOrderEntrust;
import com.copy.trade.entity.dto.PositionDto;
import com.copy.trade.entity.po.Position;
import com.copy.trade.service.IPositionService;

@Component
public class CloseOrderTimer {
	
    @Autowired
    private MarketListener marketListener;
	
	@Autowired
    private IPositionService positionServiceImpl;
	
    @Autowired
    private KafkaTemplate kafkaTemplate;
    
	@Scheduled(cron = "0/2 * * * * *") 
	public void timer(){  
		List<PositionDto> selectPositionStatusNot30All = positionServiceImpl.selectPositionStatusNot30All();
		selectPositionStatusNot30All.forEach(position -> {
			Long positionId = position.getPositionId();
			BigDecimal stopLossPrice = position.getLossPrice();
			BigDecimal stopProfitPrice = position.getProfitPrice();
			Integer direction = position.getDirection();
			String symbol = position.getSymbol();
			BigDecimal currentPrice = marketListener.getCurrentPriceMap().get(symbol);
			if(currentPrice != null) {
				//跌破止损止盈价格时强平
				if((direction == 0 && ((stopLossPrice != null && currentPrice.compareTo(stopLossPrice)<0)  || (stopProfitPrice != null && currentPrice.compareTo(stopProfitPrice)>0)))
						|| (direction != 0 && ((stopLossPrice != null && currentPrice.compareTo(stopLossPrice)>0)  || (stopProfitPrice !=null && currentPrice.compareTo(stopProfitPrice)<0)))) {
					ContractOrderEntrust closeOrderEntrust = new ContractOrderEntrust();
					closeOrderEntrust.setPositionId(positionId);
					closeOrderEntrust.setProfitOrLoss(position.getProfitAmount());
					
					//profitOrLoss = 仓位的保证金乘以止盈或者止损比例
					if((direction == 0 && stopLossPrice!=null && currentPrice.compareTo(stopLossPrice)<0) || (direction != 0 && stopLossPrice !=null && currentPrice.compareTo(stopLossPrice)>0)) {
						closeOrderEntrust.setProfitOrLoss(position.getLossAmount());
					}
					kafkaTemplate.send(KafkaTopic.FOLLOW_POSITION_FORCE_CLOSE, JSON.toJSONString(closeOrderEntrust));
					
					//记录消息发送,只发送一次
					Position positionDb = positionServiceImpl.getById(position.getId());
					positionDb.setIsSendCloseMessage(true);
					positionServiceImpl.updateById(positionDb);
				}
			}
		});
	} 
	
}
