package com.bonus.canteen.core.common.utils;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.system.api.model.LoginUser;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

@Component
public class TableFillHandler implements MetaObjectHandler {
   private static final Logger log = LoggerFactory.getLogger(TableFillHandler.class);

   public void insertFill(MetaObject metaObject) {
      this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class);
      LoginUser loginUser = SecurityUtils.getLoginUser();
      if(Objects.nonNull(loginUser)) {
         loginUser.setUsername(SecurityUtils.getUsername());
         loginUser.setUserid(SecurityUtils.getUserId());
         Objects.requireNonNull(loginUser);
         this.strictInsertFill(metaObject, "createBy", loginUser::getUsername, String.class);
         this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
         loginUser.setUsername(SecurityUtils.getUsername());
         loginUser.setUserid(SecurityUtils.getUserId());
         Objects.requireNonNull(loginUser);
         this.strictUpdateFill(metaObject, "updateBy", loginUser::getUsername, String.class);
      }
   }

   public void updateFill(MetaObject metaObject) {
      this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
      LoginUser loginUser = SecurityUtils.getLoginUser();
      if(Objects.nonNull(loginUser)) {
         loginUser.setUsername(SecurityUtils.getUsername());
         Objects.requireNonNull(loginUser);
         this.strictUpdateFill(metaObject, "updateBy", loginUser::getUsername, String.class);
      }
   }
}
