package com.ruoyi.framework.web.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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;

/**
 * 登录校验方法
 *
 * @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;

    @Value("${system.security}")
    private String thirdSecurity;

    @Value("${third.userLogin}")
    private String userLogin;

    @Value("${token.filterUser}")
    private String filterUser;

    @Value("${third.userTokenInfo}")
    private String dajiaoguan_token;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        boolean captchaOnOff = configService.selectCaptchaOnOff();
        // 验证码开关
        if (captchaOnOff) {
            validateCapcha(username, code, uuid);
        }
        // 用户验证
        Authentication authentication = null;
        try {
            if ("third".equals(thirdSecurity) && !StrUtil.contains(filterUser, username)) {
                // 走第三方的校验规则,同时将第三方的password设置为系统自动生成的
                JSONObject jsonObject = new JSONObject();
                jsonObject.set("account", username);
                jsonObject.set("password", password);
                String post = HttpUtil.post(userLogin, jsonObject.toString());
                JSONObject postJson = JSONUtil.parseObj(post);
                if (postJson.getInt("code") == 200) {
                    // 成功
                    password = Constants.DEFAULT_PASSWORD;
                    // 保存用户
                    if (UserConstants.UNIQUE.equals(userService.checkUserNameUnique(username))) {
                        // 查询第三方用户信息
                        String getResult = HttpUtil.createGet(dajiaoguan_token).header("Authorization", Constants.TOKEN_PREFIX + postJson.getStr("data")).execute().body();
                        JSONObject getJson = JSONUtil.parseObj(getResult);
                        int infoCode = getJson.getInt("code");
                        if (infoCode == 1) {
                            SysUser sysUser = new SysUser();
                            // 将此用户新增入系统
                            JSONObject data = getJson.getJSONObject("data");
                            sysUser.setUserId(data.getLong("userId"));
                            sysUser.setUserName(username);
                            sysUser.setDeptId(data.getStr("depId"));
                            sysUser.setPhonenumber(data.getStr("phone"));
                            sysUser.setDelFlag("0");
                            sysUser.setStatus("0");
                            sysUser.setNickName(data.getStr("name"));
                            // 新加入的用户属于普通用户角色
                            sysUser.setRoleIds(new Long[]{2L});
                            sysUser.setPassword(SecurityUtils.encryptPassword(password));
                            userService.insertUser(sysUser);
                        }
                    }
                } else {
                    log.info("第三方校验登录失败：{}", postJson);
                    AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                    throw new UserPasswordNotMatchException();
                }
            }
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, 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 CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUser());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    public String nologin(String thirdToken) {
        // 用户验证
        Authentication authentication;
        String password = Constants.DEFAULT_PASSWORD;
        try {
            // 保存用户
            // 查询第三方用户信息
            String getResult = HttpUtil.createGet(dajiaoguan_token).header("Authorization", Constants.TOKEN_PREFIX + thirdToken).execute().body();
            JSONObject getJson = JSONUtil.parseObj(getResult);
            int infoCode = getJson.getInt("code");
            if (infoCode == 1) {
                // 校验用户是否存在
//                String username = getJson.getStr("account");
                String username = "qinxq@zjgmsa";
                if (UserConstants.UNIQUE.equals(userService.checkUserNameUnique(username))) {
                    SysUser sysUser = new SysUser();
                    // 将此用户新增入系统
                    JSONObject data = getJson.getJSONObject("data");
                    sysUser.setUserId(data.getLong("userId"));
                    sysUser.setUserName(username);
                    sysUser.setDeptId(data.getStr("depId"));
                    sysUser.setPhonenumber(data.getStr("phone"));
                    sysUser.setDelFlag("0");
                    sysUser.setStatus("0");
                    sysUser.setNickName(data.getStr("name"));
                    // 新加入的用户属于普通用户角色
                    sysUser.setRoleIds(new Long[]{2L});
                    sysUser.setPassword(SecurityUtils.encryptPassword(password));
                    userService.insertUser(sysUser);
                }
                // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
                authentication = authenticationManager
                        .authenticate(new UsernamePasswordAuthenticationToken(username, password));
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
            } else {
                return "";
            }
        } catch (Exception e) {
            return "";
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUser());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCapcha(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();
        }
    }

    /**
     * 记录登录信息
     */
    public void recordLoginInfo(SysUser user) {
        user.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        user.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(user);
    }

}
