package com.mcwl.web.controller.rabbitmq.consumer;

import com.alibaba.fastjson.JSON;
import com.mcwl.common.constant.QueueConstants;
import com.mcwl.common.constant.RedisConstants;
import com.mcwl.common.core.domain.model.PhoneLoginBody;
import com.mcwl.common.core.redis.RedisCache;
import com.mcwl.common.utils.uuid.TelSmsUtils;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 手机号登录短信验证码消费者
 *
 * @author DaiZibo
 * @date 2024/12/30
 * @apiNote
 */


@Component
public class CodeConsumer {

    @Value("${mcwl.templateCode}")
    private String templateCode;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @RabbitListener(queues = QueueConstants.CODE_QUEUE)
    public void code(Message message, Channel channel, String msg) {


        if (msg == "") {
            return;
        }
        String messageId = message.getMessageProperties().getMessageId();
        try {
            Long add = redisTemplate.opsForSet().add(RedisConstants.CODE_UUID + messageId, "1");
            redisTemplate.expire(RedisConstants.CODE_UUID + messageId, 2, TimeUnit.MINUTES);
            if (add > 0) {
                PhoneLoginBody phoneLoginBody = JSON.parseObject(msg, PhoneLoginBody.class);

                //发送短信服务
                // 构建 sendDataMap
                Map<String, String> sendDataMap = new HashMap<>();
                sendDataMap.put("code", phoneLoginBody.getCode());
                String s1 = TelSmsUtils.sendSms(phoneLoginBody.getPhone(), templateCode, sendDataMap);


                //手动确认
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            }else {

            }

        } catch (IOException e) {
            //删除标记
            redisTemplate.delete(RedisConstants.CODE_UUID+messageId);
            throw new RuntimeException(e);
        }


    }
}
