package com.bizzan.bitrade.consumer;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bizzan.bitrade.engine.ContractCoinMatchFactory;
import com.bizzan.bitrade.engine.TradingAccountMonitor;
import com.bizzan.bitrade.entity.ContractCoin;
import com.bizzan.bitrade.entity.ContractOrderPattern;
import com.bizzan.bitrade.entity.Member;
import com.bizzan.bitrade.entity.MemberContractWallet;
import com.bizzan.bitrade.service.ContractCoinService;
import com.bizzan.bitrade.service.ExchangeCoinService;
import com.bizzan.bitrade.service.ExchangeWalletService;
import com.bizzan.bitrade.service.MemberContractWalletService;
import com.bizzan.bitrade.service.MemberService;
import com.bizzan.bitrade.service.MemberTransactionService;
import com.bizzan.bitrade.service.UserPurseService;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

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

@Component
public class MemberConsumer {
    private Logger logger = LoggerFactory.getLogger(MemberConsumer.class);

    @Autowired
    private MemberContractWalletService memberContractWalletService;
    
    @Autowired
    private TradingAccountMonitor tradingAccountMonitor;

    @Autowired
    private ContractCoinMatchFactory contractCoinMatchFactory; // 合约引擎工厂

    @Autowired
    private ContractCoinService contractCoinService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private UserPurseService userPurseService;
    @Autowired
    private MemberTransactionService memberTransactionService;
    @Autowired
    private ExchangeWalletService exchangeWalletService;
    @Autowired
    private ExchangeCoinService exchangecoinService;

    /**
     * 用户注册成功，创建合约账户（此消息发送自Ucenter）
     * @param content
     */
    @KafkaListener(topics = {"member-register-swap"})
    public void handle(String content) {
        logger.info("[注册流程-swap] 收到member-register-swap消息, data={}", content);
        if (StringUtils.isEmpty(content)) {
            logger.warn("[注册流程-swap] 消息内容为空, 忽略");
            return;
        }
        JSONObject json = JSON.parseObject(content);
        if(json == null) {
            logger.warn("[注册流程-swap] JSON解析失败, 忽略");
            return ;
        }
        Long memberId = json.getLong("uid");
        logger.info("[注册流程-swap] 开始为memberId={}创建合约账户", memberId);
        userPurseService.create(memberId);
        logger.info("[注册流程-swap] 已创建userPurse, memberId={}", memberId);
        //获取所有支持的币种
        List<ContractCoin> coins =  contractCoinService.findAll();
        for(ContractCoin coin:coins) {
            logger.info("[注册流程-swap] 创建合约钱包 memberId={}, symbol={}", memberId, coin.getSymbol());
            addMemberContractWallet(coin, memberId);
        }
        logger.info("[注册流程-swap] member-register-swap处理完成, memberId={}, 共{}个合约币种", memberId, coins.size());
    }
    
    @KafkaListener(topics = {"add-contract-to-members"})
    public void memberContractAdd(String content) {
        logger.info("handle member-register,data={}", content);
        if (StringUtils.isEmpty(content)) {
            return;
        }
        JSONObject json = JSON.parseObject(content);
        if(json == null) {
            return ;
        }
        String symbol = json.getString("symbol");
        ContractCoin coin = contractCoinService.findBySymbol(symbol);
        //获取所有支持的币种
        List<Member> members = memberService.findAll();
        for (Member member: members) {
        	addMemberContractWallet(coin, member.getId());
        }
    }
    
