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.InsertListener;
import com.ema.common.domain.base.BaseEntity;
import com.ema.common.domain.enums.BooleanEnum;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Date;

/**
 * MyBatisFlex插入监听器
 */
public class MyBatisFlexInsertListener implements InsertListener {

    @Override
    public void onInsert(Object entity) {
        if (entity == null) {
            return;
        }

        // 1. 处理BaseEntity公共字段
        if (entity instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) entity;
            baseEntity.setDelFlag(BooleanEnum.FALSE.getValue());
            baseEntity.setCreateTime(DateUtil.date());
            baseEntity.setUpdateTime(DateUtil.date());
            try {
                baseEntity.setCreateBy(StrUtil.isNotBlank(baseEntity.getCreateBy()) ? baseEntity.getCreateBy()
                        : (StpUtil.isLogin() ? StpUtil.getLoginIdAsString() : "system"));
                baseEntity.setUpdateBy(StrUtil.isNotBlank(baseEntity.getUpdateBy()) ? baseEntity.getUpdateBy()
                        : (StpUtil.isLogin() ? StpUtil.getLoginIdAsString() : "system"));
            } catch (Exception e) {
                // 异步时，无法获取用户登录信息，设置为async
                baseEntity.setUpdateBy("async");
                baseEntity.setCreateBy("async");
            }
        }

        // 2. 处理所有null字段，字符串给''，数值给0
        setDefaultValues(entity);
    }

    /**
     * 为实体类的null字段设置默认值
     * - String类型：设置为 ""
     * - 数值类型(Integer, Long, Double, Float, BigDecimal)：设置为 0
     * - Date类型：设置为当前时间
     * - Boolean/boolean、集合类型：不处理（保持null）
     */
    private void setDefaultValues(Object entity) {
        Class<?> clazz = entity.getClass();
        Field[] fields = clazz.getDeclaredFields();
        Date now = DateUtil.date();

        for (Field field : fields) {
            field.setAccessible(true);
            try {
                Object value = field.get(entity);
                if (value == null) {
                    Class<?> fieldType = field.getType();

                    // String类型设置为空字符串
                    if (fieldType == String.class) {
                        field.set(entity, "");
                    }
                    // 数值类型设置为0
                    else if (fieldType == Integer.class || fieldType == int.class) {
                        field.set(entity, 0);
                    } else if (fieldType == Long.class || fieldType == long.class) {
                        field.set(entity, 0L);
                    } else if (fieldType == Double.class || fieldType == double.class) {
                        field.set(entity, 0.0);
                    } else if (fieldType == Float.class || fieldType == float.class) {
                        field.set(entity, 0.0f);
                    } else if (fieldType == BigDecimal.class) {
                        field.set(entity, BigDecimal.ZERO);
                    }
                    // Date类型设置为当前时间
                    else if (fieldType == Date.class) {
                        field.set(entity, now);
                    }
                }
            } catch (IllegalAccessException e) {
                // 忽略访问异常
            }
        }
    }
}
