package org.security.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springblade.core.secure.utils.AuthUtil;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;

@Slf4j
@Component
public class SecurityMetaObjectHandler implements MetaObjectHandler {

	//插入时的填充策略
	@Override
	public void insertFill(MetaObject metaObject) {

		this.setFieldValByName("createdBy", Optional.ofNullable(String.valueOf(AuthUtil.getUserId())).orElse(""), metaObject);
		this.setFieldValByName("updatedBy", Optional.ofNullable(String.valueOf(AuthUtil.getUserId())).orElse(""), metaObject);
		this.setFieldValByName("createdTime", new Date(), metaObject);
		this.setFieldValByName("updatedTime", new Date(), metaObject);
	}

	//更新时的填充策略
	@Override
	public void updateFill(MetaObject metaObject) {

		this.setFieldValByName("updatedTime", new Date(), metaObject);
		this.setFieldValByName("updatedBy", Optional.ofNullable(String.valueOf(AuthUtil.getUserId())).orElse(""), metaObject);
	}
}
