package com.ruoyi.framework.config;


import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

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

/**
 * 自动注入
 *
 * @author wu
 * @since 2023/5/4 10:16
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        // 获取当前登录用户

        String userName = null;
        Long userId = null;
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            userName = loginUser.getUser().getNickName();
            userId = SecurityUtils.getUserId();
        } catch (Exception ignored) {
        }
        if (!Objects.equals(userName, "")) {
            this.strictInsertFill(metaObject, "createBy", String.class, userName);
            this.strictInsertFill(metaObject, "updateBy", String.class, userName);
        }
        if (userId != null) {
            this.strictInsertFill(metaObject, "createId", Long.class, userId);
            this.strictInsertFill(metaObject, "updateId", Long.class, userId);
        }
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 获取当前登录用户
        String userName = null;
        Long userId = null;
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            userName = loginUser.getUser().getNickName();
            userId = SecurityUtils.getUserId();
        } catch (Exception ignored) {
        }
        if (userId != null) {
            this.strictUpdateFill(metaObject, "updateId", Long.class, userId);
        }
        if (!Objects.equals(userName, "")) {
            this.strictUpdateFill(metaObject, "updateBy", String.class, userName);
        }
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }
}
