package com.ghy.framework.shiro.service;

import com.ghy.common.core.domain.dto.SysUserAddDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ghy.common.constant.Constants;
import com.ghy.common.constant.ShiroConstants;
import com.ghy.common.constant.UserConstants;
import com.ghy.common.core.domain.entity.SysUser;
import com.ghy.common.utils.DateUtils;
import com.ghy.common.utils.MessageUtils;
import com.ghy.common.utils.ServletUtils;
import com.ghy.common.utils.ShiroUtils;
import com.ghy.framework.manager.AsyncManager;
import com.ghy.framework.manager.factory.AsyncFactory;
import com.ghy.system.service.ISysUserService;
import org.springframework.transaction.annotation.Transactional;

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

    @Autowired
    private SysPasswordService passwordService;

    /**
     * 注册
     */
    @Transactional(rollbackFor = Exception.class)
    public String register(SysUserAddDTO userAddDTO) {
        String msg = "";
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userAddDTO, sysUser);

        if (ShiroConstants.CAPTCHA_ERROR.equals(ServletUtils.getRequest().getAttribute(ShiroConstants.CURRENT_CAPTCHA))) {
            msg = "验证码错误";
        } else if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(sysUser.getLoginName()))) {
            msg = "保存用户'" + userAddDTO.getLoginName() + "'失败，注册账号已存在";
        } else if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkPhoneUnique(sysUser))) {
            msg = "保存手机号码'" + userAddDTO.getPhonenumber() + "'失败，该手机号码已被注册";
        } else {
            sysUser.setDeptId(101L);
            sysUser.setPwdUpdateDate(DateUtils.getNowDate());
            sysUser.setUserName(userAddDTO.getLoginName());
            sysUser.setSalt(ShiroUtils.randomSalt());
            sysUser.setPassword(passwordService.encryptPassword(sysUser.getLoginName(), sysUser.getPassword(), sysUser.getSalt()));
            boolean regFlag = userService.registerUser(sysUser);
            SysUser registeredUserInfo = userService.selectUserByLoginName(sysUser.getLoginName());
            userService.insertUserAuth(registeredUserInfo.getUserId(), new Long[]{101l});
            if (!regFlag) {
                msg = "注册失败,请联系系统管理人员";
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(userAddDTO.getLoginName(), Constants.REGISTER, MessageUtils.message("user.register.success")));
            }
        }
        return msg;
    }
}
