package com.elab.spring.config;

import com.elab.spring.config.prop.SpringAutoProperties;
import com.elab.spring.intercept.SQLMonitorEventHandler;
import com.elab.spring.intercept.SQLMonitorPostCallback;
import com.elab.spring.monitor.JayMonitorServiceCollect;
import com.elab.spring.monitor.MonitorCollect;
import com.elab.spring.monitor.ServiceMonitorDataCollect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

/**
 * 公共的MVC层的解析器定义
 *
 * @author : liukx
 * @create : 2018/6/4 16:47
 * @email : liukx@elab-plus.com
 */
@Configuration
@EnableConfigurationProperties(SpringAutoProperties.class)
public class SpringMvcConfig {

    /**
     * 构建一个文件上传解析器
     *
     * @return
     */
    @Bean(name = "multipartResolver")
    public MultipartResolver getCommonsMultipartResolver(@Autowired Environment env) {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        multipartResolver
            .setMaxUploadSize(Long.valueOf(env.getProperty("mvc.multipartResolver.MaxUploadSize", "10485760")));
        multipartResolver.setDefaultEncoding("UTF-8");
        return multipartResolver;
    }

    @Bean
    public SQLMonitorEventHandler sqlMonitorEventHandler(@Autowired Environment env) {
        SQLMonitorEventHandler sqlMonitorEventHandler = new SQLMonitorEventHandler();
        sqlMonitorEventHandler.setAffectNumber(Integer.valueOf(env.getProperty("default.affectNumber", "100")));
        return sqlMonitorEventHandler;
    }

    @Bean
    public SQLMonitorPostCallback sqlMonitorPostCallback(@Autowired Environment env) {
        SQLMonitorPostCallback sqlMonitorPostCallback = new SQLMonitorPostCallback();
        return sqlMonitorPostCallback;
    }

    @Bean
    @ConditionalOnMissingBean(value = {ServiceMonitorDataCollect.class})
    public ServiceMonitorDataCollect serviceMonitorDataCollect() {
        JayMonitorServiceCollect jayMonitorServiceCollect = new JayMonitorServiceCollect();
        // 注册到收集器中
        MonitorCollect.getINSTANCE().register(jayMonitorServiceCollect);
        return jayMonitorServiceCollect;
    }
}
