package io.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import io.common.exception.RenException;
import io.common.service.impl.BaseServiceImpl;
import io.common.validator.AssertUtils;
import io.entity.TokenEntity;
import io.modules.item.dao.UserDao;
import io.modules.item.dto.LoginDTO;
import io.modules.item.entity.UserEntity;
import io.service.TokenService;
import io.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;

@Service
@AllArgsConstructor
public class UserServiceImpl extends BaseServiceImpl<UserDao, UserEntity> implements UserService {
    private final TokenService tokenService;

    @Override
    public UserEntity getByUsername(String username){
        return baseDao.getUserByUsername(username);
    }

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

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

        //密码错误
        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;
    }

}
