package com.leromro.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.leromro.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        // 设置创建时间和修改时间为当前时间
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());

        // 设置创建人和修改人为当前登录用户，这里假设从某个地方获取当前用户
        String currentUser = getCurrentUser();
        this.strictInsertFill(metaObject, "createBy", String.class, currentUser);
        this.strictInsertFill(metaObject, "updateBy", String.class, currentUser);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 设置修改时间为当前时间
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());

        // 设置修改人为当前登录用户，这里假设从某个地方获取当前用户
        String currentUser = getCurrentUser();
        this.strictUpdateFill(metaObject, "updateBy", String.class, currentUser);
    }

    private String getCurrentUser() {
        String name = "";
        try {
            name =  SecurityUtils.getUsername();
        } catch (Exception e) {
            name = "admin7";
        }
        // 这里可以根据实际情况获取当前登录用户，例如从 SecurityContext 中获取
        return name; // 示例返回值
    }
}
