package com.ozs.mdm.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

/**
 * shell操作工具类
 * 
 * @author yangsy
 *
 */
public class ShellUtils {
	private static final Logger log = LoggerFactory.getLogger(ShellUtils.class);

	private static JSch jsch;
	private static Session session;

	// public static void main(String[] args) throws NumberFormatException,
	// Exception {
	// String str = "find /dyhome/wangyifu/exportfile/customersGroup/ -name
	// 'user_group_20181107182237125.csv' |xargs cat|grep -v ^$|wc -l";
	// int j = Integer
	// .parseInt(execCmd("113.106.54.13", 12022, "wangyifu",
	// "uF5jKW4q8VKmO3GZ5L9POOmFUr9A5lxqQNBoTag", str));
	// System.out.println(j);
	// }

	/**
	 * 连接到指定的IP
	 * 
	 * @throws JSchException
	 */
	public static void connect(String user, String passwd, String host) throws JSchException {
		jsch = new JSch();
		session = jsch.getSession(user, host, 22);
		session.setPassword(passwd);
		java.util.Properties config = new java.util.Properties();
		config.put("StrictHostKeyChecking", "no");
		session.setConfig(config);
		session.connect();
	}

	/**
	 * 执行清单下载相关的命令
	 * 
	 * @throws JSchException
	 */
	public static boolean execCmd(String command, String user, String passwd, String host, long num)
			throws JSchException {
		connect(user, passwd, host);
		boolean flag = false;
		BufferedReader br;
		Channel channel = null;
		try {
			// 执行linux命令
			channel = session.openChannel("exec");
			((ChannelExec) channel).setCommand(command);
			((ChannelExec) channel).setErrStream(System.err);
			channel.connect();
			br = new BufferedReader(new InputStreamReader(channel.getInputStream()));
			StringBuffer sb = new StringBuffer();
			// 文件合并时的客户数
			String customNum = String.valueOf(num);
			// 带表头时的客户数
			String downLoadNum = String.valueOf(num + 1);
			// 导入时的可能出现的文件缺少1条换行符所统计的客户数
			String importCustomNum = String.valueOf(num - 1);
			String line;
			int i = 0;
			while (!flag) {
				i++;
				if (i == 50) {
					break;
				}
				if ((line = br.readLine()) != null) {
					sb.append(line).append("\n");
					String results = sb.toString();
					String[] result = results.split(" ");
					String num1 = result[0];
					if (customNum.equals(num1) || downLoadNum.equals(num1) || importCustomNum.equals(num1)) {
						flag = true;
						break;
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			channel.disconnect();
			session.disconnect();
		}
		return flag;
	}

	/**
	 * ssh到主机上执行命令
	 * 
	 * @param host
	 * @param port
	 * @param user
	 * @param passWord
	 * @param command
	 * @return
	 * @throws Exception
	 */
	public static String execCmd(String host, int port, String user, String passWord, String command) throws Exception {
		StringBuffer result = new StringBuffer();
		Session session = null;
		ChannelExec openChannel = null;
		try {
			JSch jsch = new JSch();
			session = jsch.getSession(user, host, port);
			java.util.Properties config = new java.util.Properties();
			config.put("StrictHostKeyChecking", "yes");
			session.setConfig(config);
			session.setPassword(passWord);
			session.connect();
			openChannel = (ChannelExec) session.openChannel("exec");
			openChannel.setCommand(command);
			openChannel.connect();
			BufferedReader reader = new BufferedReader(new InputStreamReader(openChannel.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				result.append(line).append("\n");
			}
		} catch (Exception e) {
			log.error("ssh 执行命令异常", e);
			result.append(e.getMessage());
			e.printStackTrace();
			throw e;
		} finally {
			if (openChannel != null) {
				openChannel.disconnect();
			}
			if (session != null) {
				session.disconnect();
			}
		}
		return result.toString();
	}
	// public static String exportCustomerFile(String sql, String fileName,
	// HiveFtp hiveFtp) throws Exception {
	// String pathFile = hiveFtp.getPathBase() + "/" + hiveFtp.getExportPath() +
	// "/" + fileName + ".csv";
	// String command = "hive -e \"" + sql + "\" > " + pathFile;
	// execCmd(hiveFtp.getHost(), hiveFtp.getPort(), hiveFtp.getUserName(),
	// hiveFtp.getPassWord(), command);
	// log.info("ssh执行成功,导出客户群文件完成");
	// return pathFile;
	// }

}
