package com.bizzan.bitrade.controller;

import static com.bizzan.bitrade.constant.SysConstant.SESSION_MEMBER;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import com.bizzan.bitrade.constant.PageModel;
import com.bizzan.bitrade.engine.ContractCoinMatchFactory;
import com.bizzan.bitrade.engine.FollowAccountMonitor;
import com.bizzan.bitrade.engine.TradingAccountMonitor;
import com.bizzan.bitrade.entity.FollowAccount;
import com.bizzan.bitrade.entity.MemberContractPosition;
import com.bizzan.bitrade.entity.transform.AuthMember;
import com.bizzan.bitrade.service.ContractOrderEntrustService;
import com.bizzan.bitrade.service.MemberContractPositionService;
import com.bizzan.bitrade.service.WalletService;
import com.bizzan.bitrade.util.MessageResult;
import com.bizzan.bitrade.vo.MemberContractPositionWithCut;
import com.bizzan.bitrade.vo.TradingAccount;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Api(value = "MemberContractPositionController" , tags = "仓位接口")
@RestController
@RequestMapping("/position")
public class MemberContractPositionController {

	@Autowired
	private MemberContractPositionService positionService;
	@Autowired
    private TradingAccountMonitor tradingAccountMonitor;
	@Autowired
    private FollowAccountMonitor followAccountMonitor;
    @Autowired
    private ContractOrderEntrustService contractOrderEntrustService;
    @Autowired
    private ContractCoinMatchFactory contractCoinMatchFactory;
    
    @ApiOperation(value="刷新仓位", notes="刷新当前仓位(已弃用，改从wallet-new的get-with-positions获取数据)")
    @GetMapping("refresh")
	public MessageResult<List<MemberContractPositionWithCut>> refresh(@SessionAttribute(SESSION_MEMBER) AuthMember authMember) {
		TradingAccount tradingAccount = tradingAccountMonitor.get(authMember.getId());
		//List<MemberContractPosition> positions = positionService.findCurrentPositionsByMemberId(authMember.getId());
		
		BigDecimal blastRate = tradingAccount.getEstimatedBlastRate();
		List<MemberContractPositionWithCut> positions = tradingAccount.getCurrentPositionWithCutList();
		
		List<MemberContractPositionWithCut> retList = new ArrayList<MemberContractPositionWithCut>();
		for(MemberContractPosition position: positions) {
			MemberContractPositionWithCut positionWithCut = new MemberContractPositionWithCut();
			BeanUtils.copyProperties(position, positionWithCut);
			positionWithCut.setCutList(contractCoinMatchFactory.getContractCoinMatch(position.getCoin().getSymbol()).findRunningCutOrders(position.getId()));
			//positionWithCut.setCutList(contractOrderEntrustService.queryEntrustCutOrdersByPositionId(position.getId()));
			if(blastRate.doubleValue()==0 || (blastRate.doubleValue() > 1 && blastRate.doubleValue() < 1000))
				positionWithCut.setEstimatedBlastPrice(BigDecimal.valueOf(-1));
			else {
				if (position.getCurrentPrice()!=null)
					positionWithCut.setEstimatedBlastPrice(position.getCurrentPrice().multiply(BigDecimal.ONE.subtract(blastRate)));
			}
			positionWithCut.setMarginRate(tradingAccount.getCurrentCapital().multiply(BigDecimal.valueOf(100)).divide(tradingAccount.getCurrentMargin(), 2, BigDecimal.ROUND_DOWN));
			retList.add(positionWithCut);
		}
		MessageResult<List<MemberContractPositionWithCut>> result = MessageResult.success("success");
        result.setData(retList);
        return result;
	}
	
