package com.fzm.mall.server.admin.util;

import com.fzm.mall.server.admin.constant.MallResponseError;
import com.fzm.mall.server.admin.enums.response.MallResponseEnum;
import com.fzm.mall.server.admin.exception.MyException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

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

/**
 * @author wangp
 * @date 2020/8/12 14:40
 * @description 对象工具类
 * @since JDK 1.8
 */
@Slf4j
public class ObjectUtil {

    /**
     * 判断对象中属性值是否为空
     *
     * @param object 待判空的对象
     * @return 判空结果
     */
    public static <T> void checkObjFieldsIsNull(T object, String... ignoreField) {
        List<String> ignoreFields = ignoreField == null ? null : Arrays.asList(ignoreField);
        try {
            for (Field field : object.getClass().getDeclaredFields()) {
                field.setAccessible(true);
                if (ignoreFields != null && ignoreFields.contains(field.getName())) {
                    continue;
                }
                Object obj = field.get(object);
                if (obj == null || StringUtils.isBlank(obj.toString())) {
                    throw new MyException(MallResponseError.NULL_PARAM_ERROR);
                }
            }
        } catch (IllegalAccessException e) {
            log.error("判断对象是否为空出错：" + e.getMessage());
            throw new MyException(MallResponseEnum.FAIL.code());
        }
    }

    /**
     * 判断对象中属性值是否为空
     *
     * @param object 待判空的对象
     * @return 判空结果
     */
    public static <T> void checkObjFieldsIsNull(T object) {
        try {
            for (Field field : object.getClass().getDeclaredFields()) {
                field.setAccessible(true);
                Object obj = field.get(object);
                if (obj == null || StringUtils.isBlank(obj.toString())) {
                    throw new MyException(MallResponseError.NULL_PARAM_ERROR);
                }
            }
        } catch (IllegalAccessException e) {
            log.error("判断对象是否为空出错：" + e.getMessage());
            throw new MyException(MallResponseEnum.FAIL.code());
        }
    }


}
