package com.yeejoin.precontrol.common.utils;

import com.baomidou.mybatisplus.annotation.TableName;
import com.yeejoin.precontrol.common.entity.publics.BaseEntity;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.List;

/**
 * @description:
 * @author: duanwei
 * @date: 2020-08-05 15:39
 **/
@Slf4j
public class TranslateUtil {

    /**
     * 用于启动加载全部数据 GlobalFormat
     *
     * @param list
     * @param keyName
     * @param redisUtil
     */
    public static void setDictionary(List<? extends BaseEntity> list, String keyName, RedisUtil redisUtil) {
        if (!list.isEmpty()) {
            list.forEach(data -> {
                try {
                    Class<? extends BaseEntity> aClass = data.getClass();
                    Field field = aClass.getDeclaredField(keyName);
                    field.setAccessible(true);
                    Object name = field.get(data);
                    if (name != null) {
                        String tableName = aClass.getAnnotation(TableName.class).value();
                        Long id = data.getId();
                        redisUtil.set(tableName + "_" + keyName + "_" + id, name);
                    }
                } catch (NoSuchFieldException e) {
                    log.error("反射字典表属性不存在{}:", data);
                } catch (IllegalAccessException e) {
                    log.error("反射访问权限不足{}:", data);
                }
            });
        }
    }


    /**
     * 根据key操作数据 单个添加
     *
     * @param data
     * @param keyName
     * @param redisUtil
     */
    public static void setDictionary(BaseEntity data, String keyName, RedisUtil redisUtil) {
        try {
            Class<? extends BaseEntity> aClass = data.getClass();
            Field field = aClass.getDeclaredField(keyName);
            field.setAccessible(true);
            Object name = field.get(data);
            if (name != null) {
                String tableName = aClass.getAnnotation(TableName.class).value();
                Long id = data.getId();
                redisUtil.set(tableName + "_" + keyName + "_" + id, name);
            }
        } catch (NoSuchFieldException e) {
            log.error("反射字典表属性不存在{}:", data);
        } catch (IllegalAccessException e) {
            log.error("反射访问权限不足{}:", data);
        }
    }

}
