package com.ningdatech.pmapi.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ningdatech.pmapi.user.util.LoginUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

import static com.ningdatech.pmapi.common.constant.BaseFieldConst.*;

/**
 * <p>
 * 字段自动填充处理
 * </p>
 *
 * @author WendyYang
 * @since 17:20 2022/11/24
 */
@Slf4j
@Component
public class BaseFieldFillHandler implements MetaObjectHandler {

    private Long getUserId() {
        if (LoginUserUtil.isLogin()) {
            return LoginUserUtil.getUserId();
        }
        return 0L;
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        long userId = getUserId();
        LocalDateTime now = LocalDateTime.now();
        this.fillStrategy(metaObject, CREATE_BY, userId);
        this.fillStrategy(metaObject, CREATE_ON, now);
        this.fillStrategy(metaObject, UPDATE_BY, userId);
        this.fillStrategy(metaObject, UPDATE_ON, now);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.fillStrategy(metaObject, UPDATE_BY, getUserId());
        this.fillStrategy(metaObject, UPDATE_ON, LocalDateTime.now());
    }

}