package com.leromro.common.utils;

import com.baomidou.mybatisplus.annotation.TableField;
import com.leromro.common.constant.CommonConstants;
import com.leromro.common.core.domain.ListPermission;
import org.apache.commons.lang3.reflect.FieldUtils;

import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

public class PermissionUtil {

    /**
     * 从参数实体获取数据权限对象
     *
     * @param parameterObject mapper参数集合
     * @return
     */
    public static Optional<ListPermission> findPermission(Object parameterObject) {
        if (parameterObject != null) {
            if (parameterObject instanceof Map) {
                Map<?, ?> parameterMap = (Map) parameterObject;
                Iterator var2 = parameterMap.entrySet().iterator();

                while (var2.hasNext()) {
                    Map.Entry entry = (Map.Entry) var2.next();
                    if (entry.getValue() != null && entry.getValue() instanceof ListPermission) {
                        return Optional.ofNullable((ListPermission) entry.getValue());
                    }
                }
            } else if (parameterObject instanceof ListPermission) {
                return Optional.of((ListPermission) parameterObject);
            }
        }
        return Optional.empty();
    }

    /**
     * 通过反射判断存在TableField的字段，并返回校验类中的字段
     * @param tableEntity
     * @return
     */
    public static List<String> getGroupMappers(Class<?> tableEntity) {
        List<Field> fields = FieldUtils.getFieldsListWithAnnotation(tableEntity, TableField.class);
        return fields.stream()
                .map(f ->{
                    TableField annotation = f.getAnnotation(TableField.class);
                    if (Objects.isNull(annotation)){
                        return null;
                    }
                    return annotation.value();
                })
                .filter(CommonConstants.GROUP_CONSTANT::contains)
                .collect(Collectors.toList());

    }

}
