package com.junmp.jyzb.advice;

import com.alibaba.fastjson2.JSONObject;
import com.junmp.jyzb.api.bean.req.ChannelReq.GetCfgByNumV2Req;
import org.apache.poi.ss.formula.functions.T;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.lang.reflect.Field;

@Aspect
@Component
public class DecryptionRequiredValidator {


    @Pointcut("@annotation(com.junmp.jyzb.api.bean.validator.DecryptionRequired)")
    public void cutLogService() {
    }



    @Around("cutLogService()")
    public Object decryptRequestParameters1(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();

        // 获取请求体数据
//        String requestBody = "";
        for (int i = 0; i < args.length; i++) {

            args[i] = processDecryption(args[i]);
            break;

        }
        return joinPoint.proceed(args);
    }


    private <T> T processDecryption(T obj) {
        try {

            Field bodyField = obj.getClass().getDeclaredField("body");
            bodyField.setAccessible(true);
            String encryptedBody = (String) bodyField.get(obj);
            String decodedBody = URLDecoder.decode(encryptedBody, StandardCharsets.UTF_8.toString());

            // 使用 JSONObject 将解密后的字符串转换为对象
            T decryptedObj = JSONObject.parseObject(decodedBody, (Class<T>) obj.getClass());

            return decryptedObj;
        } catch (NoSuchFieldException | IllegalAccessException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return obj;
    }
}