package com;

import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import java.net.ServerSocket;
import java.util.Date;

@EnableEurekaClient
@EnableDiscoveryClient
@SpringBootApplication
@ServletComponentScan
@MapperScan(basePackages = {"com.chinaitop.depot.**.mapper"})
public class DepotIntelligentApplication {

	Logger log = LoggerFactory.getLogger(this.getClass());

	public static void main(String[] args) {
		SpringApplication.run(DepotIntelligentApplication.class, args);
	}

	/**
	 * 注册一个dispatcherServlet,解决增加ws之后https接口访问不了问题
	 */
	@Bean
	public ServletRegistrationBean restServlet(){
		//注解扫描上下文
		AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
		//base package
		applicationContext.scan("com.unissoft");
		//通过构造函数指定dispatcherServlet的上下文
		DispatcherServlet rest_dispatcherServlet = new DispatcherServlet(applicationContext);
		//用ServletRegistrationBean包装servlet
		ServletRegistrationBean registrationBean = new ServletRegistrationBean(rest_dispatcherServlet);
		registrationBean.setLoadOnStartup(1);
		//指定urlmapping
		registrationBean.addUrlMappings("/*");
		//指定name，如果不指定默认为dispatcherServlet
		registrationBean.setName("rest");
		return registrationBean;
	}

	@Bean
	public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
		return new ThreadPoolTaskScheduler();
	}

	@Bean(name = "serverSocket")
	@Order
	public ServerSocket serverSocket(){
		ServerSocket server = null;
		try {
			log.info(new Date().toString() + "***开启监听扫描端口：2001***");
			server = new ServerSocket(2001);
			//超过10秒没有连接返回数据自动断开连接 8899
//            server.setSoTimeout(20000);
		}catch (Exception e){
			e.printStackTrace();
			log.error("监听扫描端口失败:"+e.getMessage());
		}
		return  server;
	}
}
