package com.njzscloud.common.mp.support;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.njzscloud.common.security.support.UserDetail;
import com.njzscloud.common.security.util.SecurityUtil;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;
import java.util.function.Supplier;

/**
 * 字段填充
 * 填充字段：createTime、creatorId、modifyTime、modifierId
 */
public class MetaObjectHandlerImpl implements MetaObjectHandler {
    /**
     * 获取当前登录人 Id，默认：0
     */
    public static final Supplier<Long> OPERATOR_ID_SUPPLIER = () -> {
        UserDetail userDetail = SecurityUtil.loginUser();
        Long userId = 0L;
        if (userDetail != null) userId = userDetail.getUserId();
        if (userId == null) userId = 0L;
        return userId;
    };
    public static final Supplier<Long> TENANT_ID_SUPPLIER = () -> {
        UserDetail userDetail = SecurityUtil.loginUser();
        Long tenantId = 0L;
        if (userDetail != null) tenantId = userDetail.getTenantId();
        if (tenantId == null) tenantId = 0L;
        return tenantId;
    };

    public static final Supplier<LocalDateTime> OPERATOR_TIME_SUPPLIER = LocalDateTime::now;

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", OPERATOR_TIME_SUPPLIER, LocalDateTime.class);
        this.strictInsertFill(metaObject, "creatorId", OPERATOR_ID_SUPPLIER, Long.class);

        this.strictInsertFill(metaObject, "modifyTime", OPERATOR_TIME_SUPPLIER, LocalDateTime.class);
        this.strictInsertFill(metaObject, "modifierId", OPERATOR_ID_SUPPLIER, Long.class);
        this.strictInsertFill(metaObject, "tenantId", TENANT_ID_SUPPLIER, Long.class);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "modifyTime", OPERATOR_TIME_SUPPLIER, LocalDateTime.class);
        this.strictUpdateFill(metaObject, "modifierId", OPERATOR_ID_SUPPLIER, Long.class);
    }
}
