package org.eco.common.orm.listener;

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

import java.util.Date;

/**
 * Entity实体类全局插入数据监听器
 *
 * @author wgk
 */
public class EntityInsertListener implements InsertListener {

    @Override
    public void onInsert(Object entity) {
        try {
            if (ObjectUtil.isNotNull(entity) && (entity instanceof BaseEntity baseEntity)) {
                Long loginUserId = LoginHelper.getUserId();
                Date createTime = ObjectUtil.isNotNull(baseEntity.getCreateTime())
                    ? baseEntity.getCreateTime() : new Date();
                if (ObjectUtil.isNull(baseEntity.getCreateBy())) {
                    baseEntity.setCreateBy(loginUserId);
                }
                baseEntity.setCreateTime(createTime);
                if (ObjectUtil.isNull(baseEntity.getUpdateBy())) {
                    baseEntity.setUpdateBy(loginUserId);
                }
                baseEntity.setUpdateTime(createTime);
            }
        } catch (Exception e) {
            throw new BusinessException("全局插入数据监听器注入异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);
        }
    }
}
