package com.jiuzhekan.cbkj.common.interceptor.tianan;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.*;

import java.lang.reflect.Field;
import java.sql.Statement;
import java.util.List;
import java.util.Properties;

/**
 * MybatisEntrIntercept
 * <p>
 * 杭州聪宝科技有限公司
 * <p>
 *
 * @author guowei
 * @date 2021/4/8 10:32
 */
@Slf4j
@Intercepts({
        @Signature(
                type = ResultSetHandler.class,
                method = "handleResultSets",
                args = {Statement.class}
        )
})
public class TianAnDecryptIntercept implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        log.info("===========TianAnDecryptIntercept===========");
        Object returnValue = invocation.proceed();
        decryptResult(returnValue);
        return returnValue;
    }

    /**
     * 解密结果
     *
     * @param returnValue returnValue
     */
    private void decryptResult(Object returnValue) {

        if (returnValue instanceof List) {
            List resultList = (List) returnValue;
            for (Object o : resultList) {
                if (o instanceof Long) {
                    break;
                }
                decryptBean(o);
            }
        }

    }

    /**
     * 解密对象
     *
     * @param bean 对象
     * @author guowei
     * @date 2021/4/8
     */
    private void decryptBean(Object bean) {
        Field[] fields = bean.getClass().getDeclaredFields();
        for (Field field : fields) {
            try {
                if (field.getType() == List.class) {
                    field.setAccessible(true);
                    List list = (List) field.get(bean);
                    for (Object o : list) {
                        decryptBean(o);
                    }
                } else if (field.isAnnotationPresent(TianAnDecryptField.class)) {

                    field.setAccessible(true);
                    Object value = field.get(bean);
                    if (value != null) {
                        String encrypt = TianAnUtils.decrypt(value.toString());
                        field.set(bean, encrypt);
                    }
                }
            } catch (Exception ignored) {
            }
        }
    }


    @Override
    public Object plugin(Object o) {
        return Plugin.wrap(o, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
