package org.dromara.web.service;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.constant.GlobalConstants;
import org.dromara.common.core.domain.model.ForgotLoginBody;
import org.dromara.common.core.exception.user.CaptchaExpireException;
import org.dromara.common.core.exception.user.UserException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.mapper.SysUserMapper;
import org.springframework.stereotype.Service;


@RequiredArgsConstructor
@Service
public class ForgotPasswordService {

    private final SysUserMapper userMapper;


    public boolean forgotPasswordService(ForgotLoginBody loginBody) {
        SysUserVo appUserVo =new SysUserVo();
        if(Validator.isEmail(loginBody.getUsername())){
           userMapper.selectVoOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getEmail, loginBody.getUsername()));
        }else if (Validator.isMobile(loginBody.getUsername())){
            appUserVo = userMapper.selectVoOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getPhonenumber, loginBody.getUsername()));
        }else {
            appUserVo = userMapper.selectVoOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName, loginBody.getUsername()));
        }
        if (ObjectUtil.isNull(appUserVo)){
            throw new UserException("账号未注册");
        }

        boolean validateFlag = validateSmsCode(loginBody.getUsername(), loginBody.getSmsCode());
        if (!validateFlag){
            throw new UserException("验证码无效");
        }

        appUserVo.setPassword(BCrypt.hashpw(loginBody.getPassword()));
        SysUser update = MapstructUtils.convert(appUserVo, SysUser.class);
        userMapper.updateById(update);
        return userMapper.updateById(update) > 0;
    }

    /**
     * 校验短信验证码
     */
    private boolean validateSmsCode(String username, String smsCode) {
        String code = RedisUtils.getCacheObject(GlobalConstants.CAPTCHA_CODE_KEY + username);
        if (StringUtils.isBlank(code)) {
            throw new CaptchaExpireException();
        }
        return code.equals(smsCode);
    }
}
