package com.yifu.cloud.plus.v1.yifu.common.ldap.util;

import com.unboundid.ldap.sdk.*;
import com.unboundid.ldap.sdk.controls.SubentriesRequestControl;
import com.yifu.cloud.plus.v1.yifu.common.ldap.entity.PersonVo;
import com.yifu.cloud.plus.v1.yifu.common.ldap.mapper.PersonAttributesMapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.LdapTemplate;

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

import static org.springframework.ldap.query.LdapQueryBuilder.query;

@Log4j2
public class LdapUtil {

	@Autowired
	private LdapTemplate ldapTemplate;

	/**
	 * @return List<SearchResultEntry>
	 * @author huyc
	 * @date 2022-06-14 17:56
	 * @description get请求获取指定对象信息
	 **/
	public List<SearchResultEntry> getAllPersonNamesWithTraditionalWay() {
		List<SearchResultEntry> result = new ArrayList<SearchResultEntry>();
		try {
			LDAPConnection connection = new LDAPConnection("192.168.1.65", 389, "cn=admin,dc=worfu,dc=com", "yifu123456!");
			SearchRequest searchRequest = new SearchRequest("ou=安徽皖信人力资源管理有限公司,ou=wanxin,dc=worfu,dc=com", SearchScope.SUB, "(objectclass=*)");
			searchRequest.addControl(new SubentriesRequestControl());
			SearchResult searchResult = connection.search(searchRequest);
			for (SearchResultEntry entry : searchResult.getSearchEntries()) {
				result.add(entry);
			}
		} catch (LDAPException e) {
			e.printStackTrace();
		}
		return result;
	}

	public List<PersonVo> getAllPersons() {
		List<PersonVo> list = ldapTemplate.search(query()
				.where("objectclass").is("posixAccount"), new PersonAttributesMapper());
		return list;
	}

}
