package com.ruoyi.sms.listener;

import com.ruoyi.common.event.SmsSendEvent;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.sms.core.SmsTemplate;
import com.ruoyi.sms.entity.SmsResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;

@Configuration
@ConditionalOnBean(SmsTemplate.class)
@Slf4j
@RequiredArgsConstructor
public class SendListener {

  private final SmsTemplate template;

  private final ApplicationEventPublisher publisher;

  @EventListener
  @Async
  public void listener(SmsSendEvent event) {
    try {
      SmsResult result = template.send(event.getPhones(), event.getTemplateId(), event.getParam());
      if (log.isInfoEnabled()) {
        log.info("短信发送成功:{}", JsonUtils.toJsonString(event));
      }
      publisher.publishEvent(event.result(result.isSuccess(), result.getMessage(), result.getResponse()));
    } catch (Exception e) {
      if (log.isWarnEnabled()) {
        log.warn("短信发送失败:" + JsonUtils.toJsonString(event), e);
      }
      publisher.publishEvent(event.result(e));
    }
  }
}
