package cn.qinys.platform.config;

import cn.qinys.platform.base.security.utils.CurrentUtils;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

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

/**
 * MyBatis-Plus 自动填充处理器：
 * - 支持 Java 字段类型 LocalDateTime / java.util.Date / Long (时间戳毫秒)
 * - 填充字段名为 createdAt / updatedAt（与实体属性匹配，不依赖数据库列名）
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    private static final String CREATED_FIELD = "createdAt";
    private static final String UPDATED_FIELD = "updatedAt";
    private static final String CREATED_BY_FIELD = "createdBy";
    private static final String UPDATED_BY_FIELD = "updatedBy";

    @Override
    public void insertFill(MetaObject metaObject) {
        // createdAt
        Object createdVal = getFieldValByName(CREATED_FIELD, metaObject);
        if (Objects.isNull(createdVal) && hasGetter(metaObject, CREATED_FIELD)) {
            Class<?> type = getFieldType(metaObject, CREATED_FIELD);
            if (type != null && LocalDateTime.class.isAssignableFrom(type)) {
                this.setFieldValByName(CREATED_FIELD, LocalDateTime.now(), metaObject);
            } else if (type != null && Date.class.isAssignableFrom(type)) {
                this.setFieldValByName(CREATED_FIELD, new Date(), metaObject);
            } else if (type != null && (Long.class.isAssignableFrom(type) || long.class.isAssignableFrom(type))) {
                this.setFieldValByName(CREATED_FIELD, System.currentTimeMillis(), metaObject);
            }
        }

        // updatedAt -> for insert also set updatedAt
        Object updatedVal = getFieldValByName(UPDATED_FIELD, metaObject);
        if (Objects.isNull(updatedVal) && hasGetter(metaObject, UPDATED_FIELD)) {
            Class<?> type = getFieldType(metaObject, UPDATED_FIELD);
            if (type != null && LocalDateTime.class.isAssignableFrom(type)) {
                this.setFieldValByName(UPDATED_FIELD, LocalDateTime.now(), metaObject);
            } else if (type != null && Date.class.isAssignableFrom(type)) {
                this.setFieldValByName(UPDATED_FIELD, new Date(), metaObject);
            } else if (type != null && (Long.class.isAssignableFrom(type) || long.class.isAssignableFrom(type))) {
                this.setFieldValByName(UPDATED_FIELD, System.currentTimeMillis(), metaObject);
            }
        }

        // createdBy / updatedBy (set from current user)
        String current = CurrentUtils.getCurrentUsername();
        if (current == null || current.isEmpty()) {
            current = "system";
        }
        if (hasGetter(metaObject, CREATED_BY_FIELD)) {
            Object createdByVal = getFieldValByName(CREATED_BY_FIELD, metaObject);
            if (Objects.isNull(createdByVal)) {
                this.setFieldValByName(CREATED_BY_FIELD, current, metaObject);
            }
        }
        if (hasGetter(metaObject, UPDATED_BY_FIELD)) {
            Object updatedByVal = getFieldValByName(UPDATED_BY_FIELD, metaObject);
            if (Objects.isNull(updatedByVal)) {
                this.setFieldValByName(UPDATED_BY_FIELD, current, metaObject);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (hasGetter(metaObject, UPDATED_FIELD)) {
            Class<?> type = getFieldType(metaObject, UPDATED_FIELD);
            if (type != null && LocalDateTime.class.isAssignableFrom(type)) {
                this.setFieldValByName(UPDATED_FIELD, LocalDateTime.now(), metaObject);
            } else if (type != null && Date.class.isAssignableFrom(type)) {
                this.setFieldValByName(UPDATED_FIELD, new Date(), metaObject);
            } else if (type != null && (Long.class.isAssignableFrom(type) || long.class.isAssignableFrom(type))) {
                this.setFieldValByName(UPDATED_FIELD, System.currentTimeMillis(), metaObject);
            }
        }
        // updatedBy
        if (hasGetter(metaObject, UPDATED_BY_FIELD)) {
            String current = CurrentUtils.getCurrentUsername();
            if (current == null || current.isEmpty()) {
                current = "system";
            }
            this.setFieldValByName(UPDATED_BY_FIELD, current, metaObject);
        }
    }

    private boolean hasGetter(MetaObject metaObject, String name) {
        try {
            return metaObject.hasGetter(name);
        } catch (Exception e) {
            return false;
        }
    }

    private Class<?> getFieldType(MetaObject metaObject, String name) {
        try {
            Class<?> t = metaObject.getSetterType(name);
            if (t == null) {
                t = metaObject.getGetterType(name);
            }
            return t;
        } catch (Exception e) {
            return null;
        }
    }
}

