package com.gitee.sop.admin.common.fill;

import com.gitee.fastmybatis.core.handler.BaseFill;
import com.gitee.fastmybatis.core.handler.FillType;
import com.gitee.sop.admin.common.context.UserContext;
import com.gitee.sop.admin.common.user.User;

import java.lang.reflect.Field;
import java.util.Objects;

/**
 * 保存到数据库自动设置添加人
 *
 * @author 六如
 */
public class AddByFill extends BaseFill<Long> {

    private static final String ADD_BY = "addBy";

    @Override
    public FillType getFillType() {
        return FillType.INSERT;
    }

    @Override
    protected Object getFillValue(Long defaultValue) {
        if (defaultValue != null) {
            return defaultValue;
        }
        User user = UserContext.getUser();
        return user != null ? user.getUserId() : 0L;
    }

    @Override
    protected Long convertValue(Object columnValue) {
        if (columnValue == null) {
            return null;
        }
        if (columnValue instanceof Long) {
            return (Long) columnValue;
        }
        return Long.parseLong(String.valueOf(columnValue));
    }

    protected String getTargetFieldName() {
        return ADD_BY;
    }

    @Override
    public boolean match(Class<?> entityClass, Field field, String columnName) {
        return Objects.equals(getTargetFieldName(), field.getName());
    }
}
