package com.mcwl.common.handler;

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

import java.util.Date;


/**
 * mybatis-plus 自动填充处理器
 */

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {


    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            this.strictInsertFill(metaObject, "createBy", String.class, SecurityUtils.getLoginUser().getUser().getNickName());
        } catch (Exception e) {
            this.strictInsertFill(metaObject, "createBy", String.class, "");
        }

        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        try {
            this.strictInsertFill(metaObject, "tenantId", Long.class, SecurityUtils.getUserId());
        } catch (Exception e) {
            this.strictInsertFill(metaObject, "tenantId", Long.class, -1L);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            this.setFieldValByName("updateBy", SecurityUtils.getLoginUser().getUser().getNickName(), metaObject);
        } catch (Exception e) {
            this.setFieldValByName("updateBy", "", metaObject);
        }
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }
}