package com.ruoyi.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        String username = "";
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            username = loginUser.getUsername();
        } catch (Exception e) {
            username = "system";
        }
        Date today = new Date();
        this.setFieldValByName("createTime", today, metaObject);
        this.setFieldValByName("updateTime", today, metaObject);
        this.setFieldValByName("createBy", username, metaObject);
        this.setFieldValByName("updateBy", username, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String username = "";
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            username = loginUser.getUsername();
        } catch (Exception e) {
            username = "system";
        }
        Date today = new Date();
        this.setFieldValByName("updateTime", today, metaObject);
        this.setFieldValByName("updateBy", username, metaObject);
    }
}
