package com.sencorsta.rabs.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CmdUtil {
	/**
	 * 关闭 Excel 进程。
	 * @return 关闭的进程数量。
	 */
	public static int closeExcelProcesses() {
		List<String> processNames = Arrays.asList("excel.exe", "et.exe","wps.exe");

		// 查找 Office 进程并关闭
		List<Integer> pids = new ArrayList<>();
		for (String processName : processNames) {
			pids.addAll(killProcess(processName));
		}

		return pids.size();
	}

	private static List<Integer> killProcess(String processName) {
		Process process = null;
		BufferedReader reader = null;
		List<Integer> pids = new ArrayList<>();

		try {
			// 执行系统命令，查找进程列表
			process = Runtime.getRuntime().exec("tasklist");
			reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

			String line;
			while ((line = reader.readLine()) != null) {
				if (line.toLowerCase().contains(processName)) {
					// 如果找到 Excel 进程，则关闭进程
					int pid = Integer.parseInt(line.substring(28, 34).trim());
					Process exec = Runtime.getRuntime().exec("taskkill /PID " + pid + " /F");
					try {
						exec.waitFor();
					} catch (InterruptedException e) {
						e.printStackTrace();
					} finally {
						exec.destroy();
					}
					pids.add(pid);
				}
			}

			return pids;
		} catch (IOException e) {
			e.printStackTrace();
			return pids;
		} finally {
			if (process != null) {
				process.destroy();
			}
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
