package cn.axzo.msg.center.notices.client.config;

import cn.axzo.msg.center.domain.utils.IgnorePropsJsonTypeHandler;
import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

/**
 * Mybatis Plus Config
 *
 * @author zhaoyong_sh
 * @see MybatisPlusConfig
 * @since 2021-05-19 10:24
 */
@Configuration
public class MybatisPlusConfig {

    @Bean
    public EntityMetaObjectHandler EntityMetaObjectHandler() {
        return new EntityMetaObjectHandler();
    }

    @Component
    public static class JsonObjectTypeHandlerRegister implements BeanPostProcessor {

        @Override
        public Object postProcessAfterInitialization(@NotNull Object bean, @NotNull String beanName) throws BeansException {
            if (!(bean instanceof SqlSessionFactory))
                return bean;
            org.apache.ibatis.session.Configuration configuration = ((SqlSessionFactory) bean).getConfiguration();
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            if(!typeHandlerRegistry.hasTypeHandler(JSONObject.class)) {
                typeHandlerRegistry.register(JSONObject.class, IgnorePropsJsonTypeHandler.class);
            }
            return bean;
        }

    }
}