package com.jiayue.ssi.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.jiayue.ssi.entity.SysUser;
import com.jiayue.ssi.util.SecurityContextUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
* mybatis自动填充策略
*
* @author xsl
* @since 2023/03/10
*/
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 插入时的填充策略
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        String username = SecurityContextUtil.getSysUser().getUsername();
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "createBy", String.class, username);
    }

    /**
     * 更新时的填充策略
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        String username = SecurityContextUtil.getSysUser().getUsername();
        // 解决不会覆盖原值的情况
        metaObject.setValue("updateTime", null);
        metaObject.setValue("updateBy", null);
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "updateBy", String.class, username);
    }
}
