package com.ningdatech.carapi.user.security.auth.facade;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ningdatech.carapi.sys.entity.dto.CompanyDTO;
import com.ningdatech.carapi.sys.helper.CompaniesCacheHelper;
import com.ningdatech.carapi.user.entity.NdUserAuth;
import com.ningdatech.carapi.user.entity.NdUserInfo;
import com.ningdatech.carapi.user.security.auth.constant.AuthTypeEnum;
import com.ningdatech.carapi.user.security.auth.model.dto.UserFullInfoDTO;
import com.ningdatech.carapi.user.service.INdUserAuthService;
import com.ningdatech.carapi.user.service.INdUserInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author LiuXinXin
 * @date 2022/9/30 上午9:54
 */
@Component
@RequiredArgsConstructor
public class UserAuthLoginFacade {
    private final INdUserAuthService iNdUserAuthService;
    private final INdUserInfoService iNdUserInfoService;

    private final CompaniesCacheHelper companiesCacheHelper;

    public UserFullInfoDTO queryUserInfoInPasswordAuth(String username) {
        // 获取用户鉴权信息
        NdUserAuth userAuth = iNdUserAuthService.getOne(Wrappers.lambdaQuery(NdUserAuth.class)
                .eq(NdUserAuth::getIdentifier, username)
                .eq(NdUserAuth::getAuthType, AuthTypeEnum.ACCOUNT_PASSWORD.getKey()));
        if (Objects.isNull(userAuth)) {
            return null;
        }

        //  获取用户详情信息
        NdUserInfo userInfo = iNdUserInfoService.getOne(Wrappers.lambdaQuery(NdUserInfo.class)
                .eq(NdUserInfo::getId, userAuth.getUserId()));
        UserFullInfoDTO userFullInfoDto = new UserFullInfoDTO();
        userFullInfoDto.setUserId(userInfo.getId());
        userFullInfoDto.setNickName(userInfo.getUsername());
        userFullInfoDto.setIdentifier(userAuth.getIdentifier());
        userFullInfoDto.setCredential(userAuth.getCredential());
        userFullInfoDto.setCompanyId(userInfo.getCompanyId());
        CompanyDTO company = companiesCacheHelper.getById(userInfo.getCompanyId());
        if(Objects.nonNull(company)){
            userFullInfoDto.setCompanyName(company.getName());
            userFullInfoDto.setRegionId(company.getRegionId());
            userFullInfoDto.setRegionName(company.getRegionName());
        }
        return userFullInfoDto;
    }
}
