package com.admanager;

import com.unboundid.ldap.sdk.LDAPConnection;
import com.unboundid.ldap.sdk.LDAPException;
import com.unboundid.util.Debug;

public class ADUnboundIDExample {

    private static final String LDAP_HOST = "admserver.tlct.com.cn";
    private static final int LDAP_PORT = 389; // 普通LDAP端口，SSL使用636
    private static final String BIND_DN = "TLCT\\adadministrator";
    private static final String BIND_PASSWORD = "yonyou@123";
    private static final String BASE_DN = "dc=tlct,dc=com,dc=cn";

    public static void main(String[] args) {
        Debug.setEnabled(true);
        // 尝试以下三种常见格式
        String[] bindFormats = {
                "adadministrator@tlct.com.cn",          // UPN格式
                "CN=adadministrator,CN=Users,DC=tlct,DC=com,DC=cn",  // 完整DN
                "TLCT\\adadministrator"                 // 反斜杠格式（通常不推荐）
        };

        String password = "yonyou@123";
        String server = "admserver.tlct.com.cn";
        int port = 389;

        for (String bindDN : bindFormats) {
            try {
                LDAPConnection connection = new LDAPConnection(server, port, bindDN, password);
                System.out.println("绑定成功 - 使用: " + bindDN);
                connection.close();
                return; // 成功则退出
            } catch (LDAPException e) {
                System.err.println("绑定失败 - 使用: " + bindDN);
                System.err.println("错误: " + e.getMessage());
            }
        }
//        // 1. 创建连接
//        try (LDAPConnection connection = new LDAPConnection(LDAP_HOST, LDAP_PORT, BIND_DN, BIND_PASSWORD)) {
//
//            System.out.println("成功连接到AD服务器");
//
//            // 2. 搜索用户
//            SearchResult searchResult = connection.search(BASE_DN,
//                SearchScope.SUB,
//                "(objectClass=user)");
//
//            System.out.println("找到 " + searchResult.getEntryCount() + " 个用户");
//
//            // 3. 处理搜索结果
//            for (SearchResultEntry entry : searchResult.getSearchEntries()) {
//                System.out.println("DN: " + entry.getDN());
//                System.out.println("sAMAccountName: " + entry.getAttributeValue("sAMAccountName"));
//                System.out.println("mail: " + entry.getAttributeValue("mail"));
//            }
//
//        } catch (LDAPException e) {
//            System.err.println("LDAP操作失败: " + e.getMessage());
//            System.err.println("返回码: " + e.getResultCode());
//            System.err.println("错误消息: " + e.getDiagnosticMessage());
//        }
    }
}
