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

import com.inkasso.adapter.enums.ClientTypeEnum;
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.factoring.login.service.SessionService;
import com.inkasso.factoring.login.service.UserLoginService;
import com.inkasso.factoring.system.user.model.dto.UserDTO;
import com.inkasso.factoring.system.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 张超
 * @date 2021/11/5
 */
@Service
public class UserLoginServiceImpl implements UserLoginService {


    @Autowired
    private SessionService sessionService;

    @Autowired
    private UserService userService;


    @Override
    public LoginResultDTO login(ClientTypeEnum clientTypeEnum, PasswordLoginRequest request) {
        //根据用户名查询用户
        UserDTO userDto = userService.getUserByUsername(request.getUsername());
        if (userDto == null) {
            throw new ServiceException(UserExceptionEnum.USER_NOT_EXISTS);
        }
        //第一步判断用户密码
        boolean flag = MD5Util.validPassword(request.getPassword(), userDto.getPassword());
        //前端暂无加密
        //boolean flag = StringUtils.equals(request.getPassword(), userDto.getPassword());
        if (!flag) {
            throw new ServiceException(UserExceptionEnum.USER_PASSWORD_ERROR);
        }
//    //第二步判断用户是否分配了角色
//    List<Long> roleIds = userToRoleService.getRoleIdsByUserId(userDto.getUserId());
//    if(CollectionUtils.isEmpty(roleIds)){
//      throw new ServiceException(UserExceptionEnum.USER_NOT_HAVE_ROLE);
//    }
        //查询用户绑定的头像
//    FileStorageDTO fileStorageDTO = fileService.findOneByBusinessId(userDto.getId().toString(), OrganizationFileEnum.USER_HEADING.getCode());
//    if(fileStorageDTO!=null){
//      userDto.setHeadImg(fileStorageDTO.getPath());
//    }
        //第三步生成对应的token
        LoginResultDTO result = sessionService.createTokenAndSession(clientTypeEnum, userDto);

        //保存登录日志

        return result;

    }
}
