package com.shkj.framework.web.service;

import com.shkj.common.constant.Constants;
import com.shkj.common.core.domain.entity.SysUser;
import com.shkj.common.core.domain.model.LoginUser;
import com.shkj.common.core.redis.RedisCache;
import com.shkj.common.exception.ServiceException;
import com.shkj.common.exception.user.CaptchaException;
import com.shkj.common.exception.user.CaptchaExpireException;
import com.shkj.common.exception.user.UserPasswordNotMatchException;
import com.shkj.common.utils.DateUtils;
import com.shkj.common.utils.MessageUtils;
import com.shkj.common.utils.ServletUtils;
import com.shkj.common.utils.ip.IpUtils;
import com.shkj.framework.manager.factory.AsyncFactory;
import com.shkj.framework.manager.AsyncManager;
import com.shkj.system.service.ISysParameterService;
import com.shkj.system.service.ISysUserService;
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 javax.annotation.Resource;
import java.util.Objects;

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

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysParameterService configService;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @param branchId
     * @param isPda
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid, Long branchId, boolean isPda) {
//        boolean captchaOnOff = configService.selectCaptchaOnOff();
        // 验证码开关
//        if (captchaOnOff)
//        {
//            validateCaptcha(username, code, uuid);
//        }
        if (username.contains(",")) {
            throw new ServiceException("账号非法");
        }
        String wid = branchId == null ? "" : branchId.toString();
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername  这里为了简单直接使用用户账号+仓库id 后面在进行分割
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username + "," + wid, password));
        } 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());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        SysUser sysUser = userService.selectUserById(loginUser.getUserId());
        if (isPda){
            if (!Objects.equals(sysUser.getIsDevice(), 1)) {
                throw new ServiceException("该账号不允许登录设备");
            }
        }
        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 = Constants.CAPTCHA_CODE_KEY + 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);
    }
}
