package com.ruoyi.web.work.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SendMessage;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.work.domain.dto.SmsDto;
import com.ruoyi.web.work.service.ICommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.rmi.ServerException;
import java.util.concurrent.TimeUnit;

/**
 * @author lsw
 * @date 2024-04-16
 */
@Service
public class CommonServiceImpl implements ICommonService {
    @Autowired
    private RedisCache redisCache;

    @Override
    public AjaxResult sms(SmsDto dto) {
        dto.setPhone(SecurityUtils.getLoginUser().getUser().getPhonenumber());
        String code = StringUtils.getRandomString(6);
        AjaxResult param = new AjaxResult();
        param.put("code", code);
        boolean result = SendMessage.sendSms(dto.getPhone(), "广西承揽时代数据服务", dto.getTemplateCode(), JSONUtils.toJSONString(param));
        if (result) {
            redisCache.setCacheObject(CacheConstants.APP_CODE_KEY + dto.getPhone(), code, 5, TimeUnit.MINUTES);
            return AjaxResult.success("发送成功");
        }
        return AjaxResult.error("短信发送失败");
    }

    @Override
    public void verifyCode(String phone, String code) throws ServerException {
        if (redisCache.getCacheObject(CacheConstants.APP_CODE_KEY + phone) == null) {
            throw new ServerException("验证码已过期");
        }
        if (!code.equals(redisCache.getCacheObject(CacheConstants.APP_CODE_KEY + phone))) {
            throw new ServerException("验证码错误");
        }
        redisCache.deleteObject(CacheConstants.APP_CODE_KEY + phone);
    }
}
