package com.ruoyi.web.modules.app.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.modules.app.domain.AppUserRegisterBody;
import com.ruoyi.web.modules.app.service.IAppUserRegisterService;
import com.ruoyi.web.modules.app.support.AppUserRegisterRules;

/**
 * 小程序用户注册实现
 */
@Service
public class AppUserRegisterServiceImpl implements IAppUserRegisterService
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Override
    public boolean isUsernameAvailable(String userName)
    {
        String msg = validateUserNameFormat(userName);
        if (msg != null)
        {
            throw new ServiceException(msg);
        }
        SysUser probe = new SysUser();
        probe.setUserName(userName.trim());
        return userService.checkUserNameUnique(probe);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long register(AppUserRegisterBody body)
    {
        String nickName = body.getNickName().trim();
        String userName = body.getUserName().trim();
        String password = body.getPassword();

        String userNameMsg = validateUserNameFormat(userName);
        if (userNameMsg != null)
        {
            throw new ServiceException(userNameMsg);
        }
        if (StringUtils.isEmpty(nickName))
        {
            throw new ServiceException("用户昵称不能为空");
        }
        if (nickName.length() > 30)
        {
            throw new ServiceException("用户昵称长度不能超过30个字符");
        }
        if (StringUtils.isEmpty(password))
        {
            throw new ServiceException("用户密码不能为空");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            throw new ServiceException("密码长度必须在5到20个字符之间");
        }

        SysUser probe = new SysUser();
        probe.setUserName(userName);
        if (!userService.checkUserNameUnique(probe))
        {
            throw new ServiceException("用户名'" + userName + "'已被占用");
        }

        if (roleService.selectRoleById(AppUserRegisterRules.DEFAULT_ROLE_ID) == null)
        {
            throw new ServiceException("默认角色不存在，请联系管理员");
        }

        SysUser user = new SysUser();
        user.setUserName(userName);
        user.setNickName(nickName);
        user.setPassword(SecurityUtils.encryptPassword(password));
        user.setPwdUpdateDate(DateUtils.getNowDate());
        user.setStatus(UserConstants.NORMAL);
        user.setDeptId(AppUserRegisterRules.DEFAULT_DEPT_ID);
        user.setCreateBy(AppUserRegisterRules.CREATE_BY);
        user.setRoleIds(new Long[] { AppUserRegisterRules.DEFAULT_ROLE_ID });

        int rows = userService.insertUser(user);
        if (rows <= 0 || user.getUserId() == null)
        {
            throw new ServiceException("注册失败，请稍后重试");
        }
        return user.getUserId();
    }

    private static String validateUserNameFormat(String userName)
    {
        if (StringUtils.isEmpty(userName))
        {
            return "用户名不能为空";
        }
        String trimmed = userName.trim();
        if (trimmed.length() < UserConstants.USERNAME_MIN_LENGTH
                || trimmed.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            return "账户长度必须在2到20个字符之间";
        }
        return null;
    }
}
