package cn.ezhizao.framework.security.service;

import cn.ezhizao.common.constant.CacheConstants;
import cn.ezhizao.common.constant.Constants;
import cn.ezhizao.common.constant.UserConstants;
import cn.ezhizao.common.exception.user.CaptchaException;
import cn.ezhizao.common.exception.user.CaptchaExpireException;
import cn.ezhizao.common.utils.MessageUtils;
import cn.ezhizao.common.utils.SecurityUtils;
import cn.ezhizao.common.utils.StringUtils;
import cn.ezhizao.framework.manager.AsyncManager;
import cn.ezhizao.framework.manager.factory.AsyncFactory;
import cn.ezhizao.framework.redis.RedisCache;
import cn.ezhizao.framework.security.RegisterBody;
import cn.ezhizao.project.system.domain.SysUser;
import cn.ezhizao.project.system.domain.SysUserRole;
import cn.ezhizao.project.system.mapper.SysUserRoleMapper;
import cn.ezhizao.project.system.service.ISysConfigService;
import cn.ezhizao.project.system.service.ISysUserService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 注册校验方法
 *
 * @author ruoyi
 */
@Component
public class SysRegisterService
{
    @Resource
    private ISysUserService userService;

    @Resource
    private ISysConfigService configService;
    @Resource
    private RedisCache redisCache;

    @Resource
    SysUserRoleMapper userRoleMapper;


    /**
     * 注册
     */
    public String register(RegisterBody registerBody)
    {
        String  msg = "",
                username = registerBody.getUsername(),
                password = registerBody.getPassword(),
                deptCode = registerBody.getCreditCode(),
                phoneNumber = registerBody.getPhoneNumber(),
                code = registerBody.getCode();
        Long roleId = Long.parseLong(registerBody.getRole());
        // 验证码开关
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            validateCaptcha(phoneNumber, code);
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setPhoneNumber(phoneNumber);
        sysUser.setUserType("01");

            if (StringUtils.isEmpty(username)) {
                msg = "用户名不能为空";
            } else if (StringUtils.isEmpty(password)) {
                msg = "用户密码不能为空";
            } else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                    || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
                msg = "账户长度必须在2到20个字符之间";
            } else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                    || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
                msg = "密码长度必须在5到20个字符之间";
            } else if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(sysUser))) {
                msg = "注册账号已存在";
            }else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(sysUser))) {
                msg = "注册手机号已存在";
            } else {
                sysUser.setNickName(username);
                sysUser.setPassword(SecurityUtils.encryptPassword(password));

                SysUserRole sysUserRoleAdmin = new SysUserRole();
                sysUserRoleAdmin.setUserId(sysUser.getUserId());
                sysUserRoleAdmin.setRoleId(roleId);
                List<SysUserRole> sysUserRoles = new ArrayList<>();
                sysUserRoles.add(sysUserRoleAdmin);
                userRoleMapper.batchUserRole(sysUserRoles);

                boolean regFlag = userService.registerUser(sysUser);

                if (!regFlag) {
                    msg = "注册失败,请联系系统管理人员";
                } else {
                    redisCache.deleteObject(phoneNumber);
                    AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success")));
                }
            }
        return msg;
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            throw new CaptchaException();
        }
    }

    /**
     * 校验短信验证码
     * @param key
     */
    public void validateCaptcha(String key,String value)
    {
        String verifyCode = redisCache.getCacheObject(key);
        if (verifyCode == null)
        {
            throw new CaptchaExpireException();
        }
        if (!value.equalsIgnoreCase(verifyCode))
        {
            throw new CaptchaException();
        }
    }
}
