package com.inkasso.management.login.service.impl;

import cn.hutool.core.lang.UUID;
import com.inkasso.adapter.exception.ServiceException;
import com.inkasso.adapter.util.MD5Util;
import com.inkasso.factoring.login.enums.UserExceptionEnum;
import com.inkasso.factoring.login.model.dto.LoginResultDTO;
import com.inkasso.factoring.login.model.request.PasswordLoginRequest;
import com.inkasso.management.login.service.BackEndUserLoginService;
import com.inkasso.management.user.model.dto.BackendUserDTO;
import com.inkasso.management.user.service.BackendUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class BackEndUserLoginServiceImpl implements BackEndUserLoginService {

    @Autowired
    private BackendUserService backendUserService;

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String prefix = "backendUser:";

    @Override
    public LoginResultDTO login(PasswordLoginRequest passwordLoginRequest) {
        BackendUserDTO backendUserDto = backendUserService.getBackendUserDtoByUsername(passwordLoginRequest.getUsername());
        if(backendUserDto==null){
            throw new ServiceException(UserExceptionEnum.USER_NOT_EXISTS);
        }
        //比较密码
        boolean b = MD5Util.validPassword(passwordLoginRequest.getPassword(), backendUserDto.getPassword());
        if(b){
            LoginResultDTO loginResultDTO = new LoginResultDTO();
            String s = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(prefix+s,backendUserDto);
            loginResultDTO.setToken(s);
            return loginResultDTO;
        }else{
            throw new ServiceException(UserExceptionEnum.USER_PASSWORD_ERROR);
        }

    }
}
