package com.xingxi.api.configuration;

import cn.binarywang.wx.miniapp.api.WxMaMsgService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.rabbitmq.client.Channel;
import com.xingxi.common.mq.bo.wxmessage.WxSubscribeMessageBO;
import com.xingxi.common.mq.constant.WxSubscribeMessageMqKey;
import com.xingxi.common.mq.core.AbstractRabbitConsumer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
class WxSubscribeMessageConsumer extends AbstractRabbitConsumer {
    private final WxMaService wxMaService;

    @Bean
    @Override
    protected List<Binding> getBindingList() {
        return Lists.newArrayList(
                this.bind(WxSubscribeMessageMqKey.EDIT_EXCHANGE,
                        WxSubscribeMessageMqKey.EDIT_QUEUE_FOR_WXSUBSCRIBEMESSAGE_PUBLISH,
                        WxSubscribeMessageMqKey.EDIT_ROUTE_FOR_WXSUBSCRIBEMESSAGE_PUBLISH));
    }


    @RabbitListener(queues = WxSubscribeMessageMqKey.EDIT_QUEUE_FOR_WXSUBSCRIBEMESSAGE_PUBLISH)
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        this.convertMessage(message, channel);
    }


    @Override
    public boolean execute(String body, Channel channel, Message message) throws Exception {
        log.debug("发布微信订阅消息[{}]", body);
        WxSubscribeMessageBO wxSubscribeMessageBO = JSON.parseObject(body, WxSubscribeMessageBO.class);
        WxMaSubscribeMessage subscribeMessage = new WxMaSubscribeMessage();
        BeanUtils.copyProperties(wxSubscribeMessageBO, subscribeMessage);

        try {
            WxMaMsgService msgService = wxMaService.getMsgService();
            msgService.sendSubscribeMsg(subscribeMessage);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


}
