package com.hzs.system.sms.service.impl;

import com.hzs.common.core.constant.SmsConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.EAliSmsTemplate;
import com.hzs.common.core.enums.ESmsTemplate;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.core.utils.VerificationCodeUtil;
import com.hzs.system.sms.service.ISmsService;
import com.hzs.third.sms.ISmsServiceApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Description: 短信服务
 * @author: jiang chao
 * @Time: 2024/8/5 14:34
 * @Classname: SmsServiceImpl
 * @PackageName: com.hzs.system.sms.service.impl
 */
@Slf4j
@Service
public class SmsServiceImpl implements ISmsService {

    @Autowired
    private RedisService redisService;

    @DubboReference
    ISmsServiceApi iSmsServiceApi;

    @Override
    public boolean sendLoginSms(String phoneNumber, EAliSmsTemplate aliSmsTemplate) {
        // 生成4位验证码
        String code = VerificationCodeUtil.createCode();

        R<String> sendR = iSmsServiceApi.sendAliSms(phoneNumber, code, aliSmsTemplate);

        if (sendR.isSuccess()) {
            // 返回成功，验证码放入缓存
            redisService.setCacheObject(ESmsTemplate.VERIFICATION_MANAGE.getCache() + phoneNumber, code, SmsConstants.FAILURE_TIME, TimeUnit.MINUTES);
            return true;
        }
        log.error("发送短信失败：{}", sendR.getMsg());
        return false;
    }

    @Override
    public String checkLoginSms(String phoneNumber, String code) {
        // 短信发送枚举
        ESmsTemplate eSmsTemplate = ESmsTemplate.VERIFICATION_MANAGE;
        // 短信缓存
        String cacheKey = eSmsTemplate.getCache() + phoneNumber;

        Object codeObj = redisService.getCacheObject(cacheKey);
        if (null != codeObj) {
            if (codeObj.toString().equals(code)) {
                // 校验正确之后，删除缓存
                redisService.deleteObject(cacheKey);
                return null;
            } else {
                // 验证码错误
                return "短信验证码错误";
            }
        }
        // 验证码已失效
        return "短信验证码已失效";
    }

}
