package com.jy.framework.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.jy.framework.satoken.LoginContext;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * 自定义sql字段填充器，自动填充创建修改相关字段
 */
public class CustomMetaObjectHandler implements MetaObjectHandler {

    public static final String CREATE_USER = "createUser";

    public static final String CREATE_TIME = "createTime";

    public static final String UPDATE_USER = "updateUser";

    public static final String UPDATE_TIME = "updateTime";

    public static final String DEL_FLAG = "delFlag";

    public static final String MP_VERSION = "mpVersion";

    /**
     * 新增模块时，需要添加的字段
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Long userId = getUserId();
        Date date = new Date();

        setFieldValByName(CREATE_USER, userId, metaObject);
        setFieldValByName(CREATE_TIME, date, metaObject);
        setFieldValByName(UPDATE_USER, userId, metaObject);
        setFieldValByName(UPDATE_TIME, date, metaObject);
        setFieldValByName(DEL_FLAG, "0", metaObject);
        setFieldValByName(MP_VERSION, 0, metaObject);
    }

    /**
     * 编辑模块时，需要添加的字段
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        setFieldValByName(UPDATE_USER, getUserId(), metaObject);
        setFieldValByName(UPDATE_TIME, new Date(), metaObject);
    }

    /**
     * 获取用户id
     */
    public Long getUserId() {
        try {
            return LoginContext.getUserId();
        } catch (Exception e) {
            return -1L;
        }
    }

}
