package com.muchinfo.mtp3century.listener;

import com.muchinfo.mtp.proto.AkernelMI1.AccountFundInfoRsp;
import com.muchinfo.mtp.proto.AkernelMI1.ExAccountCommandRsp;
import com.muchinfo.mtp.proto.AkernelMI1.ExAccountReckonRsp;
import com.muchinfo.mtp3common.enumtype.FunCodeConstants;
import com.muchinfo.mtp3common.vo.Calculator;
import com.muchinfo.mtp3common.vo.ProtoHelper;
import com.muchinfo.mtp3common.utils.SerialNumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class ExInOutMoneyListener implements MessageListener {
	private final static Logger logger = LoggerFactory.getLogger(ExInOutMoneyListener.class);
	
	@Override
	@RabbitListener(queues = "exInOutMoneyQueue")
	public void onMessage(Message message) {
		logger.debug("GET MESSAGE---------------ExInOutMoneyListener---------------------");
		byte[] msgBody = message.getBody();
		int funCode = ProtoHelper.getFunCodeForNTAS(msgBody);
		
		try{
			byte[] body = ProtoHelper.getProtoForNTAS(msgBody);
			switch (funCode){
			case FunCodeConstants.FunCode_Trade_ExAccountCommandRsp:{
				ExAccountCommandRsp rsp = ExAccountCommandRsp.parseFrom(body);
				logger.debug(rsp.toString());
				Long uuid = rsp.getRelatedOrderId();
				SerialNumberUtils.putMessageMap(uuid, rsp);
				Calculator c = SerialNumberUtils.lockMap.get(uuid);
				if(c != null){
					c.start();
				}
				break;
			}
			case FunCodeConstants.FunCode_Trade_AccountFundInfoRsp:{
				AccountFundInfoRsp rsp = AccountFundInfoRsp.parseFrom(body);
				logger.debug(rsp.toString());
				Long uuid = rsp.getOrderId();
				SerialNumberUtils.putMessageMap(uuid, rsp);
				Calculator c = SerialNumberUtils.lockMap.get(uuid);
				if(c != null){
					c.start();
				}
				break;
			}
			case FunCodeConstants.FunCode_Trade_ExAccountReckonRsp:{
				ExAccountReckonRsp rsp = ExAccountReckonRsp.parseFrom(body);
        		logger.debug(rsp.toString());
				Long uuid = Long.valueOf(rsp.getHeader().getUUID());
				SerialNumberUtils.putMessageMap(uuid, rsp);
				Calculator c = SerialNumberUtils.lockMap.remove(uuid);
				if(c != null){
					c.start();
				}
				break;
			}
			default:
				logger.debug("[" + funCode + "]未处理或非 ExInOutMoneyListener 列对的消息");
				break;
			}
		}catch(Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
	}
	
}
