package com.ruoyi.web.core.config;

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

import java.util.Date;

/**
 * description: 自定义元数据自动填充功能
 *
 * @author guanxu
 * @date 2023-03-09
 */
@Component
@Slf4j
public class MyMetaObjecthandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("公共字段自动填充[insert]...");
        // 起始版本 3.3.0(推荐使用)
        this.setFieldValByName("createTime",new Date(),metaObject);
        this.setFieldValByName("updateTime",new Date(),metaObject);
        //this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        //this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        try {
            metaObject.setValue("createBy", SecurityUtils.getLoginUser().getUser().getUserName());
        } catch (Exception e) {
            log.trace("没有获取当前登录用户," + e.getMessage(), e);
            metaObject.setValue("createBy", "");
        }
        try {
            metaObject.setValue("updateBy", SecurityUtils.getLoginUser().getUser().getUserName());
        } catch (Exception e) {
            log.trace("没有获取当前登录用户," + e.getMessage(), e);
            metaObject.setValue("updateBy", "");
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("公共字段自动填充[update]...");
        // 起始版本 3.3.0(推荐)
        //this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        this.setFieldValByName("updateTime",new Date(),metaObject);
        try {
            metaObject.setValue("updateBy", SecurityUtils.getLoginUser().getUser().getUserName());
        } catch (Exception e) {
            log.trace("没有获取当前登录用户," + e.getMessage(), e);
            metaObject.setValue("updateBy", "");
        }
    }
}