package com.aircraft.modules.security.service;

import com.aircraft.exception.BadRequestException;
import com.aircraft.modules.security.service.dto.JwtUserDto;
import com.aircraft.modules.security.service.dto.LoginUserDto;
import com.aircraft.modules.system.domain.CnCustomer;
import com.aircraft.modules.system.domain.Dept;
import com.aircraft.modules.system.domain.EmEmployees;
import com.aircraft.modules.system.service.CnCustomerService;
import com.aircraft.modules.system.service.EmEmployeesService;
import com.aircraft.utils.enums.UserTypeEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Slf4j
@RequiredArgsConstructor
@Service("aUserDetailsService")
public class AUserDetailsService implements UserDetailsService {

    private final EmEmployeesService emEmployeesService;
    private final UserCacheManager userCacheManager;

    @Override
    public JwtUserDto loadUserByUsername(String username) {
        JwtUserDto employeeDto = userCacheManager.getEmployeeDtoCache(username);
        // 查询B端用户表（如b_user）
        if(employeeDto == null){
            EmEmployees emEmployees = emEmployeesService.findByUsername(username);
            if (emEmployees == null) {
                throw new BadRequestException("飞行员不存在");
            } else {
                if (emEmployees.getStatus().equals("0")) {
                    throw new BadRequestException("账号未激活！");
                }
                // 使用构造函数传递必要的参数
                LoginUserDto userDto = new LoginUserDto();
                userDto.setId(emEmployees.getId());
                userDto.setUsername(emEmployees.getUsername());
                userDto.setNickName(emEmployees.getName());
                userDto.setDept(new Dept());
                userDto.setPassword(emEmployees.getPassword());
                userDto.setEnabled(true);
                userDto.setIsAdmin(false);
                // 创建一个 JwtCustomerDto 对象
                employeeDto = new JwtUserDto(userDto, UserTypeEnum.EMPLOYEES, new ArrayList<>(),null);
                // 添加缓存数据
                userCacheManager.addEmployeeCache(username, employeeDto);
            }
        }
        return employeeDto;
    }

}