package com.ruoyi.framework.mybatis.holder;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

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

    private static final String CREATE_USER = "createUser";

    private static final String CREATE_TIME = "createTime";

    private static final String UPDATE_USER = "updateUser";

    private static final String UPDATE_TIME = "updateTime";

    private static final String VERSION_FLAG = "version";

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

        if (ObjectUtil.isNotEmpty(metaObject.hasSetter(CREATE_USER))) {
            setFieldValByName(CREATE_USER, userUniqueId, metaObject);
        }
        if (ObjectUtil.isNotEmpty(metaObject.hasSetter(CREATE_TIME))) {
            setFieldValByName(CREATE_TIME, date, metaObject);
        }
        if (ObjectUtil.isNotEmpty(metaObject.hasSetter(UPDATE_USER))) {
            setFieldValByName(UPDATE_USER, userUniqueId, metaObject);
        }
        if (ObjectUtil.isNotEmpty(metaObject.hasSetter(UPDATE_TIME))) {
            setFieldValByName(UPDATE_TIME, date, metaObject);
        }
        if (ObjectUtil.isNotEmpty(metaObject.hasSetter(VERSION_FLAG))) {
            setFieldValByName(VERSION_FLAG, 0, metaObject);
        }
    }

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

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

}
