package com.zbf.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zbf.common.annotation.NoAutoFill;
import com.zbf.common.core.domain.entity.SysUser;
import com.zbf.common.core.domain.model.LoginUser;
import com.zbf.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.lang.reflect.Type;
import java.util.Date;

/**
 * mybatis拦截器，自动填充创建人、创建时间、修改人、修改时间
 *
 * @Author wgs
 * @Date 2024-6-24
 */
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            Object entity = metaObject.getOriginalObject();
            Type entityType = entity.getClass().getGenericSuperclass();
//            SysUser sysUser = SecurityUtils.getLoginUser().getUser();
            LoginUser loginUser = SecurityUtils.getLoginUser();

            if(loginUser == null ){
               return;
            }
            SysUser sysUser = loginUser.getUser();
            if (shouldAutoFill(entityType) && sysUser != null) {
                // 实现自动填充逻辑，如创建时间和创建人
                setFieldValByName("createTime", new Date(), metaObject);
                setFieldValByName("createBy", sysUser.getNickName(), metaObject);
            }
        } catch (Exception e) {
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            Object entity = metaObject.getOriginalObject();
            Type entityType = entity.getClass().getGenericSuperclass();
            LoginUser loginUser = SecurityUtils.getLoginUser();

            if(loginUser == null ){
                return;
            }
            SysUser sysUser = loginUser.getUser();
            
            if (shouldAutoFill(entityType) && sysUser != null) {
                // 实现自动填充逻辑，如创建时间和创建人
                setFieldValByName("updateTime", new Date(), metaObject);
                setFieldValByName("updateBy", sysUser.getNickName(), metaObject);
            }
        } catch (Exception e) {
        }
    }

    private boolean shouldAutoFill(Type entityType) {
        if (entityType instanceof Class) {
            Class<?> clazz = (Class<?>) entityType;
            // 检查是否实现了NoAutoFill接口
            return !NoAutoFill.class.isAssignableFrom(clazz);
            // 或者，如果是使用注解，则使用反射检查是否存在@NoAutoFill注解
            // return !clazz.isAnnotationPresent(NoAutoFill.class);
        }
        return true; // 默认处理
    }
}
