/*
#=======================================================================================================
#
#                   Copyright (c) 2007 Origin Enterprise Solution LTD.
#
#=======================================================================================================
# File description:  SearchResultDialog.java
#=======================================================================================================
#	 Date	       time   	   Name	 Action	   Description of Change
#	2011-1-17      下午03:46:01    tyl  	Ini	            初始化文件
#=======================================================================================================
 */
package cust.com.rac.workflow;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
import javax.swing.table.JTableHeader;

import cn.com.customization.util.ColumnGroup;
import cn.com.customization.util.DataSetFinder;
import cn.com.customization.util.GetChoosePath;
import cn.com.customization.util.GetMessageDialog;
import cn.com.customization.util.GroupableTableHeader;
import cn.com.customization.util.TableColorRender;
import cn.com.customization.util.TableColumnRender;
import cn.com.customization.util.UtilApi;

import com.teamcenter.rac.aif.AIFDesktop;
import com.teamcenter.rac.aif.AbstractAIFCommand;
import com.teamcenter.rac.aif.AbstractAIFUIApplication;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.commands.open.OpenCommand;
import com.teamcenter.rac.kernel.TCComponentDataset;
import com.teamcenter.rac.kernel.TCComponentSignoff;
import com.teamcenter.rac.kernel.TCComponentTask;
import com.teamcenter.rac.kernel.TCComponentUserType;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCPreferenceService;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.kernel.TCTypeService;
import com.teamcenter.rac.util.MessageBox;
import com.teamcenter.rac.util.PropertyLayout;
import com.teamcenter.rac.util.Registry;

import cust.com.rac.workflow.SearchTaskDialog.SearchCondition;

//public class SearchResultDialog extends AbstractAIFDialog {
public class SearchResultDialog extends JFrame {
	private static final long			serialVersionUID	= 1L;
	private List<SearchResults>			results				= new ArrayList<SearchResults>();
	private JTable						table1;
	private SearchResultTableModel		dtm1;
	private String						title				= "";
	private TCSession					session;
	private SearchCondition				searchCondition;
	private String[]					names1				= { "*", "任务名称", "执行者", "上步骤完成时间", "完成时间", "任务状态", "会签注释", "任务类型", "流程所有者", "工作流名称", "创建时间", "最后一次修改时间", "最后一次修改者", "状态", "工作流模板名称" };
	private String[]					names2				= { "*", "流程所有者", "工作流名称", "任务名称", "创建时间", "最后一次修改时间", "最后一次修改者", "状态" };
	private Map<String, SearchResults>	taskMap				= new HashMap<String, SearchResults>();

	private String						reportOption		= "origin_viewTask_report";
	private String						reportPath			= "c:";
	private PackExcelInfo				excelInfo			= new PackExcelInfo();
	private boolean						isExceptionSearch;

	public SearchResultDialog(AbstractAIFUIApplication app, List<InterfaceAIFComponent> components, SearchCondition searchCondition, boolean isExceptionSearch) {
		this.session = (TCSession) app.getSession();
		this.searchCondition = searchCondition;
		this.isExceptionSearch = isExceptionSearch;
		getResultValue(components);
		initUI();
		File file = new File(excelInfo.getTemplateFileName());
		if (file.exists()) {
			file.delete();
		}
	}

