package com.yida.data.auth.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.yida.data.auth.manager.UserManager;
import cc.mrbird.febs.common.redis.service.RedisService;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.yida.data.common.core.entity.FebsAuthUser;
import com.yida.data.common.core.entity.constant.FebsConstant;
import com.yida.data.common.core.entity.constant.ParamsConstant;
import com.yida.data.common.core.entity.constant.SocialConstant;
import com.yida.data.common.core.entity.constant.StringConstant;
import com.yida.data.common.core.entity.system.SystemUser;
import com.yida.data.common.core.utils.FebsUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author MrBird
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FebsUserDetailServiceImpl implements UserDetailsService {

    private final PasswordEncoder passwordEncoder;
    private final UserManager userManager;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        HttpServletRequest httpServletRequest = FebsUtil.getHttpServletRequest();
        SystemUser systemUser = userManager.findByName(username);
        if (systemUser != null) {
            List<String> permissions = userManager.findUserPermissions(systemUser.getUsername());
            boolean notLocked = false;
            if (StringUtils.equals(SystemUser.STATUS_VALID, systemUser.getStatus())) {
                notLocked = true;
            }
            String password = systemUser.getPassword();
            String loginType = (String) httpServletRequest.getAttribute(ParamsConstant.LOGIN_TYPE);
            if (StringUtils.equals(loginType, SocialConstant.SOCIAL_LOGIN)) {
                password = passwordEncoder.encode(SocialConstant.getSocialLoginPassword());
            }

            List<GrantedAuthority> grantedAuthorities = AuthorityUtils.NO_AUTHORITIES;
            // 设置角色权限
            if (StringUtils.isNotBlank(systemUser.getRolePerms())) {
                List<String> collect = Arrays.stream(systemUser.getRolePerms().split(StringConstant.COMMA))
                    .map(s -> FebsConstant.SECURITY_ROLE_PREFIX + s)
                    .distinct()
                    .collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(collect)) {
                    grantedAuthorities = AuthorityUtils
                        .commaSeparatedStringToAuthorityList(String.join(StringConstant.COMMA, collect));
                }
            }
            // 设置菜单权限
            if (CollUtil.isNotEmpty(permissions)) {
                grantedAuthorities.addAll(AuthorityUtils.createAuthorityList(permissions.toArray(new String[0])));
            }
            // 查询主角色信息
            if (Objects.nonNull(systemUser.getMainDeptId())) {
                String role = this.userManager.findMainRole(systemUser.getMainDeptId());
                systemUser.setMainRolePerms(role);
            }

            //查询登录所属部门：学校对应的
            log.info("登陆用户信息sysUser: {}", systemUser);
            log.info("登陆权限数据permission: {}", grantedAuthorities);
            log.info("登陆主角色数据mainRole: {}", systemUser.getMainRolePerms());

            FebsAuthUser authUser = new FebsAuthUser(systemUser.getUsername(), password, true, true, true, notLocked,
                grantedAuthorities);

            BeanUtils.copyProperties(systemUser, authUser);
            return authUser;
        } else {
            throw new UsernameNotFoundException("");
        }
    }
}