    private void addMemberContractWallet(ContractCoin coin, Long memberId) {
    	MemberContractWallet wallet = new MemberContractWallet();
        //wallet.setUsdtPattern(ContractOrderPattern.FIXED);
        wallet.setUsdtPattern(ContractOrderPattern.CROSSED);
        wallet.setUsdtBuyPosition(BigDecimal.ZERO);
        wallet.setUsdtTotalProfitAndLoss(BigDecimal.ZERO);
        wallet.setCoinBalance(BigDecimal.ZERO);
        wallet.setCoinBuyLeverage(BigDecimal.TEN); // 10倍合约
        wallet.setCoinBuyPosition(BigDecimal.ZERO);
        wallet.setCoinBuyPrice(BigDecimal.ZERO);
        wallet.setCoinBuyPrincipalAmount(BigDecimal.ZERO);
        wallet.setCoinFrozenBalance(BigDecimal.ZERO);
        wallet.setCoinFrozenBuyPosition(BigDecimal.ZERO);
        wallet.setCoinFrozenSellPosition(BigDecimal.ZERO);
        //wallet.setCoinPattern(ContractOrderPattern.FIXED);
        wallet.setCoinPattern(ContractOrderPattern.CROSSED);
        wallet.setCoinSellLeverage(BigDecimal.TEN);
        wallet.setCoinSellPosition(BigDecimal.ZERO);
        wallet.setCoinSellPrice(BigDecimal.ZERO);
        wallet.setCoinSellPrincipalAmount(BigDecimal.ZERO);
        wallet.setCoinShareNumber(coin.getShareNumber());
        wallet.setCoinTotalProfitAndLoss(BigDecimal.ZERO);
        wallet.setContractCoin(coin);
        wallet.setMemberId(memberId);
        wallet.setUsdtBalance(BigDecimal.ZERO);
        wallet.setUsdtBuyLeverage(BigDecimal.TEN);
        wallet.setUsdtBuyPrice(BigDecimal.ZERO);
        wallet.setUsdtBuyPrincipalAmount(BigDecimal.ZERO);
        wallet.setUsdtFrozenBalance(BigDecimal.ZERO);
        wallet.setUsdtFrozenBuyPosition(BigDecimal.ZERO);
        wallet.setUsdtFrozenSellPosition(BigDecimal.ZERO);
        wallet.setUsdtSellLeverage(BigDecimal.TEN);
        wallet.setUsdtSellPosition(BigDecimal.ZERO);
        wallet.setUsdtSellPrice(BigDecimal.ZERO);
        wallet.setUsdtSellPrincipalAmount(BigDecimal.ZERO);
        wallet.setUsdtShareNumber(coin.getShareNumber());

        memberContractWalletService.save(wallet);
    }

    //@KafkaListener(topics = {"member-wallet-change"})
    public void memberPatternModify(String content) {
        logger.info("handle member-wallet-change={}", content);
        if (StringUtils.isEmpty(content)) {
            return;
        }
        JSONObject json = JSON.parseObject(content);
        if (json == null) {
            return;
        }
        // 更新用户持仓基础信息（仓位，合约等）
        contractCoinMatchFactory.getContractCoinMatch(json.getString("symbol")).memberWalletChange(json.getLong("walletId"));
    }
    
    @KafkaListener(topics = {"trading-account-change"})
    public void tradingAccountChange(String content) {
        logger.info("trading-account-change={}", content);
        if (StringUtils.isEmpty(content)) {
            return;
        }
        if(content.indexOf(",")>0) {
        	String[] ids = content.split(",");
        	List<String> list = new ArrayList<>();
        	for(String id: ids) {
        		if(!list.contains(id)) {
        			tradingAccountMonitor.updateAccount(Long.parseLong(id));
        			list.add(id);
        		}
        	}
        } else {
        	tradingAccountMonitor.updateAccount(Long.parseLong(content));
        }
    }
    
    @KafkaListener(topics = {"trader-status-change"})
    public void onTraderStatusChange(List<ConsumerRecord<String, String>> records) {
    	for (int i = 0; i < records.size(); i++) {
			ConsumerRecord<String, String> record = records.get(i);
			JSONObject object = JSON.parseObject(record.value());
			if (object == null) {
                return;
            }
			Long memberId = object.getLong("memberId");
			int isTrader = object.getIntValue("isTrader");
			
			memberService.updateIsTrader(memberId, isTrader);
    	}
    }
    
    @KafkaListener(topics = {"member-transaction-add"})
    public void memberTransactionAdd(String content) {
        logger.info("trmember-transaction-add={}", content);
        if (StringUtils.isEmpty(content)) {
            return;
        }
        JSONObject json = JSON.parseObject(content);
        if (json == null) {
            return;
        }
        memberTransactionService.recordFee(json.getLong("memberId"), json.getIntValue("type"), json.getBigDecimal("amount"));
    }
    
    @KafkaListener(topics = {"exchange-account-change"})
    public void exchangeAccountChange(String content) {
        logger.info("exchange-account-change={}", content);
        if (StringUtils.isEmpty(content)) {
            return;
        }
        if(content.indexOf(",")>0) {
        	String[] ids = content.split(",");
        	List<String> list = new ArrayList<>();
        	for(String id: ids) {
        		if(!list.contains(id)) {
        			exchangeWalletService.updateExchangeAccount(Long.parseLong(id));
        			list.add(id);
        		}
        	}
        } else {
        	exchangeWalletService.updateExchangeAccount(Long.parseLong(content));
        }
    }
    
    @KafkaListener(topics = {"add-exchange-to-members"})
    public void memberExchangeAdd(String content) {
        logger.info("handle add-exchange-to-members,data={}", content);
        if (StringUtils.isEmpty(content)) {
            return;
        }
        JSONObject json = JSON.parseObject(content);
        if(json == null) {
            return ;
        }
        String symbol = json.getString("symbol");
        exchangeWalletService.addCoinforAllMembers(symbol);
    }
}
