package cn.axzo.msg.center.notices.client.config;

import cn.axzo.msg.center.domain.persistence.BaseEntity;
import cn.axzo.msg.center.domain.persistence.BaseOwnEntity;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

@Slf4j
public class EntityMetaObjectHandler implements MetaObjectHandler {

  @Override
  public void insertFill(MetaObject metaObject) {
    Object entity = metaObject.getOriginalObject();
    Date now = new Date();
    if (entity instanceof BaseEntity) {
      //默认有值不覆盖
      this.fillStrategy(metaObject, "createAt", now);
      this.fillStrategy(metaObject, "updateAt", now);
    }

    if (entity instanceof BaseOwnEntity) {
      //默认有值不覆盖
      this.fillStrategy(metaObject, "createBy", "");
      this.fillStrategy(metaObject, "updateBy", "");
    }
  }

  @Override
  public void updateFill(MetaObject metaObject) {
    Object entity = metaObject.getOriginalObject();
    if (entity instanceof BaseEntity) {
      //强制覆盖
      this.setFieldValByName("updateAt", new Date(), metaObject);
    }

    if (entity instanceof BaseOwnEntity) {
      //强制覆盖
      this.setFieldValByName("updateBy", "", metaObject);
    }
  }


}