package com.cool.store.service.sms.impl;

import com.cool.store.enums.SmsCodeTypeEnum;
import com.cool.store.enums.SmsNoticeTypeEnum;
import com.cool.store.response.ResponseResult;
import com.cool.store.service.impl.CommonService;
import com.cool.store.service.sms.AliyunSmsService;
import com.cool.store.utils.MobileUtil;
import com.cool.store.utils.RedisUtilPool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

/**
 * @author zhangchenbiao
 * @FileName: AliyunSmsServiceImpl
 * @Description: 发送短信
 * @date 2021-07-23 11:37
 */
@Service
@Slf4j
public class AliyunSmsServiceImpl implements AliyunSmsService {

    @Resource
    private RedisUtilPool redisUtilPool;
    @Resource
    private CommonService commonService;

    @Override
    public ResponseResult sendSmsCode(String mobile, SmsCodeTypeEnum codeType) {
        String smsCodeKey = codeType + ":" + mobile;
        String smsCode = getRandNum();
        String templateCode = MobileUtil.getSmsTemplateCode(mobile);

        Map<String, String> templateParamMap = new HashMap<>();
        templateParamMap.put("code", smsCode);
        commonService.sendSms(mobile, templateCode, templateParamMap);
        redisUtilPool.setString(smsCodeKey, smsCode, codeType.getCacheSeconds());

        return ResponseResult.success(true);
    }

    @Override
    public void sendNotice(String mobile, SmsNoticeTypeEnum type) {
        commonService.privateSendSms(Collections.singletonList(mobile), type.getTemplateCode(), type.getSmsSign().getSignName(), null);
    }

    public static String getRandNum() {
        return String.valueOf((int) ((Math.random() * 9 + 1) * Math.pow(10, 5)));
    }
}