	@SuppressWarnings("deprecation")
	private void getResultValue(List<InterfaceAIFComponent> components) {
		try {
			title = (new Date().toLocaleString()) + "_" + session.getUser() + "_执行任务查询条件：任务执行者：" + searchCondition.getUsername() + "任务时间段：[" + searchCondition.getCreateDate() + "]_[" + searchCondition.getFinishDate() + "]";
			if (components != null) {
				List<TCComponentTask> taskList = new ArrayList<TCComponentTask>();
				List<String> taskIndexList = new ArrayList<String>();
				for (int i = 0; i < components.size(); i++) {
					TCComponentTask task = (TCComponentTask) components.get(i);

					if (task != null) {
						SearchResults result = new SearchResults();
						if (!isExceptionSearch) {
							if (((task.getTaskType()).equalsIgnoreCase("EPMSelectSignoffTask")) || ((task.getTaskType()).equalsIgnoreCase("EPMPerformSignoffTask"))) {
								TCComponentSignoff[] sigoffs = task.getValidSignoffs();
								for (int m = 0; m < sigoffs.length; m++) {
									String comment = sigoffs[m].getComments();
									result.setTask_note(comment);
									result.setTask_executor(sigoffs[m].getProperty("signoff_member"));
									result.setTask_finishDate(sigoffs[m].getProperty("decision_date"));
								}
							} else {
								result.setTask_executor(task.getProperty("owning_user"));
								result.setTask_finishDate(task.getProperty("last_mod_date"));
								result.setTask_note("");
							}
						}

						if (((task.getTaskType()).equalsIgnoreCase("EPMSelectSignoffTask")) || ((task.getTaskType()).equalsIgnoreCase("EPMPerformSignoffTask"))) {
							task = task.getParent();
						}
						if (taskList.contains(task)) {
							int taskIndex = taskList.indexOf(task);
							taskList.remove(task);
							taskIndexList.remove(taskIndex);
						}

						result.setTask_name(task.getProperty("object_name"));
						if (result.getTask_type().equals("EPMTask")) {
							if (result.getTask_status().equals("已开始")) {
								result.setTask_name("◆" + result.getTask_name());
								result.setTask_finishDate("");
							}
						}

						Date taskCreateDate = null;
						SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						result.setTask(task);
						taskCreateDate = task.getDateProperty("creation_date");

						result.setTask_createDate(task.getProperty("creation_date"));
						TCComponentTask previousTask = task.getPrevious();
						if (previousTask != null) {
							result.setTask_createDate(previousTask.getProperty("last_mod_date"));
							taskCreateDate = previousTask.getDateProperty("last_mod_date");
						}
						result.setTask_type(task.getProperty("object_type"));
						result.setTask_status(task.getProperty("real_state"));

						if (!result.getTask_status().equals("已完成")) {
							result.setTask_finishDate("");
						}

						TCComponentTask rootTask = task.getRoot();
						result.setProcess_name(rootTask.getProperty("job_name"));
						result.setProcess_createDate(rootTask.getProperty("creation_date"));
						result.setProcess_finishDate(rootTask.getProperty("last_mod_date"));
						result.setProcess_lastModeUser(rootTask.getProperty("last_mod_user"));
						result.setProcess_executor(rootTask.getProperty("owning_user"));
						result.setProcess_status(rootTask.getProperty("real_state"));
						result.setProcess_templateName(rootTask.getProperty("task_template"));
						// String index = String.valueOf(i + 1) + "$$$" +
						// result.getProcess_createDate() + "$$$" +
						// result.getTask_createDate() + "$$$" +
						// result.getTask_finishDate();
						String index = String.valueOf(i + 1) + "$$$" + simpleDate.format(rootTask.getDateProperty("creation_date")) + "$$$" + result.getProcess_name() + "$$$" + simpleDate.format(taskCreateDate);
						taskIndexList.add(index);
						taskMap.put(index, result);
					}
					taskList.add(task);
				}

				Collections.sort(taskIndexList, new ComparatorTask());
				for (int i = 0; i < taskIndexList.size(); i++) {
					SearchResults result = taskMap.get(taskIndexList.get(i));
					result.setIndex(String.valueOf(i + 1));
					results.add(result);
				}
			}
		}
		catch (TCException e) {
			e.printStackTrace();
		}
	}

	public String getUserByID(String userID) {
		try {
			TCTypeService service = session.getTypeService();
			TCComponentUserType userType = (TCComponentUserType) service.getTypeComponent("User");
			if (userType.find(userID) != null) {
				String user = userType.find(userID).toString();
				return user;
			}
		}
		catch (TCException e1) {
			e1.printStackTrace();
		}
		return "";
	}

	public void initUI() {
		this.setTitle("查询任务");
		ImageIcon image = Registry.getImageIconFromPath("/com/teamcenter/rac/ecmanagement/images/processviewer_16.png");
		this.setIconImage(image.getImage());
		JPanel panel = new JPanel(new BorderLayout());
		panel.add(BorderLayout.NORTH, setTopPanel());
		panel.add(BorderLayout.CENTER, setCenterPanel());
		panel.add(BorderLayout.SOUTH, setBottomPanel());
		getContentPane().add(panel);
		// this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		// this.addWindowListener(new WindowAdapter() {
		// public void windowClosing(WindowEvent e) {
		// dispose();
		// }
		// });
		// showDialog();
		pack();
		Dimension screen = getToolkit().getScreenSize();
		setLocation((screen.width - getSize().width) / 2, (screen.height - getSize().height) / 2);
		this.setVisible(true);
	}

	private JPanel setTopPanel() {
		JPanel panel = new JPanel(new BorderLayout());
		panel.add(new JLabel("  "), BorderLayout.NORTH);
		if (!isExceptionSearch) {
			panel.add(new JLabel("    " + title), BorderLayout.CENTER);
		}
		panel.add(new JLabel("  "), BorderLayout.SOUTH);
		return panel;
	}

