package com.yanzhu.testrocketmq.consumer;

import com.yanzhu.testrocketmq.enums.MessageCodeEnum;
import com.yanzhu.testrocketmq.producer.ConsumeException;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 消息监听
 */
@Slf4j
@Component
public class RocketMsgListener implements MessageListenerConcurrently {

    /**
     * 消费消息
     *
     * @param list    msgs.size() >= 1
     *                DefaultMQPushConsumer.consumeMessageBatchMaxSize=1，you can modify here
     *                这里只设置为1，当设置为多个时，list中只要有一条消息消费失败，就会整体重试
     * @param consumeConcurrentlyContext 上下文信息
     * @return 消费状态  成功（CONSUME_SUCCESS）或者 重试 (RECONSUME_LATER)
     */
    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {

        if (!CollectionUtils.isEmpty(list)) {
            for (MessageExt messageExt : list) {
                // 消息内容
                String body = new String(messageExt.getBody());
                log.info("接受到的消息为：{}", body);
                String tags = messageExt.getTags();
                String topic = messageExt.getTopic();
                String msgId = messageExt.getMsgId();
                String keys = messageExt.getKeys();
                int reConsume = messageExt.getReconsumeTimes();
                // 消息已经重试了3次，如果不需要再次消费，则返回成功
                if (reConsume == 3) {
                    // TODO 补偿信息
                    //smsLogService.insertLog(topic, tags, msgId, keys, body, "【" + EnumUtil.getStrMsgByCode(tags, TagsCodeEnum.class) + "】消费失败");
                    log.error("消息重试超过3次，消费失败！");
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
                // 订单超时处理
                if (MessageCodeEnum.ORDER_MESSAGE.getCode().equals(topic)) {
                    if (MessageCodeEnum.ORDER_TIMEOUT_TAG.getCode().equals(tags)) {
//                        //获取订单
//                        DealUserOrder dealUserOrder = pcRemoteDealUserOrderService.selectDealUserOrderByOrderNumber(keys);
//                        if (dealUserOrder != null) {
//                            //订单状态超时未支付关闭订单 处理
//                            if (dealUserOrder.getStatus().equals("1")) {
//                                DealUserOrder dealUserOrders = new DealUserOrder();
//                                dealUserOrders.setOrderId(dealUserOrder.getOrderId());
//                                dealUserOrders.setStatus("4");
//                                pcRemoteDealUserOrderService.updateDealUserOrder(dealUserOrders);
//                                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
//                            }
//                            log.info("Order does not exist.");
//                        }
                        log.info("Consumption success：" + body);
                        DateFormat format =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        log.info("Consumption time：{}", format.format(new Date()));
                    } else {
                        log.info("未匹配到Tag【{}】" + tags);
                    }
                }
            }
        }
        // 消息消费成功
        //ConsumeConcurrentlyStatus.RECONSUME_LATER broker会根据设置的messageDelayLevel发起重试，默认16次
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }

    /**
     * 异常处理
     *
     * @param e 捕获的异常
     * @return 消息消费结果
     */
    private static ConsumeConcurrentlyStatus handleException(final Exception e) {
        Class exceptionClass = e.getClass();
        if (exceptionClass.equals(UnsupportedEncodingException.class)) {
            log.error(e.getMessage());
        } else if (exceptionClass.equals(ConsumeException.class)) {
            log.error(e.getMessage());
        }
        return ConsumeConcurrentlyStatus.RECONSUME_LATER;
    }
}
