package com.dashitech.callcenter.init;

import com.dashitech.businessdata.dao.ISystemConfigureDAO;
import com.dashitech.callcenter.socket.HandlerThread;
import com.dashitech.utils.ThreadPoolFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by chi on 2020/8/25.
 */
@Service
public class SocketInit implements ApplicationRunner {

    @Autowired
    ISystemConfigureDAO systemConfigureDAO;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //如果系统配置表的开关字段为1则连接话机socket 否则不连
        if (systemConfigureDAO.selectValueByKey("callSocketSwitch").equals("1")) {
            int PORT = 8087;
            // TODO Auto-generated method stub
            ServerSocket sock = null;
            sock = new ServerSocket(PORT);

            try {
                while (true) {
                    final Socket Client = sock.accept();
                //    System.out.println("1111111111111111");
                    //启动一个线程执行后续客户端发来的监听
                    ThreadPoolFactory.getCachedPool().submit(new Runnable() {
                        @Override
                        public void run() {
                            new HandlerThread(Client).run();
                //            System.out.println("22222222222222222");
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (sock != null) {
                    try {
                        sock.close();
                        System.out.println("电话socket关闭连接");
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        } else {
            System.out.println("callSocketSwitch 字段未开启");
        }
    }
}
