package com.fuyuanshen.app.service;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fuyuanshen.app.domain.AppUser;
import com.fuyuanshen.app.mapper.AppUserMapper;
import com.fuyuanshen.app.model.AppRegisterBody;
import com.fuyuanshen.app.model.AppUpdatePasswordBody;
import com.fuyuanshen.common.core.constant.Constants;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.core.domain.model.RegisterBody;
import com.fuyuanshen.common.core.enums.UserType;
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.satoken.utils.AppLoginHelper;
import com.fuyuanshen.common.tenant.helper.TenantHelper;
import com.fuyuanshen.common.web.config.properties.CaptchaProperties;
import com.fuyuanshen.system.domain.SysUser;
import com.fuyuanshen.system.domain.bo.SysUserBo;
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 IAppUserService userService;
    private final AppUserMapper userMapper;

    /**
     * 注册
     */
    public void register(AppRegisterBody registerBody) {
        String tenantId = registerBody.getTenantId();
        String username = registerBody.getPhonenumber();
        String password = registerBody.getPassword();

        boolean codeValidate = validateRegisterSmsCode(tenantId, username, registerBody.getSmsCode());
        if (!codeValidate) {
            throw new CaptchaException();
        }

        // 校验用户类型是否存在
        String userType = UserType.APP_USER.getUserType();

        boolean exist = TenantHelper.dynamic(tenantId, () -> {
            return userMapper.exists(new LambdaQueryWrapper<AppUser>()
                .eq(AppUser::getUserName, username));
        });
        if (exist) {
            throw new UserException("user.register.save.error", username);
        }
        AppUser appUser = new AppUser();
        appUser.setPhonenumber(username);
        appUser.setUserName(username);
        appUser.setStatus("0");
        appUser.setLoginDate(new Date());
        appUser.setLoginIp(ServletUtils.getClientIP());
        appUser.setTenantId(tenantId);
        appUser.setPassword(password);
        appUser.setUserType(userType);
        userMapper.insert(appUser);
        recordLogininfor(tenantId, username, Constants.REGISTER, MessageUtils.message("user.register.success"));
    }

    /**
     * 注册校验短信验证码
     */
    private boolean validateRegisterSmsCode(String tenantId, String phonenumber, String smsCode) {
        String code = RedisUtils.getCacheObject(GlobalConstants.REGISTER_CODE_KEY + phonenumber);
        if (StringUtils.isBlank(code)) {
            recordLogininfor(tenantId, phonenumber, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"));
            throw new CaptchaExpireException();
        }
        return code.equals(smsCode);
    }

    /**
     * 忘记密码校验验证码
     */
    private boolean validateForgetPasswordCode(String tenantId, String phonenumber, String smsCode) {
        String code = RedisUtils.getCacheObject(GlobalConstants.FORGET_PASSWORD_CODE_KEY + phonenumber);
        if (StringUtils.isBlank(code)) {
            recordLogininfor(tenantId, phonenumber, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"));
            throw new CaptchaExpireException();
        }
        return code.equals(smsCode);
    }

    /**
     * 记录登录信息
     *
     * @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);
    }

    public void forgetPassword(AppRegisterBody registerBody) {
        String tenantId = registerBody.getTenantId();
        String username = registerBody.getPhonenumber();
        String password = registerBody.getPassword();
        boolean codeValidate = validateForgetPasswordCode(tenantId, username, registerBody.getSmsCode());
        if (!codeValidate) {
            throw new CaptchaException();
        }
        boolean exist = TenantHelper.dynamic(tenantId, () -> {
            return userMapper.exists(new LambdaQueryWrapper<AppUser>()
                    .eq(AppUser::getUserName, username));
        });
        if (!exist) {
            throw new UserException("用户不存在");
        }

        UpdateWrapper<AppUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_name", username)
                .set("password", password);
        userMapper.update(updateWrapper);
    }

    public void updatePassword(AppUpdatePasswordBody body) {
        String username = AppLoginHelper.getUsername();
        String password = body.getPassword();
        UpdateWrapper<AppUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_name", username)
                .set("password", password);
        userMapper.update(updateWrapper);
    }
}
