package com.xunhong.erp.turbo.web.handler;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import com.xunhong.erp.turbo.base.annotation.Decrypt;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;

import java.lang.reflect.Field;

@ControllerAdvice
public class DecryptControllerAdvice {

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		Object target = binder.getTarget();
		if (target != null) {
			decryptObject(target);
		}
	}

	private void decryptObject(Object obj) {
		try {
			Class<?> clazz = obj.getClass();
			for (Field field : clazz.getDeclaredFields()) {
				if (field.isAnnotationPresent(Decrypt.class)) {
					field.setAccessible(true);
					String encryptedValue = (String) field.get(obj);
					String decryptedValue = decrypt(encryptedValue);
					field.set(obj, decryptedValue);
				}
			}
		} catch (IllegalAccessException e) {
			throw new RuntimeException("Decryption failed", e);
		}
	}

	/**
	 * 解密方法
	 *
	 * @param encryptedText 加密的字符串
	 * @return 解密后的字符串
	 */
	public String decrypt(String encryptedText) {
		AES aes = SecureUtil.aes("weKANfYbTTqZCve0".getBytes());

		return aes.decryptStr(encryptedText);
	}
}
