package com.czg.service.account.service.impl;

import cn.hutool.core.util.StrUtil;
import com.czg.account.entity.SysUser;
import com.czg.account.service.CommonService;
import com.czg.account.service.SysUserService;
import com.czg.config.RedisCst;
import com.czg.exception.CzgException;
import com.czg.sa.StpKit;
import com.czg.service.RedisService;
import com.czg.system.service.SmsService;
import com.czg.utils.CzgRandomUtils;
import jakarta.annotation.Resource;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

/**
 * @author Administrator
 */
@Service
public class CommonServiceImpl implements CommonService {
    @DubboReference
    private SmsService smsService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private RedisService redisService;

    @Override
    public Boolean sendSms(String type) {
        SysUser sysUser = sysUserService.queryChain().eq(SysUser::getId, StpKit.USER.getLoginIdAsLong()).one();
        if (StrUtil.isBlank(sysUser.getPhone())) {
            throw new CzgException("账号未绑定手机号");
        }
        String key = RedisCst.SMS_CODE + sysUser.getPhone() + ":" + type;
        Object val = redisService.get(key);
        if (val != null) {
            throw new CzgException("请勿频繁获取");
        }
        String code = CzgRandomUtils.randomNumber(6,true);
        redisService.set(key, code, 300);
        smsService.sendCode(sysUser.getPhone(), code);
        return true;
    }

    @Override
    public Boolean checkSmsCode(String type, String code) {
        SysUser sysUser = sysUserService.queryChain().eq(SysUser::getId, StpKit.USER.getLoginIdAsLong()).one();
        if (StrUtil.isBlank(sysUser.getPhone())) {
            throw new CzgException("账号未绑定手机号");
        }
        Object value = redisService.get(RedisCst.SMS_CODE + sysUser.getPhone() + ":" + type);
        return code.equals(value);
    }
}
