package com.huashe.park.infrastructure.cfg.mybatis;

import com.huashe.common.annotation.mybatis.TenantField;
import com.huashe.common.exception.ServiceException;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;

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

@Slf4j
public class BaseInterceptor {
    public void setTenantField(Object parameter, Field field) {
        TenantField annotation = field.getAnnotation(TenantField.class);
        if (annotation != null) {
            field.setAccessible(true);
            try {
                field.set(parameter, getLoginUser().getUser().getTenantId());
            }
            catch (Exception e) {
                log.error("------MybatisInterceptor field.name------{},error:", field.getName(), e);
            }
            field.setAccessible(false);
        }
    }

    public LoginUser getLoginUser() {
        LoginUser userNow = new LoginUser();
        userNow.setUser(new SysUser() {
            {
                setNickName(Thread.currentThread().getName());
            }
        });
        try {
            // try catch避免线程任务出错
            userNow = SecurityUtils.getLoginUser() != null ? SecurityUtils.getLoginUser() : null;
        }
        catch (ServiceException e) {
            log.debug("------MybatisInterceptor getLoginUser------");
        }
        return userNow;
    }

    /**
     * 获取类的所有属性，包括父类
     *
     * @param object
     * @return
     */
    public Field[] getAllFields(Object object) {
        Class<?> clazz = object.getClass();
        if (clazz == null) {
            return null;
        }
        List<Field> fieldList = new ArrayList<>();
        while (clazz != null) {
            fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
            clazz = clazz.getSuperclass();
        }
        Field[] fields = new Field[fieldList.size()];
        fieldList.toArray(fields);
        return fields;
    }
}
