package com.playlet.web.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.playlet.common.constant.RedisConstants;
import com.playlet.web.core.config.SmsConfig;
import com.playlet.web.service.SmsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SmsServiceImpl implements SmsService {

    private final SmsConfig smsConfig;

    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public void sendSmsCode(String phone) throws Exception{
        // 短信验证码
        String alreadyCode = stringRedisTemplate.opsForValue().get(RedisConstants.SMS_CODE_PREFIX + phone);
        if(StringUtils.isNotEmpty(alreadyCode)){
            throw new Exception("已发的验证码还在有效期!");
        }
        String code = String.valueOf((int)((Math.random() * 9 + 1) * Math.pow(10,5)));
        // 工程代码泄露可能会导致AccessKey泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html
        Client client = createClient(smsConfig.getAccessKeyId(), smsConfig.getAccessKeySecret());
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(smsConfig.getSignName())
                .setTemplateCode(smsConfig.getTemplateCode())
                .setPhoneNumbers(phone)
                .setTemplateParam("{\"code\":"+ code +"}");
        RuntimeOptions runtime = new RuntimeOptions();
        // 复制代码运行请自行打印 API 的返回值
        SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
        log.info("发送给{}短信响应为{}", phone, sendSmsResponse);
        stringRedisTemplate.opsForValue().set(RedisConstants.SMS_CODE_PREFIX + phone, code, 300, TimeUnit.SECONDS);
    }

    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId key
     * @param accessKeySecret 密钥
     * @throws Exception 异常信息
     */
    public static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }
}
