package cn.iocoder.yudao.module.system.service.dingding;

import cn.iocoder.yudao.module.system.controller.admin.dingding.vo.DingToken;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Objects;


@Component
@Slf4j
@RequiredArgsConstructor
public class DingAuthenticationProvider implements AuthenticationProvider {

//    @Autowired
//    private ISysUserService userService;
//
//    @Autowired
//    private SysPermissionService permissionService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        DingToken token = (DingToken) authentication;
        String userId = (String) token.getPrincipal();
        String corpId = (String) token.getCredentials();

//        SysUser sysUser = userService.getUserByUserNameAndCorpId(userId,corpId);
//        if (Objects.isNull(sysUser)) {
//            throw new InternalAuthenticationServiceException("根据userId：" + userId + "，无法获取对应的用户信息！");
//        }
//        LoginUser user = (LoginUser) createLoginUser(sysUser);
//        user.setAuthType("AuthDingtalk");
//        user.setPrincipal(userId);
//        user.setCredentials(corpId);
//        user.setCorpid(corpId);
//        token.setDetails(user);
        DingToken authenticationResult = new DingToken("user.getAuthorities()", userId, corpId);
        authenticationResult.setDetails(token.getDetails());
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return DingToken.class.isAssignableFrom(authentication);
    }


//    public UserDetails createLoginUser(SysUser user) {
//        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
//    }
}
