package com.zsc.bill.framework.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zsc.bill.framework.security.SecurityUtil;
import com.zsc.bill.framework.security.UserDetailsImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

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

/**
 * @author Yao
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        UserDetailsImpl userInfo = SecurityUtil.getUserInfo();
        this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class);
        this.strictInsertFill(metaObject, "createdBy", String.class, Objects.nonNull(userInfo) ? userInfo.getUsername() : "");

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        UserDetailsImpl userInfo = SecurityUtil.getUserInfo();
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
        this.strictUpdateFill(metaObject, "updatedBy", String.class, Objects.nonNull(userInfo) ? userInfo.getUsername() : "");

    }

}