package com.cftech.pay.api.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.rocketmq.client.consumer.DefaultMQPushConsumer;
import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import com.alibaba.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import com.alibaba.rocketmq.client.exception.MQClientException;
import com.alibaba.rocketmq.common.message.MessageExt;
import com.cftech.core.util.DateFormatUtils;
import com.cftech.pay.api.com.cftech.pay.api.entity.WeiXinPayBillEntity;
import com.cftech.pay.api.impl.WeiXinPayImpl;
import com.cftech.pay.model.PayRecord;
import com.cftech.pay.service.PayRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by user on 2017/5/11.
 */
@Component
@Slf4j
public class WeiXinPayConsumer implements ApplicationListener<ContextRefreshedEvent>
{

    private static AtomicInteger ai = new AtomicInteger();

    @Autowired
    private WeiXinPayImpl weiXinPay;

    @Autowired
    private PayRecordService payRecordService;


    private void onInit() {
        log.info("----MQ初始化开始----");
        // TODO Auto-generated method stub
        DefaultMQPushConsumer pushConsumer = new DefaultMQPushConsumer("ConsumerGroupName");
        pushConsumer.setNamesrvAddr("192.168.220.134:9876;192.168.220.135:9876");
        try {
            pushConsumer.subscribe("TopicTest1", "*");
            pushConsumer.setMessageListener(new MessageListenerConcurrently() {
                @Override
                public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> messages,
                                                                ConsumeConcurrentlyContext arg1) {
                    for(MessageExt message:messages)
                    {
                        WeiXinPayBillEntity weiXinPayBillEntity = JSONObject.toJavaObject(JSONObject.parseObject(new String(message.getBody())), WeiXinPayBillEntity.class);
                        PayRecord payRecord = new PayRecord();
                        payRecord.setSrcid(weiXinPayBillEntity.getAppid());
                        payRecord.setSrctype("微信");
                        payRecord.setBank_type(weiXinPayBillEntity.getBank_type());
                        payRecord.setAttach(weiXinPayBillEntity.getAttach());
                        payRecord.setCash_fee(weiXinPayBillEntity.getCash_fee());
                        payRecord.setErr_code(weiXinPayBillEntity.getErr_code());
                        payRecord.setErr_code_des(weiXinPayBillEntity.getErr_code_des());
                        payRecord.setFee_type(weiXinPayBillEntity.getFee_type());
                        payRecord.setTransaction_id(weiXinPayBillEntity.getTransaction_id());
                        payRecord.setCash_fee_type(weiXinPayBillEntity.getCash_fee_type());
                        payRecord.setIs_subscribe(weiXinPayBillEntity.getIs_subscribe());
                        payRecord.setMch_id(weiXinPayBillEntity.getMch_id());
                        payRecord.setOut_trade_no(weiXinPayBillEntity.getOut_trade_no());
                        payRecord.setOpenid(weiXinPayBillEntity.getOpenid());
                        payRecord.setTotal_fee(weiXinPayBillEntity.getTotal_fee());
                        payRecord.setTrade_type(weiXinPayBillEntity.getTrade_type());
                        payRecord.setTime_end(DateFormatUtils.formatDate(weiXinPayBillEntity.getTime_end(),"yyyMMddHHmmss"));
                        payRecordService.save(payRecord);
                    }
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
            });
            pushConsumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
        log.info("---MQ执行初始化结束----");
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
      //  log.info("----容器执行初始化开始----");
        if(contextRefreshedEvent.getApplicationContext().getParent() == null && "Root WebApplicationContext".equals(contextRefreshedEvent.getApplicationContext().getDisplayName())){//root application context 没有parent，他就是老大.
            if(ai.intValue()==0)
            {
                onInit();
                ai.incrementAndGet();
            }

        }
     //   log.info("---容器执行初始化结束----");
    }
}
