package cn.ezhizao.framework.security.service;

import cn.ezhizao.common.constant.CacheConstants;
import cn.ezhizao.common.constant.Constants;
import cn.ezhizao.common.exception.ServiceException;
import cn.ezhizao.common.exception.user.CaptchaException;
import cn.ezhizao.common.exception.user.CaptchaExpireException;
import cn.ezhizao.common.exception.user.UserPasswordNotMatchException;
import cn.ezhizao.common.utils.DateUtils;
import cn.ezhizao.common.utils.MessageUtils;
import cn.ezhizao.common.utils.ServletUtils;
import cn.ezhizao.common.utils.StringUtils;
import cn.ezhizao.common.utils.ip.IpUtils;
import cn.ezhizao.common.utils.uuid.SnowflakeIdWorker;
import cn.ezhizao.framework.manager.AsyncManager;
import cn.ezhizao.framework.manager.factory.AsyncFactory;
import cn.ezhizao.framework.redis.RedisCache;
import cn.ezhizao.framework.security.LoginUser;
import cn.ezhizao.framework.security.context.AuthenticationContextHolder;
import cn.ezhizao.project.system.domain.SysDept;
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.ISysDeptService;
import cn.ezhizao.project.system.service.ISysUserService;
import cn.ezhizao.project.tenant.domain.BizUserTenant;
import cn.ezhizao.project.tenant.domain.Tenant;
import cn.ezhizao.project.tenant.service.IBizUserTenantService;
import cn.ezhizao.project.tenant.service.ITenantService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

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

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class SysLoginService
{
    @Resource
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisCache redisCache;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private ISysConfigService configService;

    @Resource
    private ITenantService tenantService;

    @Resource
    private ISysDeptService deptService;

    @Resource
    SysUserRoleMapper userRoleMapper;

    @Resource
    private IBizUserTenantService userTenantService;

    @Resource
    private SnowflakeIdWorker snowflakeIdWorker;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        // 验证码开关
        if (captchaEnabled)
        {
            validateCaptcha(username, code, uuid);
        }
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     *
     * @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)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        sysUser.setLoginDate(DateUtils.getNowDate());
        sysUserService.updateUserProfile(sysUser);
    }

    public List<Tenant> getTenantList(String userName) {
        Tenant tenant = new Tenant();
        tenant.setUserName(userName);
        List<Tenant> tenantList = tenantService.getList(tenant);
        if (tenantList.size() > 0) {
            return tenantList;
        } else {
            tenantList = new ArrayList<Tenant>();
            return tenantList;
        }
    }
}
