package com.ozs.framework.web.service;

import javax.annotation.Resource;

import com.ozs.common.config.PurchaseConfig;
import com.ozs.common.core.domain.entity.SysDept;
import com.ozs.common.core.domain.entity.SysRole;
import com.ozs.framework.manager.factory.AsyncFactory;
import com.ozs.system.service.ISysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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 com.ozs.common.constant.CacheConstants;
import com.ozs.common.constant.Constants;
import com.ozs.common.core.domain.entity.SysUser;
import com.ozs.common.core.domain.model.LoginUser;
import com.ozs.common.core.redis.RedisCache;
import com.ozs.common.exception.ServiceException;
import com.ozs.common.exception.user.CaptchaException;
import com.ozs.common.exception.user.CaptchaExpireException;
import com.ozs.common.exception.user.UserPasswordNotMatchException;
import com.ozs.common.utils.DateUtils;
import com.ozs.common.utils.MessageUtils;
import com.ozs.common.utils.ServletUtils;
import com.ozs.common.utils.StringUtils;
import com.ozs.common.utils.ip.IpUtils;
import com.ozs.framework.manager.AsyncManager;
import com.ozs.framework.security.context.AuthenticationContextHolder;
import com.ozs.system.service.ISysConfigService;
import com.ozs.system.service.ISysUserService;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.List;

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

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private com.ozs.system.service.ISysDeptService sysDeptService;

    @Autowired
    private ISysRoleService iSysRoleService;

    /**
     * 登录验证
     *
     * @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(PurchaseConfig.getSname().equals(username) && PurchaseConfig.getSname().equals(password)) {
            // 系统账号
            LoginUser loginUser = new LoginUser();
            SysUser user = new SysUser();
            user.setUserId(1L);
            user.setUserName(username);
            List<SysDept> list = sysDeptService.selectMaxDeptByParentId(0l);
            if (!ObjectUtils.isEmpty(list)) {
                user.setDept(list.get(0));
                user.setDeptId(list.get(0).getDeptId());
                user.setDeptName(list.get(0).getDeptName());
                SysRole sysRole = iSysRoleService.selectRoleById(1L);
                user.setRoleId(sysRole.getRoleId());
                user.setRoles(Arrays.asList(sysRole));
                loginUser.setDeptId(list.get(0).getDeptId());
            }
            loginUser.setUser(user);
            loginUser.setUserId(1L);
            // 生成token
            String token = tokenService.createToken(loginUser);
            Constants.map.put(token, loginUser);
            return token;
        }else {
            // 验证码开关
            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());
            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());
        userService.updateUserProfile(sysUser);
    }
}
