package com.ema.admin.handler;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.annotation.UpdateListener;
import com.ema.common.domain.base.BaseEntity;
import lombok.extern.slf4j.Slf4j;

/**
 * MyBatisFlex更新监听器
 */
@Slf4j
public class MyBatisFlexUpdateListener implements UpdateListener {

    @Override
    public void onUpdate(Object entity) {
        if (entity instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) entity;
            baseEntity.setUpdateTime(DateUtil.date());
            try {
                baseEntity.setUpdateBy(StrUtil.isNotBlank(baseEntity.getUpdateBy()) ? baseEntity.getUpdateBy()
                        : (StpUtil.isLogin() ? StpUtil.getLoginIdAsString() : "system"));
            } catch (Exception e) {
                // 异步时，无法获取用户登录信息，设置为async
                baseEntity.setUpdateBy("async");
            }
        }
    }
}
