package com.fzm.mall.server.front.mq.consumer;

import cn.fzm.chain.simplesdk.constant.TxStatusEnum;
import cn.fzm.chain.simplesdk.model.TxResult;
import com.alibaba.fastjson.JSON;
import com.fzm.mall.server.front.asset.model.UserAsset;
import com.fzm.mall.server.front.asset.model.UserAssetRecord;
import com.fzm.mall.server.front.asset.service.IUserAssetRecordService;
import com.fzm.mall.server.front.asset.service.IUserAssetService;
import com.fzm.mall.server.front.constant.MALLGlobalConfig;
import com.fzm.mall.server.front.enums.QueueTTLTypeEnum;
import com.fzm.mall.server.front.mq.MsgProducer;
import com.fzm.mall.server.front.order.model.po.TranDto;
import com.fzm.mall.server.front.user.service.IRedisService;
import com.fzm.mall.server.front.util.ChainUtil;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 提币确认
 * 
 * @author lgang
 * @date 创建时间：2018年12月13日 下午3:01:41
 *
 */
@Slf4j
@Component
public class WithdrawConsumer {

	
	@Autowired
	private ChainUtil chainUtil;
	
	@Autowired
	private MsgProducer msgProducer;

	@Autowired
	private IUserAssetRecordService userAssetRecordService;

	@Autowired
	private IUserAssetService userAssetService;

	@Autowired
	private IRedisService redisService;
	
	@RabbitListener(bindings = {
	        @QueueBinding(value = @Queue(value = MALLGlobalConfig.projectMq+".withdraw.queue"), exchange = @Exchange(value = MALLGlobalConfig.projectMq+"-withdraw-exchange"), key = MALLGlobalConfig.projectMq+".withdraw.key") })
	public void receiver(String message) {
		try {
			if(StringUtil.isNullOrEmpty(message)) {
				return;
			}
			TranDto tranDto = JSON.parseObject(message, TranDto.class);
			if(tranDto == null) {
				log.error("WithdrawConsumer :" +message +"-tranDto == null");
				return;
			}
			TxResult txResult = chainUtil.confirmTxWithTxHash(tranDto.getHash());
			TxStatusEnum txStatusEnum = txResult.getStatus();
			System.out.println(txResult.getErrMsg());
			switch (txStatusEnum) {
			case SUCCESS:
				commit(tranDto);
				break;
			case FAIL:
				rollBack(tranDto);
				break;
			default:
				resend(tranDto);
				break;
			}
			
		} catch (Exception e) {
			StackTraceElement[] stackTrace = e.getStackTrace();
			StringBuilder sb = new StringBuilder();
			for (StackTraceElement stackTraceElement : stackTrace) {
				sb.append(stackTraceElement.getFileName()).append("*").append(stackTraceElement.getLineNumber()).append("*");
			}
			log.error("WithdrawConsumer-message:"+message+"-e"+sb.toString());
			msgProducer.sendTTL(message, QueueTTLTypeEnum.CONFIRM_WITHDRAW_TTL,
			        5*1000);
		}
		
	}

	@Transactional
	private void commit(TranDto tranDto) {
		//转让
		if(tranDto.getType()!=null&&tranDto.getType() == 1){
			return;
		}
		Long updateTime = tranDto.getUpdateTime();
		if(updateTime == null||updateTime == 0) {
			updateTime =System.currentTimeMillis();
		}
		//回收确认
		if(tranDto.getDelivery() == null) {
			UserAssetRecord assetRecord = userAssetRecordService.getById(tranDto.getId());
			assetRecord.setStatus(2);
			userAssetRecordService.updateById(assetRecord);
			//减去冻结资产
			UserAsset assets = userAssetService.getAmountByUidAndCoinForUpdate(assetRecord.getUid(), assetRecord.getCoin());
			int i  = userAssetService.deleteFrozen(assets.getId(),tranDto.getAmount());
			return;
		}
		//直接提货
		if(tranDto.getDelivery()) {
			//自提
			if(tranDto.getDeliveryMode() == 1) {
				//变更资产记录状态
			//邮寄
			}else {

				msgProducer.sendTTL(JSON.toJSONString(tranDto), QueueTTLTypeEnum.CONFIRM_WITHDRAW_TTL,
				        5*1000);
				return;
			}
		}
		//购买不提货
		if(!tranDto.getDelivery()) {
			//变更资产记录状态

			return;
		}
	}

	@Transactional
	private void rollBack(TranDto tranDto) {
		log.error("withdraw fail,hash:" + tranDto.getHash());
		/*//tranDto.setCoin("YHTY");
		if(StringUtil.isNullOrEmpty(tranDto.getKey())){
			tranDto.setKey(tranDto.getHash());
			redisService.setKey(tranDto.getKey(),"1");
		}else{
			redisService.getKey(tranDto.getKey());
		}
		String hash = paraChainUtil.evmTransfer(tranDto.getToAddr(), tranDto.getFromAddr(),Long.valueOf(tranDto.getCoin()),tranDto.getAmount().longValue());
		tranDto.setHash(hash);

		msgProducer.sendTTL(JSON.toJSONString(tranDto), QueueTTLTypeEnum.CONFIRM_WITHDRAW_TTL,
		        5*1000);*/
		return;
	}

	private void resend(TranDto tranDto) {
		log.error("withdraw queue resend:" + tranDto);
		if(StringUtil.isNullOrEmpty(tranDto.getHash())) {
			String hash = chainUtil.evmTransfer(tranDto.getToAddr(), tranDto.getFromAddr(),Long.valueOf(tranDto.getCoin()),tranDto.getAmount().longValue());
			tranDto.setHash(hash);
		}
		msgProducer.sendTTL(JSON.toJSONString(tranDto), QueueTTLTypeEnum.CONFIRM_WITHDRAW_TTL,
		        5*1000);
	}
	
}
