package org.springblade.auth.sms;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springblade.auth.model.SmsLogin;
import org.springblade.message.MsgTemplate;
import org.springblade.message.model.MsgResponse;
import org.springblade.message.model.SmsInfo;
import org.springblade.message.model.SmsMsgRequest;
import org.springblade.message.sms.AliyunSmsTemplate;
import org.springblade.message.sms.QiniuSmsTemplate;
import org.springblade.message.sms.TencentSmsTemplate;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
@Slf4j
public class SmsLoginAuth {

    public String sendMsg(SmsInfo smsInfo, SmsLogin login){

        String msg;

        // 使用随机数生成短信验证码
        Random randObj = new Random();
        String smsCode = Integer.toString(100000 + randObj.nextInt(900000));
        MsgTemplate msgTemplate;
        if(login.getCategory() == 0) { //阿里云
            msgTemplate = SpringUtil.getBean(AliyunSmsTemplate.class);
        }else if(login.getCategory() == 1) { //七牛云
            msgTemplate = SpringUtil.getBean(QiniuSmsTemplate.class);
        }else {
            msgTemplate = SpringUtil.getBean(TencentSmsTemplate.class);
        }
        SmsMsgRequest smsMsgRequest = new SmsMsgRequest();

        Map<String, String> params = new HashMap<>();
        if (StrUtil.isNotEmpty(login.getTemplateParams())) {
            String templateParams = login.getTemplateParams();
            if (login.getCategory() == 2){
                String[] s = templateParams.split(",");
                params.put(s[0],smsCode);
                params.put(s[1],"5");
            } else {
                params.put(login.getTemplateParams(),smsCode);
            }
        }


        smsMsgRequest.setSmsInfo(smsInfo);
        smsMsgRequest.setParams(params);
        smsMsgRequest.setPhones(Arrays.asList(new String[]{login.getPhone()}));
        MsgResponse msgResponse = msgTemplate.sendSmsMessage(smsMsgRequest);

        if (msgResponse.isSuccess()) {
            msg = "200,"+smsCode;
        } else {
           msg = "500";
        }

        return msg;
    }
}
