package com.ruoyi.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;

import java.util.Date;
import java.util.function.Supplier;

/**
 * @author fangk
 * @date 2024/5/14
 * @desc MybatisPlusConfig mp自动填充配置
 */
@Slf4j
@Configuration
public class MybatisPlusConfig implements MetaObjectHandler {

    private static final Supplier<String> GET_USER_ID = () -> {
        try {
            return SecurityUtils.getStrUserId();
        } catch (Exception e) {
            // log.warn("自动填充创建人：获取当前用户失败！请检查是否登录或者异步调用情况");
            log.warn("Auto fill in the creator: Failed to get the current user! Please check whether you are logged in or in an asynchronous call");
            return null;
        }
    };


    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        // 起始版本 3.3.0(推荐使用)
        //this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        // 或者 // 起始版本 3.3.3(推荐)
        this.strictInsertFill(metaObject, "createTime", Date::new, Date.class);
        //this.strictInsertFill(metaObject, "createTime", LocalDate::now, LocalDate.class);

        // 或者 // 也可以使用(3.3.0 该方法有bug)
        //this.fillStrategy(metaObject, "createTime", LocalDateTime.now());

        // 插入创建人
        this.strictInsertFill(metaObject, "createBy", String.class, GET_USER_ID.get());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        // 起始版本 3.3.0(推荐)
        //this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        // 或者 // 起始版本 3.3.3(推荐)
        this.strictUpdateFill(metaObject, "updateTime", Date::new, Date.class);
        // 或者 // 也可以使用(3.3.0 该方法有bug)
        //this.fillStrategy(metaObject, "updateTime", LocalDateTime.now());

        // 更新修改人
        this.strictUpdateFill(metaObject, "updateBy", String.class, GET_USER_ID.get());
    }
}