package com.aircraft.modules.security.service;

import com.aircraft.exception.BadRequestException;
import com.aircraft.modules.security.service.dto.JwtCustomerDto;
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.service.CnCustomerService;
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("bUserDetailsService")
public class BUserDetailsService implements UserDetailsService {

    private final CnCustomerService cnCustomerService;
    private final UserCacheManager userCacheManager;

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

}