package com.dcs.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.dcs.common.exception.ServiceException;
import com.dcs.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

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

/**
 * MyMetaObjectHandler
 *
 * @author: hmy
 * @date: 2025/4/26 10:47
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        String username;
        try {
            username = SecurityUtils.getUsername();
        } catch (ServiceException e) {
            // 任务线程无用户，使用默认用户名
            username = "system";
        }
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "createBy", String.class, username);
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
        this.strictUpdateFill(metaObject, "updateBy", String.class, username);

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String username;
        try {
            username = SecurityUtils.getUsername();
        } catch (ServiceException e) {
            // 任务线程无用户，使用默认用户名
            username = "system";
        }
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
        this.strictUpdateFill(metaObject, "updateBy", String.class, username);
    }
}
