package com.liquidnet.service.consumer.base.receiver;

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.liquidnet.common.sms.processor.SmsProcessor;
import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.base.SmsMessage;
import com.liquidnet.service.base.constant.MQConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.stream.StreamRecords;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;

@Slf4j
@Component
public class ConsumerCommonSmsNoticeReceiver extends AbstractBizRedisReceiver {
    @Resource
    private SmsProcessor smsProcessor;

    @Override
    protected boolean consumerMessageHandler(String msg) {
        boolean aBoolean = false;
        try {
            SmsMessage smsMessage = JsonUtils.fromJson(msg, SmsMessage.class);
//            aBoolean = smsProcessor.send(smsMessage.getPhone(), smsMessage.getSignName(), smsMessage.getTemplateCode(), smsMessage.getTemplateParam().toString());
            ObjectNode templateParam = smsMessage.getTemplateParam();
            aBoolean = smsProcessor.send(smsMessage.getPhone(), smsMessage.getSignName(), smsMessage.getTemplateCode(), null == templateParam ? "" : templateParam.toString());
        } catch (Exception e) {
            log.error("CONSUMER MSG EX_HANDLE ==> [{}]:{}", this.getRedisStreamKey(), msg, e);
        } finally {
            if (!aBoolean) {
                HashMap<String, String> map = CollectionUtil.mapStringString();
                map.put("message", msg);
                stringRedisTemplate.opsForStream().add(StreamRecords.mapBacked(map).withStreamKey(this.getRedisStreamKey()));
            }
        }
        return aBoolean;
    }

    @Override
    protected String getRedisStreamKey() {
        return MQConst.KylinQueue.SMS_NOTICE.getKey();
    }

    @Override
    protected String getRedisStreamGroup() {
        return MQConst.KylinQueue.SMS_NOTICE.getGroup();
    }
}
