package com.ktg.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ktg.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

/**
 * mybatis-plus自动填充
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    // 设置默认账号，获取用户失败时
    private final String defaultAccountId = "0";
    @Override
    public void insertFill(MetaObject metaObject) {
        String userId;
        try {
            userId = String.valueOf(SecurityUtils.getLoginUser().getUserId());
        } catch (Exception e){
            log.error("获取登录用户信息失败，给予默认用户信息");
            userId = defaultAccountId;
        }
        this.strictInsertFill(metaObject,"createBy", String.class, userId);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String userId;
        try {
            userId = String.valueOf(SecurityUtils.getLoginUser().getUserId());
        } catch (Exception e){
            log.error("获取登录用户信息失败，给予默认用户信息");
            userId = defaultAccountId;
        }
        this.strictUpdateFill(metaObject,"updateBy", String.class, userId);
    }
}
