package com.tzy.listener.mq;

import com.alibaba.fastjson2.JSON;
import com.rabbitmq.client.Channel;
import com.tzy.common.constant.Constants;
import com.tzy.common.constant.MqConstans;
import com.tzy.sportcard.api.service.MineApiService;
import com.tzy.sportcard.point.domain.AppUserPointRecord;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;


@Slf4j
@Component
public class UserPointJsonConsumer {

    @Autowired
    private MineApiService mineApiService;

    @RabbitHandler
    @RabbitListener(queuesToDeclare = @Queue(MqConstans.QUEUE_USER_POINT_JSON))
    public void addPointRecord(String pointRecordStr, Channel channel, Message message) throws IOException {
        userPointConsumer(pointRecordStr, channel, message);
    }

    private void userPointConsumer(String pointRecordStr, Channel channel, Message message) throws IOException {
        try {
            AppUserPointRecord pointRecord = JSON.parseObject(pointRecordStr, AppUserPointRecord.class);
            mineApiService.addUserPoint(pointRecord);
            if(Constants.POINT_TYPE_GOODS.equals(pointRecord.getType())){
                pointRecord.setType(Constants.POINT_TYPE_USER_GROWTH);
                mineApiService.addUserPoint(pointRecord);
            }
        } catch (Exception e) {
            log.info("积分记录添加异常,参数:{},异常", pointRecordStr, e);
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }





}
