package com.lesingle.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.lesingle.common.util.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * MyBatis-Plus 审计字段自动填充
 * 同时填充新字段（create_by/update_by/deleted）和旧字段（creator/modifier/valid_state）
 */
@Slf4j
@Component
public class AuditMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        String username = SecurityUtil.getCurrentUsername();
        Long userId = SecurityUtil.getCurrentUserIdOrNull();

        // 新审计字段
        this.strictInsertFill(metaObject, "createBy", String.class, username);
        this.strictInsertFill(metaObject, "updateBy", String.class, username);
        this.strictInsertFill(metaObject, "deleted", Integer.class, 0);

        // 旧审计字段
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, now);
        this.strictInsertFill(metaObject, "modifyTime", LocalDateTime.class, now);
        this.strictInsertFill(metaObject, "validState", Integer.class, 1);

        if (userId != null) {
            this.strictInsertFill(metaObject, "creator", Integer.class, userId.intValue());
            this.strictInsertFill(metaObject, "modifier", Integer.class, userId.intValue());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        String username = SecurityUtil.getCurrentUsername();
        Long userId = SecurityUtil.getCurrentUserIdOrNull();

        // 新审计字段
        this.strictUpdateFill(metaObject, "updateBy", String.class, username);

        // 旧审计字段
        this.strictUpdateFill(metaObject, "modifyTime", LocalDateTime.class, now);

        if (userId != null) {
            this.strictUpdateFill(metaObject, "modifier", Integer.class, userId.intValue());
        }
    }
}