	@ApiOperation(value="获取仓位", notes="获取当前仓位(已弃用，改从wallet-new的get-with-positions获取数据)")
    @GetMapping("list")
	public MessageResult<List<MemberContractPositionWithCut>> list(@SessionAttribute(SESSION_MEMBER) AuthMember authMember) {
		TradingAccount tradingAccount = tradingAccountMonitor.get(authMember.getId());
		//List<MemberContractPosition> positions = positionService.findCurrentPositionsByMemberId(authMember.getId());
		
		BigDecimal blastRate = tradingAccount.getEstimatedBlastRate();
		List<MemberContractPositionWithCut> positions = tradingAccount.getCurrentPositionWithCutList();
		
		List<MemberContractPositionWithCut> retList = new ArrayList<MemberContractPositionWithCut>();
		if(positions != null) {
			for(MemberContractPosition position: positions) {
				MemberContractPositionWithCut positionWithCut = new MemberContractPositionWithCut();
				BeanUtils.copyProperties(position, positionWithCut);
				positionWithCut.setCutList(contractCoinMatchFactory.getContractCoinMatch(position.getCoin().getSymbol()).findRunningCutOrders(position.getId()));
				//positionWithCut.setCutList(contractOrderEntrustService.queryEntrustCutOrdersByPositionId(position.getId()));
				if(blastRate.doubleValue()==0 || (blastRate.doubleValue() > 1 && blastRate.doubleValue() < 1000))
					positionWithCut.setEstimatedBlastPrice(BigDecimal.valueOf(-1));
				else {
					if (position.getCurrentPrice()!=null)
						positionWithCut.setEstimatedBlastPrice(position.getCurrentPrice().multiply(BigDecimal.ONE.subtract(blastRate)));
				}
				if(tradingAccount.getCurrentMargin().compareTo(BigDecimal.ZERO)>0)
					positionWithCut.setMarginRate(tradingAccount.getCurrentMargin().multiply(BigDecimal.valueOf(100)).divide(tradingAccount.getCurrentCapital(), 2, BigDecimal.ROUND_DOWN));
				retList.add(positionWithCut);
			}
		}
		MessageResult<List<MemberContractPositionWithCut>> result = MessageResult.success("success");
        result.setData(retList);
        return result;
	}
	
	@ApiOperation(value="获取历史仓位", notes="获取历史仓位")
    @GetMapping("history")
	public Page<MemberContractPositionWithCut> history(@SessionAttribute(SESSION_MEMBER) AuthMember authMember,
			int pageNo,
            int pageSize) {
		Page<MemberContractPosition> positions = positionService.findHistoryPositionsByMemberId(authMember.getId(), pageNo, pageSize);
		List<MemberContractPositionWithCut> retList = new ArrayList<MemberContractPositionWithCut>();
		for(MemberContractPosition position: positions) {
			MemberContractPositionWithCut positionWithCut = new MemberContractPositionWithCut();
			BeanUtils.copyProperties(position, positionWithCut);
			positionWithCut.setCutList(contractOrderEntrustService.querySuccessCutOrdersByPositionId(position.getId()));
			retList.add(positionWithCut);
		}
		PageModel pageModel = new PageModel();
		pageModel.setPageNo(pageNo);
		pageModel.setPageSize(pageSize);
		Page<MemberContractPositionWithCut> newAll = new PageImpl<MemberContractPositionWithCut>(retList, pageModel.getPageable(), positions.getTotalElements());
		return newAll;
	}
	
	@ApiOperation(value="获取跟单仓位", notes="获取当前跟单仓位")
    @GetMapping("follow-list")
	public MessageResult<List<MemberContractPositionWithCut>> listFollow(@SessionAttribute(SESSION_MEMBER) AuthMember authMember) {
		//FollowAccount followAccount = followAccountMonitor.get(authMember.getId());
		List<MemberContractPosition> positions = positionService.findCurrentFollowPositionsByMemberId(authMember.getId());
		
		//BigDecimal blastRate = followAccount.getEstimatedBlastRate();
		//Set<MemberContractPosition> positions = followAccount.getCurrentPositionList();
		
		List<MemberContractPositionWithCut> retList = new ArrayList<MemberContractPositionWithCut>();
		for(MemberContractPosition position: positions) {
			MemberContractPositionWithCut positionWithCut = new MemberContractPositionWithCut();
			BeanUtils.copyProperties(position, positionWithCut);
			positionWithCut.setCutList(contractCoinMatchFactory.getContractCoinMatch(position.getCoin().getSymbol()).findRunningCutOrders(position.getId()));
			//positionWithCut.setCutList(contractOrderEntrustService.queryEntrustCutOrdersByPositionId(position.getId()));
			
			//if (position.getCurrentPrice()!=null)
			//	positionWithCut.setEstimatedBlastPrice(position.getCurrentPrice().multiply(BigDecimal.ONE.subtract(blastRate)));
			
			retList.add(positionWithCut);
		}
		MessageResult<List<MemberContractPositionWithCut>> result = MessageResult.success("success");
        result.setData(retList);
        return result;
	}
}
