package com.simuwang.base.components;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.simuwang.shiro.core.ShiroUser;
import com.simuwang.shiro.utils.UserUtils;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * @author wangzaijun
 * @date 2024/9/14 15:58
 * @description 默认的字段填充
 */
public class MyBatisPlusMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        ShiroUser loginUser = UserUtils.getLoginUser();
        this.setFieldValByName("creatorId", loginUser.getUserId(), metaObject);
        this.strictInsertFill(metaObject, "createTime", Date::new, Date.class);
        if (metaObject.hasGetter("valid")) {
            this.setFieldValByName("valid", 1, metaObject);
        }
        if (metaObject.hasGetter("updaterId")) {
            this.setFieldValByName("updaterId", loginUser.getUserId(), metaObject);
        }
        if (metaObject.hasGetter("updateTime")) {
            this.strictInsertFill(metaObject, "updateTime", Date::new, Date.class);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        ShiroUser loginUser = UserUtils.getLoginUser();
        this.setFieldValByName("updaterId", loginUser.getUserId(), metaObject);
        this.strictUpdateFill(metaObject, "updateTime", Date::new, Date.class);
    }
}
