package com.yeejoin.precontrol.common.config;

import com.yeejoin.precontrol.common.annotations.TableFormat;
import com.yeejoin.precontrol.common.utils.RedisUtil;
import com.yeejoin.precontrol.common.utils.SpringUtils;

import java.lang.reflect.Field;

public class GlobalUtils {


    public static void setFormateByOne(Object body) throws IllegalAccessException {
        Field[] declaredFields = body.getClass().getDeclaredFields();
        for (Field declaredField : declaredFields) {
            TableFormat tableFormat = declaredField.getAnnotation(TableFormat.class);
            if (tableFormat != null) {
                declaredField.setAccessible(true);
                Long idValue = (Long) declaredField.get(body);
                if (idValue != null) {
                    //表对象名称
                    String entity = tableFormat.entityName();
                    //表对象的属性名
                    String fieldName = tableFormat.fieldName();
                    //要修改属性名
                    String operFieldName = tableFormat.operFieldName();
                    RedisUtil redisUtil = (RedisUtil) SpringUtils.getBean("redisUtil");
                    if (redisUtil.hasKey(entity + "_" + fieldName + "_" + idValue)) {
                        String redisValue = redisUtil.get(entity + "_" + fieldName + "_" + idValue).toString();
                        for (Field operField : declaredFields) {
                            String name = operField.getName();
                            if (name.equals(operFieldName)) {
                                operField.setAccessible(true);
                                operField.set(body, redisValue);
                            } else {
                                continue;
                            }
                        }
                    }
                }
            }
        }
    }
}
