package org.springblade.modules.auth.ldap.service;

import cn.hutool.crypto.digest.DigestUtil;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.springblade.core.tool.utils.AesUtil;
import org.springblade.core.tool.utils.DesUtil;
import org.springblade.modules.auth.ldap.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.filter.EqualsFilter;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

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

@Service
public class LdapService {

	@Autowired
	private LdapTemplate ldapTemplate;



	/**
	 * AD认证
	 *
	 * @param username 用户名
	 * @param password 密码
	 */
	public boolean ldapAuth(String username, String password) {
		ldapTemplate.setIgnorePartialResultException(true);
		EqualsFilter filter = new EqualsFilter("sAMAccountName", username);
		return ldapTemplate.authenticate("", filter.toString(), password);
	}

	public List findAll() throws Exception {
		ldapTemplate.setIgnorePartialResultException(true);
		return ldapTemplate.findAll(Person.class);
	}

	public void findAll2(){
		Person person = ldapTemplate.findOne(query().where("uid").is("ldapuser2"), Person.class);
		System.out.println(person);
	}

	public Person create(Person person){
		ldapTemplate.create(person);
		return person;
	}

	public Person findByCn(String cn){
		String encryptToHex = DesUtil.encryptToHex("admin123", "cyzh2020");
		System.out.println("encryptToHex=" + encryptToHex);

		String decryptFormHex = DesUtil.decryptFormHex(encryptToHex, "cyzh2020");
		System.out.println("decryptFormHex=" + decryptFormHex);

		String admin123 = DigestUtil.md5Hex("admin123");
		System.out.println("md5=" + admin123);

		return ldapTemplate.findOne(query().where("cn").is(cn),Person.class);
	}

	public Person modifyPerson(Person person){
		ldapTemplate.update(person);
		return person;
	}

	public void deletePerson(Person person){
		ldapTemplate.delete(person);
	}
}
