package com.ruoyi.gysl.login.service;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysUserService;
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.Service;

import javax.annotation.Resource;

/**
 * 登录实现
 *
 * @author du
 * @since 2025/5/9 下午2:30
 */
@Service
public class LoginTokenServiceImpl implements LoginTokenService {

    @Resource
    private ISysUserService userService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private TokenService tokenService;


    @Override
    public String singleLogin(String accountName,
                              String name,
                              String type,
                              String mobile,
                              String email) {
        // 用户验证
        Authentication authentication;
        try {
            SysUser user = new SysUser();
            user.setUserName(accountName);
            user.setNickName(name);
            user.setPassword("Gysl@2025//**...");
            user.setPhonenumber(mobile);
            user.setEmail(email);
            Long[] roles = new Long[1];
            if ("01".equals(type)) {
                if("jjdntest".equals(accountName)||"yanyq".equals(accountName)){
                    roles[0] = 101L;
                }else {
                    roles[0] = 2L;
                }
            } else if ("02".equals(type)) {
                roles[0] = 100L;
            }
            user.setRoleIds(roles);
            user.setStatus("0");
            //如果用户名也就是信用代码没有重复的就新增用户
            if (userService.checkUserNameUnique(user)) {
                user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
                userService.insertUser(user);
            }
            //新增user账号密码
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(accountName, "Gysl@2025//**...");
            AuthenticationContextHolder.setContext(authenticationToken);
//             该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(accountName, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(accountName, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(accountName, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return tokenService.createToken(loginUser);
    }
}