	private JPanel setCenterPanel() {
		JPanel panel1 = new JPanel(new PropertyLayout());
		panel1.setBorder(new TitledBorder(""));
		if (!isExceptionSearch) {
			dtm1 = new SearchResultTableModel(names1, results, 0);
			table1 = new JTable(dtm1) {
				private static final long	serialVersionUID	= 1L;

				protected JTableHeader createDefaultTableHeader() {
					return new GroupableTableHeader(columnModel);
				}
			};
			GroupableTableHeader header = new GroupableTableHeader(table1.getColumnModel());
			javax.swing.table.TableColumnModel cm = table1.getColumnModel();
			// 接受类型
			ColumnGroup taskCol = new ColumnGroup("所参入任务信息");
			taskCol.add(cm.getColumn(1));
			taskCol.add(cm.getColumn(2));
			taskCol.add(cm.getColumn(3));
			taskCol.add(cm.getColumn(4));
			taskCol.add(cm.getColumn(5));
			taskCol.add(cm.getColumn(6));
			taskCol.add(cm.getColumn(7));
			header.addColumnGroup(taskCol);

			ColumnGroup processCol = new ColumnGroup("所属工作流信息");
			processCol.add(cm.getColumn(8));
			processCol.add(cm.getColumn(9));
			processCol.add(cm.getColumn(10));
			processCol.add(cm.getColumn(11));
			processCol.add(cm.getColumn(12));
			processCol.add(cm.getColumn(13));
			processCol.add(cm.getColumn(14));
			header.addColumnGroup(processCol);
			table1.setTableHeader(header);
			table1.setDefaultRenderer(Object.class, new TableColorRender());
			dtm1.setTableColumnsWidth(table1, 0);
		} else {
			dtm1 = new SearchResultTableModel(names2, results, 1);
			table1 = new JTable(dtm1);
			dtm1.setTableColumnsWidth(table1, 1);
		}
		table1.setRowHeight(20);
		table1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

		// 对列进行渲染
		table1.getColumnModel().getColumn(0).setCellRenderer(new TableColumnRender());
		Dimension screen = getToolkit().getScreenSize();
		JScrollPane scrollPane1 = new JScrollPane(table1, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
		if (!isExceptionSearch) {
			scrollPane1.setPreferredSize(new Dimension((int) (screen.getWidth() * (0.75)), (int) (screen.getHeight() * (0.6))));
		} else {
			scrollPane1.setPreferredSize(new Dimension((int) (screen.getWidth() * (0.62)), (int) (screen.getHeight() * (0.5))));
		}
		JPanel panel = new JPanel(new BorderLayout());
		panel.setBorder(new TitledBorder(""));
		panel.add(scrollPane1);
		return panel;
	}

	private JPanel setBottomPanel() {
		JPanel southPanel = new JPanel(new FlowLayout());
		// southPanel.setSize(100, 15);
		JButton confirmButton = new JButton("查看流程");
		JButton exitButton = new JButton("退    出");
		JButton exportButton = new JButton("导出Excel");
		confirmButton.addActionListener(new buttonListener());
		exitButton.addActionListener(new buttonListener());
		exportButton.addActionListener(new buttonListener());
		southPanel.add(new JLabel("               "));
		southPanel.add(new JLabel("               "));
		southPanel.add(new JLabel("               "));
		southPanel.add(new JLabel("               "));
		southPanel.add(new JLabel("               "));
		southPanel.add(confirmButton);
		if (!isExceptionSearch) {
			southPanel.add(exportButton);
		}
		southPanel.add(exitButton);
		return southPanel;
	}

	class buttonListener implements ActionListener {
		public void actionPerformed(ActionEvent event) {
			String name = ((JButton) event.getSource()).getText();
			if (name.equals("查看流程")) {
				showProcess();
			} else if (name.equals("导出Excel")) {
				exportResult();
			} else if (name.equals("退    出")) {
				dispose();
			}
		}
	}

	private void exportResult() {
		String dir = new GetChoosePath().getPath("\\viewTask.txt");
		if ((dir != "") || (dir.trim().length() > 0)) {
			excelInfo.setTitle(title);
			excelInfo.setTemplateFileName(getTemplateFile());
			String times = String.valueOf(new SimpleDateFormat("yyyyMMddhhmmss").format(new Date(System.currentTimeMillis())));
			excelInfo.setTargetFileName(dir + "\\查询任务_" + times + ".xls");
			new ExportSearchResult(results, excelInfo);
			openFile(excelInfo.getTargetFileName(), false);
			this.setVisible(true);
		}
	}

	public String getTemplateFile() {
		HashMap<String, String> cfghm = UtilApi.getPreferenceHashMap(session, TCPreferenceService.TC_preference_site, reportOption);
		if (cfghm == null) {
			MessageBox.post("没有配置首选项【" + reportOption + "】!", "INFO", MessageBox.INFORMATION);
			return "";
		}
		String DatasetOwningUser = (cfghm.get("DatasetOwningUser") + "").trim();
		String DatasetOwningGroup = (cfghm.get("DatasetOwningGroup") + "").trim();
		String DatasetName = (cfghm.get("DatasetName") + "").trim();
		DataSetFinder dataset_finder = new DataSetFinder(session);
		TCComponentDataset imancomponentdataset = dataset_finder.FindDatasetByName(DatasetName, DatasetOwningUser, DatasetOwningGroup, "MSExcel");
		System.out.println("imancomponentdataset=========" + imancomponentdataset);
		if (imancomponentdataset != null) {
			try {
				File file1 = new File(reportPath);
				if (!file1.exists()) {
					file1.createNewFile();
				}
				File file = dataset_finder.ExportFileToDir(imancomponentdataset, reportPath);
				if (file != null) {
					System.out.println("file=========" + file.getAbsolutePath());
					return file.getAbsolutePath();
				}
			}
			catch (Exception e) {
				MessageBox.post("导出数据集命名引用时出错!", "INFO", MessageBox.INFORMATION);
				e.printStackTrace();
			}
		} else {
			MessageBox.post("配置的【" + DatasetName + "】数据集模板不存在!", "INFO", MessageBox.INFORMATION);
		}
		return "";
	}

	public void openFile(String targetFile, boolean isDir) {
		File file = new File(targetFile);
		if (file.exists()) {
			int value = 0;
			if (isDir) {
				value = new GetMessageDialog("INFO", "文件已经生成，是否打开其所在目录？").getValue();
				// value =
				// MessageDialog.openConfirm(Display.getCurrent().getActiveShell(),
				// "INFO", "文件已经生成，是否打开其所在目录？");
			} else {
				// value =
				// MessageDialog.openConfirm(Display.getCurrent().getActiveShell(),
				// "INFO", "文件已经生成，是否打开？");
				value = new GetMessageDialog("INFO", "文件已经生成，是否打开？").getValue();
			}
			if (value == 0) {
				try {
					Runtime runtime = Runtime.getRuntime();
					runtime.exec("cmd /c  start exit &&\"" + targetFile + "\" ");
				}
				catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private void showProcess() {
		int row = table1.getSelectedRow();
		if (row >= 0) {
			final SearchResults result = results.get(row);
			AIFDesktop localAIFDesktop = AIFUtility.getActiveDesktop();

			// try {
			// ExplorerService exploreService = new ExplorerService();
			// // exploreService.expand();
			// // exploreService.refresh();
			// }
			// catch (Exception e1) {
			// e1.printStackTrace();
			// }
			// String str = "com.teamcenter.rac.explorer.ExplorerApplication";
			// localAIFDesktop.sendToApplication(result.getTask(), str);

			TCComponentTask task = result.getTask();
			try {
				AIFComponentContext[] context = task.getChildren();
				InterfaceAIFComponent[] contexts = new InterfaceAIFComponent[] { (InterfaceAIFComponent) context[0].getComponent() };
				try {
					System.out.println("task.getName()==" + task.getName());
				}
				catch (TCException e1) {
					e1.printStackTrace();
				}
				AbstractAIFCommand abstractaifcommand = new OpenCommand(localAIFDesktop, contexts);
				try {
					abstractaifcommand.executeModal();
				}
				catch (Exception e1) {
					e1.printStackTrace();
				}
			}
			catch (TCException e1) {
				e1.printStackTrace();
			}

			try {
				Thread.sleep(500);
			}
			catch (InterruptedException e) {
				e.printStackTrace();
			}
			SearchResultDialog.this.setExtendedState(JFrame.ICONIFIED);
		} else {
			MessageBox.post("请选择要查看的流程！", "INFO", MessageBox.INFORMATION);
			this.setVisible(true);
		}
	}

	class SearchResults {
		private String	index			= "";
		private String	task_name		= "";
		private String	task_createDate	= "";
		private String	task_finishDate	= "";
		private String	task_status		= "";
		private String	task_executor	= "";
		private String	task_note		= "";
		private String	task_type		= "";

		/**
		 * @return the task_type
		 */
		public String getTask_type() {
			return task_type;
		}

		/**
		 * @param task_type the task_type to set
		 */
		public void setTask_type(String task_type) {
			this.task_type = task_type;
		}

		private TCComponentTask	task;

		private String			process_name;
		private String			process_createDate;
		private String			process_finishDate;
		private String			process_status;
		private String			process_executor;
		private String			process_lastModeUser;
		private String			process_templateName;

		/**
		 * @return the task
		 */
		public TCComponentTask getTask() {
			return task;
		}

		/**
		 * @return the process_lastModeUser
		 */
		public String getProcess_lastModeUser() {
			return process_lastModeUser;
		}

		/**
		 * @param process_lastModeUser the process_lastModeUser to set
		 */
		public void setProcess_lastModeUser(String process_lastModeUser) {
			this.process_lastModeUser = process_lastModeUser;
		}

		/**
		 * @param task the task to set
		 */
		public void setTask(TCComponentTask task) {
			this.task = task;
		}

		/**
		 * @return the index
		 */
		public String getIndex() {
			return index;
		}

		/**
		 * @param index the index to set
		 */
		public void setIndex(String index) {
			this.index = index;
		}

		/**
		 * @return the task_name
		 */
		public String getTask_name() {
			return task_name;
		}

		/**
		 * @param task_name the task_name to set
		 */
		public void setTask_name(String task_name) {
			this.task_name = task_name;
		}

		/**
		 * @return the task_createDate
		 */
		public String getTask_createDate() {
			return task_createDate;
		}

		/**
		 * @param task_createDate the task_createDate to set
		 */
		public void setTask_createDate(String task_createDate) {
			this.task_createDate = task_createDate;
		}

		/**
		 * @return the task_finishDate
		 */
		public String getTask_finishDate() {
			return task_finishDate;
		}

		/**
		 * @param task_finishDate the task_finishDate to set
		 */
		public void setTask_finishDate(String task_finishDate) {
			this.task_finishDate = task_finishDate;
		}

		/**
		 * @return the task_status
		 */
		public String getTask_status() {
			return task_status;
		}

		/**
		 * @param task_status the task_status to set
		 */
		public void setTask_status(String task_status) {
			this.task_status = task_status;
		}

		/**
		 * @return the task_executor
		 */
		public String getTask_executor() {
			return task_executor;
		}

		/**
		 * @param task_executor the task_executor to set
		 */
		public void setTask_executor(String task_executor) {
			this.task_executor = task_executor;
		}

		/**
		 * @return the task_note
		 */
		public String getTask_note() {
			return task_note;
		}

		/**
		 * @param task_note the task_note to set
		 */
		public void setTask_note(String task_note) {
			this.task_note = task_note;
		}

		/**
		 * @return the process_name
		 */
		public String getProcess_name() {
			return process_name;
		}

		/**
		 * @param process_name the process_name to set
		 */
		public void setProcess_name(String process_name) {
			this.process_name = process_name;
		}

		/**
		 * @return the process_createDate
		 */
		public String getProcess_createDate() {
			return process_createDate;
		}

		/**
		 * @param process_createDate the process_createDate to set
		 */
		public void setProcess_createDate(String process_createDate) {
			this.process_createDate = process_createDate;
		}

		/**
		 * @return the process_finishDate
		 */
		public String getProcess_finishDate() {
			return process_finishDate;
		}

		/**
		 * @param process_finishDate the process_finishDate to set
		 */
		public void setProcess_finishDate(String process_finishDate) {
			this.process_finishDate = process_finishDate;
		}

		/**
		 * @return the process_status
		 */
		public String getProcess_status() {
			return process_status;
		}

		/**
		 * @param process_status the process_status to set
		 */
		public void setProcess_status(String process_status) {
			this.process_status = process_status;
		}

		/**
		 * @return the process_executor
		 */
		public String getProcess_executor() {
			return process_executor;
		}

		/**
		 * @param process_executor the process_executor to set
		 */
		public void setProcess_executor(String process_executor) {
			this.process_executor = process_executor;
		}

		/**
		 * @return the process_templateName
		 */
		public String getProcess_templateName() {
			return process_templateName;
		}

		/**
		 * @param process_templateName the process_templateName to set
		 */
		public void setProcess_templateName(String process_templateName) {
			this.process_templateName = process_templateName;
		}

	}
}
