package com.fuyuanshen.web.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fuyuanshen.app.domain.AppUser;
import com.fuyuanshen.app.domain.vo.AppUserVo;
import com.fuyuanshen.app.mapper.AppUserMapper;
import com.fuyuanshen.common.core.constant.Constants;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.core.domain.model.AppSmsRegisterBody;
import com.fuyuanshen.common.core.exception.BadRequestException;
import com.fuyuanshen.common.core.exception.user.CaptchaException;
import com.fuyuanshen.common.core.exception.user.CaptchaExpireException;
import com.fuyuanshen.common.core.exception.user.UserException;
import com.fuyuanshen.common.core.utils.MessageUtils;
import com.fuyuanshen.common.core.utils.ServletUtils;
import com.fuyuanshen.common.core.utils.SpringUtils;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.log.event.LogininforEvent;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.common.tenant.helper.TenantHelper;
import com.fuyuanshen.common.web.config.properties.CaptchaProperties;
import com.fuyuanshen.system.mapper.SysUserMapper;
import com.fuyuanshen.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 注册校验方法
 *
 * @author Lion Li
 */
@RequiredArgsConstructor
@Service
public class AppRegisterService {

    private final ISysUserService userService;
    private final SysUserMapper userMapper;
    private final CaptchaProperties captchaProperties;
    private final AppUserMapper appUserMapper;

    /**
     * 注册
     */
    public void register(AppSmsRegisterBody registerBody) {
        String phoneNumber = registerBody.getPhoneNumber();
        LambdaQueryWrapper<AppUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppUser::getPhonenumber, phoneNumber);
        AppUserVo appUserVo = appUserMapper.selectVoOne(wrapper);
        if (appUserVo != null) {
            throw new BadRequestException("该手机号已被注册");
        }
        String verificationCode = RedisUtils.getCacheObject(GlobalConstants.CAPTCHA_CODE_KEY + phoneNumber);
        if (verificationCode == null) {
            throw new BadRequestException("验证码已过期");
        }
        if(!registerBody.getVerificationCode().equals(verificationCode)){
            throw new BadRequestException("验证码错误");
        }
        String tenantId = registerBody.getTenantId();
        String username = registerBody.getPhoneNumber();
        String password = registerBody.getPassword();

        AppUser appUser = new AppUser();
        appUser.setUserName(username);
        appUser.setNickName(username);
        appUser.setPhonenumber(phoneNumber);
        appUser.setPassword(password);
        appUser.setUserType("app_user");
        appUser.setTenantId(tenantId);
        appUser.setLoginIp(ServletUtils.getClientIP());
        appUser.setStatus("0");
        appUser.setDelFlag("0");
        appUser.setCreateTime(new Date());


        boolean exist = TenantHelper.dynamic(tenantId, () -> {
            return appUserMapper.exists(new LambdaQueryWrapper<AppUser>()
                .eq(AppUser::getUserName, appUser.getUserName()));
        });
        if (exist) {
            throw new UserException("user.register.save.error", username);
        }
        appUserMapper.insert(appUser);
        recordLogininfor(tenantId, username, Constants.REGISTER, MessageUtils.message("user.register.success"));
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     */
    public void validateCaptcha(String tenantId, String username, String code, String uuid) {
        String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + StringUtils.blankToDefault(uuid, "");
        String captcha = RedisUtils.getCacheObject(verifyKey);
        RedisUtils.deleteObject(verifyKey);
        if (captcha == null) {
            recordLogininfor(tenantId, username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            recordLogininfor(tenantId, username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"));
            throw new CaptchaException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param tenantId 租户ID
     * @param username 用户名
     * @param status   状态
     * @param message  消息内容
     * @return
     */
    private void recordLogininfor(String tenantId, String username, String status, String message) {
        LogininforEvent logininforEvent = new LogininforEvent();
        logininforEvent.setTenantId(tenantId);
        logininforEvent.setUsername(username);
        logininforEvent.setStatus(status);
        logininforEvent.setMessage(message);
        logininforEvent.setRequest(ServletUtils.getRequest());
        SpringUtils.context().publishEvent(logininforEvent);
    }

}
