package org.eco.common.orm.listener;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import org.eco.common.core.exception.BusinessException;
import org.eco.common.orm.core.domain.BaseEntity;
import org.eco.common.security.utils.LoginHelper;
import com.mybatisflex.annotation.UpdateListener;

import java.util.Date;

/**
 * Entity实体类全局更新数据监听器
 *
 * @author wgk
 */
public class EntityUpdateListener implements UpdateListener {
    @Override
    public void onUpdate(Object entity) {
        try {
            if (ObjectUtil.isNotNull(entity) && (entity instanceof BaseEntity baseEntity)) {
                if (ObjectUtil.isNull(baseEntity.getUpdateBy())) {
                    baseEntity.setUpdateBy(LoginHelper.getUserId());
                }
                baseEntity.setUpdateTime(new Date());
            }
        } catch (Exception e) {
            throw new BusinessException("全局更新数据监听器注入异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);
        }

    }
}
