package cn.wise.sc.energy.power.plant.business.security;

import cn.wise.sc.energy.power.plant.business.domain.UserInfo;
import cn.wise.sc.energy.power.plant.business.service.IUserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * JwtUserDetailsService
 * 实现UserDetailsService,重写loadUserByUsername方法
 */
@Slf4j
@Component
public class JwtUserDetailsService implements UserDetailsService {

    final
    IUserInfoService iUserInfoService;

    public JwtUserDetailsService(IUserInfoService iUserInfoService) {
        this.iUserInfoService = iUserInfoService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        String[] split = username.split("\\|");
        if (split.length != 2) {
            throw new UsernameNotFoundException("username is not available!");
        }
        String account = split[0];
        //获取数据库用户信息
        List<UserInfo> list = iUserInfoService.getSysUserByUsername(account);

        //todo 权限获取
        if (list.size() == 0) {
            log.warn("未找到当前用户:{} \n ====== cn.wise.sc.pay.common.security2.userDetail.JwtUserDetailsService.loadUserByUsername()", username);
            throw new UsernameNotFoundException("未找到当前用户!");
        }

        //判断用户登录
        UserDetails userDetails = list.get(0);

        //判断用户所属
        UserInfo userInfo = (UserInfo) userDetails;
        if (!userInfo.getPlantid().equals(split[1])) {
            throw new UsernameNotFoundException("user is not belong to this plant!");
        }
        ((UserInfo) userDetails).setUsername(username);
        return userDetails;
    }
}
