package com.bizzan.bitrade.service;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bizzan.bitrade.dao.GameAdmitDao;
import com.bizzan.bitrade.entity.GameAdmit;
import com.bizzan.bitrade.entity.GameRecord;
import com.querydsl.core.types.Predicate;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class GameAdmitService {

	@Autowired
	private GameAdmitDao dao;
	@Autowired
	private GameWalletService gameWalletService;
	@Autowired
	private GameRecordService gameRecordService;
	
	public GameAdmit save(GameAdmit entity) {
		return dao.save(entity);
	}
	
	public GameAdmit findOne(Long id) {
		return dao.findOne(id);
	}
	
	public GameAdmit findByOrder(GameRecord order) {
		return dao.findByOrder(order);
	}
	
	public Page<GameAdmit> findAll(Predicate predicate, Pageable pageable) {
		return dao.findAll(predicate, pageable);
	}
	
	@Transactional(rollbackFor = Exception.class)
	public void clear(Long id) {
		GameAdmit gameAdmit = this.findOne(id);
		if(gameAdmit.getAdmitStatus()==0) {
			GameRecord order = gameAdmit.getOrder();
			if(order.getStatus() == 0) {
				gameWalletService.clear(order.getMemberId(), order.getAmount(), order.getFee(), gameAdmit.getProfit());
				gameAdmit.setAdmitStatus(1);
				gameAdmit.setAdmitTime(new Date());
				dao.save(gameAdmit);
				
				order.setStatus(1);
				gameRecordService.save(order);
				log.info("clear finish, gameAdmit={}", gameAdmit);
			}
		}
	}
}
