package com.bizzan.bitrade.service;

import java.math.BigDecimal;
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.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bizzan.bitrade.constant.TransactionType;
import com.bizzan.bitrade.constant.WithdrawStatus;
import com.bizzan.bitrade.dao.MoneyOperationRecordDao;
import com.bizzan.bitrade.entity.MemberTransaction;
import com.bizzan.bitrade.entity.MemberWallet;
import com.bizzan.bitrade.entity.MoneyOperationRecord;
import com.querydsl.core.types.Predicate;

@Service
public class MoneyOperationRecordService {

	@Autowired
	private MoneyOperationRecordDao dao;
    @Autowired
    private MemberWalletService walletService;
    @Autowired
    private MemberTransactionService memberTransactionService;
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;
	
	public MoneyOperationRecord save(MoneyOperationRecord record){
        return dao.save(record);
    }
    
    public MoneyOperationRecord findOne(Long id){
        return dao.findOne(id);
    }
    
    public Page<MoneyOperationRecord> findAll(Predicate predicate, Pageable pageable) {
        return dao.findAll(predicate, pageable);
    }
	
	@Transactional(rollbackFor = Exception.class)
    public void audit(Long[] ids, WithdrawStatus status) {
    	for (Long id : ids) {
    		MoneyOperationRecord record = dao.findOne(id);
    		
    		if(record.getStatus()==WithdrawStatus.PROCESSING && status == WithdrawStatus.SUCCESS) {
	    		MemberWallet memberWallet = walletService.findByMemberId(record.getMemberId());
	    		walletService.increaseBalance(memberWallet.getId(), record.getAmount());
	    		kafkaTemplate.send("trading-account-change", record.getMemberId()+"");
	    		
	    		MemberTransaction memberTransaction = new MemberTransaction();
	            memberTransaction.setMemberId(record.getMemberId());
	            memberTransaction.setAmount(record.getAmount());
	            memberTransaction.setSymbol("USDT");
	            memberTransaction.setCreateTime(record.getCreateTime());
	            memberTransaction.setType(TransactionType.PROMOTION_AWARD);
	            memberTransaction.setFee(BigDecimal.ZERO);
	            memberTransaction.setRealFee("0");
	            memberTransaction.setDiscountFee("0");
	            memberTransaction= memberTransactionService.save(memberTransaction);
    		}
    		
    		record.setStatus(status);
    		record.setAdmitTime(new Date());
    		dao.save(record);
    	}
	}
}
