/**
 * 
 */
package com.tzy.framework.datasource;

import com.tzy.framework.config.ServerModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zheng
 *
 */
@Service
public class DBChangeServiceImpl implements DBChangeService {

		//数据库连接信息
	    @Value("${spring.datasource.druid.master.url}")
	    private String dbUrl;
	    @Value("${spring.datasource.druid.master.username}")
	    private String username;
	    @Value("${spring.datasource.druid.master.password}")
	    private String password;
	    @Value("${spring.datasource.driverClassName}")
	    private String driverClassName;
	    
	    
	    @Autowired
	    private DynamicDataSource dynamicDataSource;

	    @Override
	    public boolean changeDb(String datasourceId) throws Exception {
	 
	        //默认切换到主数据源,进行整体资源的查找
	        DynamicDataSourceContextHolder.clearDataSource();
	 
	        List<ServerModel> dataSourcesList = getServerList();//dataSourceMapper.get();
	 
	        for (ServerModel dataSource : dataSourcesList) {
	            if (dataSource.getCustNo().equals(datasourceId)) {
	                System.out.println("需要使用的的数据源已经找到,datasourceId是：" + dataSource.getCustNo());
	                //创建数据源连接&检查 若存在则不需重新创建
	                dynamicDataSource.createDataSourceWithCheck(dataSource);
	                //切换到该数据源
	                DynamicDataSourceContextHolder.setDataSource(dataSource.getCustNo());
	                return true;
	            }
	        }
	        return false;
	    }

	    /**
	     * 查询所有数据库
	     *
	     * @return
	     */
	    @Override
	    public List<ServerModel> getServerList() {
	        Connection conn = null;
	        String sql;
	        List<ServerModel> lists = new ArrayList<>();
	        try {
	            Class.forName(driverClassName);
	            conn = DriverManager.getConnection(dbUrl, username, password);
	            Statement stmt = conn.createStatement();
	            sql = "select * from cust_info where status='有效'";
	            ResultSet rs = stmt.executeQuery(sql);
	            while (rs.next()) {
	                ServerModel server = new ServerModel();
	                server.setCustNo(rs.getString("cust_no"));
	                server.setServerName(rs.getString("server_name"));
	                server.setDbUser(rs.getString("db_user"));
	                server.setDbPassword(rs.getString("db_password"));
	                lists.add(server);
	            }
	        } catch (SQLException e) {
	            System.out.println("数据库操作错误");
	            e.printStackTrace();
	        } catch (Exception e) {
	            e.printStackTrace();
	        } finally {
	            try {
	                conn.close();
	            } catch (Exception e) {
	            }
	        }
	        return lists;
	    }
}
