package com.bizzan.bitrade.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.bizzan.bitrade.constant.CommonStatus;
import com.bizzan.bitrade.constant.ContractRewardRecordType;
import com.bizzan.bitrade.constant.TransactionType;
import com.bizzan.bitrade.dao.ContractOrderEntrustDao;
import com.bizzan.bitrade.dao.ContractOrderEntrustRepository;
import com.bizzan.bitrade.dao.ContractRewardRecordRepository;
import com.bizzan.bitrade.entity.*;
import com.bizzan.bitrade.pagination.Criteria;
import com.bizzan.bitrade.pagination.Restrictions;
import com.bizzan.bitrade.service.Base.BaseService;
import com.bizzan.bitrade.util.BigDecimalUtils;
import com.bizzan.bitrade.util.DateUtil;
import com.bizzan.bitrade.util.InnerInvokeUtil;
import com.bizzan.bitrade.util.JSONUtils;
import com.bizzan.bitrade.vo.RewardSetOneLevel;
import com.bizzan.bitrade.vo.RewardSetVo;
import com.querydsl.core.types.Predicate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Slf4j
@Service
public class ExchangeRewardService extends BaseService {

    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberWeightUpperService memberWeightUpperService;
    @Autowired
    private MemberWalletService memberWalletService;
    @Autowired
    private MemberTransactionService memberTransactionService;
    @Autowired
    private UserPurseService userPurseService;

    @Autowired
    private RedisTemplate redisTemplate ;
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    
    public void executeReward(Member fromMember, Long agentId, BigDecimal fee, int allocatedRate, List<Long> memberIdList) {
    	MemberWeightUpper upper = memberWeightUpperService.findMemberWeightUpperByMemberId(agentId);
    	if(upper == null) {
    		log.info("upper is null, agentId={}", agentId);
    		return;
    	}
    	
    	int totalRate = upper.getRate();
    	
    	
    	if(totalRate>0){
            Integer currentRate=totalRate - allocatedRate;
            if(currentRate<=0) {
            	log.error("rate error, currentRate={}, upper={}", currentRate, upper.getMemberId());
            	return;
            }
            //应返比例
            BigDecimal rate = BigDecimal.valueOf(currentRate).divide(BigDecimal.valueOf(100),8,BigDecimal.ROUND_DOWN);
            //返佣
            //MemberWallet memberWallet = memberWalletService.findByCoinUnitAndMemberId("USDT", upper.getMemberId());
            BigDecimal reward = BigDecimalUtils.mulDown(fee ,rate, 8);
            Member agentMember = memberService.findOne(agentId);
            if (reward.compareTo(BigDecimal.ZERO) > 0 && agentMember.getDisableReward()==0 && agentMember.getStatus()==CommonStatus.NORMAL) {
                //memberWalletService.increaseBalance(memberWallet.getId(), reward);
                //invokeUtil.increaseBalance("USDT", upper.getMemberId(), reward);
            	userPurseService.increaseBalance(upper.getMemberId(), reward);
            	//exchangeWalletService.transferIn(upper.getMemberId(), reward);
                
                
                MemberTransaction memberTransaction = new MemberTransaction();
                memberTransaction.setAmount(reward);
                memberTransaction.setFee(BigDecimal.ZERO);
                memberTransaction.setMemberId(upper.getMemberId());
                memberTransaction.setSymbol("USDT");
                memberTransaction.setCreateTime(DateUtil.getCurrentDate());
                memberTransaction.setType(TransactionType.SPOT_AWARD);
                memberTransaction.setDiscountFee("0");
                memberTransaction.setRealFee("0");
                memberTransaction = memberTransactionService.save(memberTransaction);
                
                if(!memberIdList.contains(upper.getMemberId()))
                	memberIdList.add(upper.getMemberId());
                
            }
        }
    	
    	if(upper.getUpper() == null)
    		return;
    	else {
    		executeReward(fromMember, Long.parseLong(upper.getUpper()), fee, totalRate, memberIdList);
    	}
    }
    /**
     * 合约返佣
     * @param orderEntrust
     */
    @Transactional(rollbackFor = Exception.class)
    public BigDecimal sendReturnReward(MemberTransaction transaction, List<Long> memberIdList) {
        BigDecimal lave = BigDecimal.ZERO.subtract(transaction.getAmount());
    	memberTransactionService.updateRewardFlag(transaction.getId());
        //修改返佣状态
        Member member = memberService.findOne(transaction.getMemberId());
        if(member.getDisableReward() == 1)
        	return BigDecimal.ZERO;
        if(member.getIsInternal() != null && member.getIsInternal() == 1)
        	return BigDecimal.ZERO;
        if(lave.compareTo(BigDecimal.ZERO)<=0)
        	return BigDecimal.ZERO;
        executeReward(member, transaction.getMemberId(), lave, 0, memberIdList);
        
        return lave;
    }

    
}
