package com.diagbot.service;

import com.diagbot.entity.SysPermission;
import com.diagbot.entity.SysUserUaa;
import com.diagbot.enums.ConstantEnum;
import com.diagbot.mapper.SysPermissionMapper;
import com.diagbot.mapper.SysUserUaaMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
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.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 用户权限信息获取
 * @author: gaodm
 * @time: 2018/8/23 11:39
 */
@Service
public class UrlUserService implements UserDetailsService {
    @Autowired
    SysUserUaaMapper userUaaMapper;
    @Autowired
    SysPermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) { //重写loadUserByUsername 方法获得 userdetails 类型用户

        SysUserUaa user = userUaaMapper.getByUserName(userName);
        if (user != null) {
            List<SysPermission> permissions = permissionMapper.getByUserId(user.getId());
            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
            for (SysPermission permission : permissions) {
                if (null != permission && StringUtils.isNotBlank(permission.getPermissionUrl())) {
                    GrantedAuthority grantedAuthority
                            = new UrlGrantedAuthority(permission.getPermissionUrl(), permission.getMethod());
                    grantedAuthorities.add(grantedAuthority);
                }
            }
            user.setGrantedAuthorities(grantedAuthorities);
            if (user.getType().equals(ConstantEnum.OUTER_USER.getKey())) {
                SysUserUaa userHosp = userUaaMapper.getHospByUserName(userName);
                if (null == userHosp) {
                    throw new UsernameNotFoundException("医院管理人员: " + userName + " 未绑定医院");
                } else {
                    user.setHospitalId(userHosp.getHospitalId());
                }
            } else {
                user.setHospitalId(-1L);
            }
            return user;
        } else {
            throw new UsernameNotFoundException("admin: " + userName + " do not exist");
        }
    }
}