/*
 * Copyright (c) 2023 codvision.com All Rights Reserved.
 */

package com.codvision.base.support;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.codvision.authcore.bean.SysUserBean;
import com.codvision.authcore.util.AuthUtil;
import com.codvision.authcore.util.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 基础对象处理器
 *
 * @author lingee
 * @date 2023/9/11
 */
@Slf4j
@Component
public class BaseObjectHandler implements MetaObjectHandler {


    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "deleteFlag", Boolean.class, Boolean.FALSE);
        if (ObjectUtils.isEmpty(RequestUtil.getRequest()) || StrUtil.isBlank(AuthUtil.getToken())) {
            return;
        }
        SysUserBean sysUser = AuthUtil.getCurrentUser();
        this.strictInsertFill(metaObject, "createBy", Long.class, sysUser.getId());
        this.strictInsertFill(metaObject, "createByName", String.class, sysUser.getName());
        this.strictInsertFill(metaObject, "updateBy", Long.class, sysUser.getId());
        this.strictInsertFill(metaObject, "updateByName", String.class, sysUser.getName());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
        if (ObjectUtils.isEmpty(RequestUtil.getRequest()) || StrUtil.isBlank(AuthUtil.getToken())) {
            return;
        }
        SysUserBean sysUser = AuthUtil.getCurrentUser();
        this.strictUpdateFill(metaObject, "updateBy", Long.class, sysUser.getId());
        this.strictUpdateFill(metaObject, "updateByName", String.class, sysUser.getName());
    }
}
