package com.nokia.sms.service;

import java.util.Arrays;
import java.util.Date;
import java.util.UUID;

import org.springframework.stereotype.Service;

import com.nokia.sms.dao.SmsDao;
import com.nokia.sms.pojo.Sms;
import com.nokia.sms.sgip.message.SendResult;
import com.nokia.sms.sgip.mt.client.MTClient;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class SgipSmsService {

    private final SmsDao smsDao;

    public SgipSmsService(SmsDao smsDao) {
        this.smsDao = smsDao;
    }

    public String sendMessage(Sms sms) {
        log.debug("准备发送短信: {}", sms);
        sms.setId(UUID.randomUUID().toString());
        sms.setSendTime(new Date());
        try {
            // 获取单例的MTClient
            MTClient client = MTClient.getInstance();
            // 发送短信
            SendResult[] results = client.sendMessage(sms.getPhoneNumbers(), sms.getContent(), sms.getScheduleTime());
            log.debug("短信已成功发送, 发送结果: {}", Arrays.toString(results));
            // 销毁应用
            client.dispose();
            sms.setResult(Arrays.toString(results));
            sms.setStatus("已发送到短信网关");
            return "成功";
        } catch (Exception e) {
            log.error("短信发送失败, 短信: {}, 错误信息: {}", sms, e.getMessage());
            sms.setStatus("发送到短信网关失败");
            e.printStackTrace();
            return sms.getStatus();
        } finally {
            smsDao.insert(sms);
        }
    }
}
