package com.project.zcustom.service.system.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.zcustom.domain.system.SysUser;
import com.project.zcustom.exception.ServiceException;
import com.project.zcustom.mapper.system.SysUserMapper;
import com.project.zcustom.service.system.ISysUserService;
import com.project.zcustom.tools.AESUtil;
import com.project.zcustom.tools.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 用户 业务层处理
 *
 * @author bqyang
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    @Autowired
    private SysUserMapper userMapper;


    @Override
    public String login(String userName, String password) {
        password = AESUtil.decrypt(password);
        SysUser user = userMapper.selectUserByUserName(userName);
        if (Objects.isNull(user)) {
            throw new ServiceException("用户名/密码错误！");
        }
        boolean pass = SecurityUtils.matchesPassword(password, user.getPassword());
        if (!pass){
            throw new ServiceException("用户名/密码错误！");
        }
        StpUtil.login(user.getUserId());
        String token = StpUtil.getTokenValue();
        return token;
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        return userMapper.selectUserByUserName(userName);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }


}
