package com.ruoyi.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

@Component
public class AutoFillHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        boolean hasCreateBy = metaObject.hasSetter("createBy");
        boolean hasCreateTime = metaObject.hasSetter("createTime");

        if (hasCreateBy || hasCreateTime) {
            String userId = null;
            try {
                userId = Convert.toStr(SecurityUtils.getUserId());
            } catch (Exception ignore) {}

            if (StringUtils.isNotBlank(userId) && hasCreateBy) {
                metaObject.setValue("createBy", userId);
            }
            if (hasCreateTime) {
                metaObject.setValue("createTime", DateUtils.getNowDate());
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        boolean hasUpdateBy = metaObject.hasSetter("updateBy");
        boolean hasUpdateTime = metaObject.hasSetter("updateTime");

        if (hasUpdateBy || hasUpdateTime) {
            String userId = null;
            try {
                userId = Convert.toStr(SecurityUtils.getUserId());
            } catch (Exception ignore) {}

            if (StringUtils.isNotBlank(userId) && hasUpdateBy) {
                metaObject.setValue("updateBy", userId);
            }
            if (hasUpdateTime) {
                metaObject.setValue("updateTime", DateUtils.getNowDate());
            }
        }
    }
}
