package com.huashe.park.infrastructure.cfg.mybatis;

import java.util.List;

import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
public class RegisterCustomerInterceptor implements ApplicationListener<ContextRefreshedEvent> {
    /**
     * 需要注册的自定义插件
     */
    @Autowired
    private MybatisInterceptor mybatisInterceptor;

    @Autowired
    private TenantSqlInterceptor tenantSqlInterceptor;

    @Autowired
    private TenantIdInterceptor tenantIdInterceptor;

    @Autowired
    private List<SqlSessionFactory> sqlSessionFactories;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        for (SqlSessionFactory factory : sqlSessionFactories) {
            factory.getConfiguration().setObjectWrapperFactory(new MapWrapperFactory());
            // 这里注册的类型处理不能在mybatis启动的时候注册，所以需要在framework的工程里面MybatisConfig中注册,才能在rs字段映射的时候起作用。
            // 这里注册只能是已经是默认转换完了在进行转换，可以转换同类型的字段比如字段的加解密
            // factory.getConfiguration().getTypeHandlerRegistry().register(new MySqlJsonHandler<>());
            // 由于mybatis拦截器使用责任链模式,有可能会导致自定义拦截器失效,因此下面方法可以将自定义拦截器重新注入到sql中
            factory.getConfiguration().addInterceptor(tenantSqlInterceptor);
            factory.getConfiguration().addInterceptor(tenantIdInterceptor);
            factory.getConfiguration().addInterceptor(mybatisInterceptor);
            // factory.getConfiguration().addInterceptor(new FieldConvertInterceptor());
        }
    }
}
