package com.itheima.listener;

import com.alibaba.fastjson.JSON;
import com.itheima.domain.MoneyLog;
import com.itheima.service.MoneyLogService;
import com.itheima.service.RedPacketService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/*****
 * @Author: http://www.itheima.com
 * @Description: com.itheima.listener.MoneyListener
 ****/
@Component
public class MoneyListener {

    @Autowired
    private RedPacketService redPacketService;

    @Autowired
    private  RabbitTemplate rabbitTemplate;

    @Autowired
    private MoneyLogService moneyLogService;

    /****
     * 消息监听，实现抢红包操作
     * @param message
     */
    @RabbitListener(queues = {"red.queue"})
    public void moneyList(String message){
        //抢红包
        System.out.println(message);

        //1)将message转成Map获取用户名字
        Map<String,String> userMap = JSON.parseObject(message,Map.class);
        String username = userMap.get("user");
        //2)抢红包->grap()
        Double money = redPacketService.grab();
        if(money!=null && money>0){
            //3)红包金额>0->抢红包成功，记录到数据库
            moneyLogService.add(new MoneyLog(money,username));
        }

        String msg =money>0? "抢红包成功！"+money:"下手太慢！";
        System.out.println(msg);
        //向RabbitMQ发消息
        //封装抢红包信息
        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("user",username);
        resultMap.put("money",money);
        resultMap.put("code",money>0? 200 :204);

        //发送MQ消息
        rabbitTemplate.convertAndSend("","redmessage.queue",JSON.toJSONString(resultMap));
        System.out.println("消息发送成功！");
    }
}
