package io.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.common.exception.RenException;
import io.common.validator.AssertUtils;
import io.dao.UserDao;
import io.entity.TokenEntity;
import io.entity.UserEntity;
import io.service.TokenService;
import io.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Autowired
    private  TokenService tokenService;

    @Override
    public UserEntity getUserByUserId(Long userId) {
        return baseMapper.selectById(userId);
    }

    @Override
    public boolean existsUsername(String username) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        return baseMapper.selectCount(wrapper) > 0;
    }

    @Override
    public UserEntity getByUsername(String username) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public Map<String, Object> login(UserEntity dto) {
        UserEntity user = getByUsername(dto.getUsername());
        AssertUtils.isNull(user, "用户名不存在~");

        if (!dto.getRole().equals(user.getRole())){
            throw new RenException("该角色没有账号");
        }

        //密码错误
        if (!user.getPassword().equals(DigestUtil.sha256Hex(dto.getPassword()))) {
            throw new RenException("密码输入错误~");
        }

        //获取登录token
        TokenEntity tokenEntity = tokenService.createToken(user.getId());

        Map<String, Object> map = new HashMap<>(2);
        map.put("token", tokenEntity.getToken());
        map.put("expire", tokenEntity.getExpireDate().getTime() - System.currentTimeMillis());
        return map;
    }
}
