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

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;

import cn.com.customization.util.GetAllUserIds;
import cn.com.customization.util.UtilApi;

import com.teamcenter.rac.aif.AbstractAIFDialog;
import com.teamcenter.rac.aif.AbstractAIFUIApplication;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent; //import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.TCComponentTask;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.DateButton;
import com.teamcenter.rac.util.MessageBox;
import com.teamcenter.rac.util.PropertyLayout;

public class SearchTaskDialog extends AbstractAIFDialog {
	// public class SearchTaskDialog extends JDialog {
	// public class SearchTaskDialog extends JFrame {
	private static final long			serialVersionUID	= 1L;
	private JComboBox					user_cmb;
	private DateButton					startTime_jtb;
	private DateButton					endTime_jtb;
	private JCheckBox					EPMTask_ck;
	private JCheckBox					EPMDoTask_ck;
	private JCheckBox					EPMReviewTask_ck;
	private JCheckBox					EPMAcknowledgeTask_ck;
	private JCheckBox					EPMAddStatusTask_ck;
	private JCheckBox					EPMConditionTask_ck;
	private String						title;
	private AbstractAIFUIApplication	app;
	private String						queryName			= "__SearachViewTask";
	private String						querySelectSigoff	= "__SearchEPMReviewTask";
	private TCSession					session;
	private boolean						isExceptionSearch	= false;
	// private String serverInfoOption = "origin_serverinfo";

	public SearchTaskDialog(AbstractAIFUIApplication app, String title, boolean isExceptionSearch) {
		super(true);
		this.title = title;
		this.isExceptionSearch = isExceptionSearch;
		this.app = app;
		session = (TCSession) app.getSession();
		initUI();
	}

	public void initUI() {
		// setPersistentDisplay(false);
		// setOptimalDisplay(false);
		setTitle(title);
		this.setResizable(false);
		// this.setAlwaysOnTop(true);
		// ImageIcon image =
		// Registry.getImageIconFromPath("/com/teamcenter/rac/ecmanagement/images/processviewer_16.png");
		// this.setIconImage(image.getImage());
		JPanel panel = new JPanel(new PropertyLayout());
		panel.add("1.1.left.center", new JLabel("  "));
		if (isExceptionSearch) {
			panel.add("1.2.left.center", setSearchExceptionPanel());
		} else {
			panel.add("1.2.left.center", setSearchPanel());
		}
		panel.add("2.1.left.center", new JLabel("  "));
		this.getContentPane().add(panel);
		pack();
		validate();
		Dimension screen = getToolkit().getScreenSize();
		setLocation((screen.width - getSize().width) / 2, (screen.height - getSize().height) / 2);
		this.setVisible(true);

		// showDialog();
		// Dimension screen = getToolkit().getScreenSize();
		// setLocation((screen.width - getSize().width) / 2, (screen.height -
		// getSize().height) / 2);
	}

	private JPanel setSearchExceptionPanel() {
		startTime_jtb = new DateButton();
		endTime_jtb = new DateButton();
		JPanel panel1 = new JPanel(new PropertyLayout());
		panel1.setBorder(BorderFactory.createTitledBorder("请输入任务查询条件"));
		panel1.add("1.1.left.center", new JLabel("   "));
		panel1.add("2.1.left.center", new JLabel(" 执行时间_自  "));
		panel1.add("2.2.left.center", startTime_jtb);
		panel1.add("2.3.left.center", new JLabel("   "));
		panel1.add("3.1.left.center", new JLabel(" 执行时间_止  "));
		panel1.add("3.2.left.center", endTime_jtb);
		panel1.add("4.1.left.center", new JLabel("   "));

		JPanel panel = new JPanel(new PropertyLayout());
		panel.add("1.1.left.center", panel1);
		panel.add("1.2.left.center", setButtonPanel());
		return panel;
	}

	private JPanel setSearchPanel() {
		user_cmb = new JComboBox();
		user_cmb.setPreferredSize(new Dimension(156, 27));
		startTime_jtb = new DateButton();
		endTime_jtb = new DateButton();

		java.util.Date myDate = new java.util.Date();
		long myTime = (myDate.getTime() / 1000) - 60 * 60 * 24 * 7;
		myDate.setTime(myTime * 1000);
		startTime_jtb.setDate(myDate);
		new Thread() {
			public void run() {
				while (true) {
					try {
						String userRole = session.getPreferenceService().getString(4, "Cust_search_task_role");
						if(session.getCurrentRole().getRoleName().equals(userRole)){
							List<String> users = GetAllUserIds.getUsers();
							Collections.sort(users);
							if (users != null) {
								for (int i = 0; i < users.size(); i++) {
									user_cmb.addItem(users.get(i));
									if (users.get(i).equalsIgnoreCase(session.getUser().getUserId())) {
										user_cmb.setSelectedIndex(i);
									}
								}
								user_cmb.setEnabled(true);
								break;
							}
						}else{
							user_cmb.addItem(session.getUser());
							break;
						}
					}
					catch (TCException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();

		JPanel panel1 = new JPanel(new PropertyLayout());
		panel1.setBorder(BorderFactory.createTitledBorder("请输入任务查询条件"));
		panel1.add("1.1.left.center", new JLabel(" 执  行  者  "));
		panel1.add("1.2.left.center", user_cmb);
		panel1.add("1.3.left.center", new JLabel("   "));
		panel1.add("2.1.left.center", new JLabel(" 执行时间_自  "));
		panel1.add("2.2.left.center", startTime_jtb);
		panel1.add("2.3.left.center", new JLabel("   "));
		panel1.add("3.1.left.center", new JLabel(" 执行时间_止  "));
		panel1.add("3.2.left.center", endTime_jtb);
		panel1.add("3.3.left.center", new JLabel("   "));

		JPanel panel2 = new JPanel(new PropertyLayout());
		panel2.setBorder(BorderFactory.createTitledBorder("请选择查询任务类型"));
		EPMTask_ck = new JCheckBox("EPMTask");
		EPMDoTask_ck = new JCheckBox("EPMDoTask");
		EPMReviewTask_ck = new JCheckBox("EPMReviewTask");
		EPMAcknowledgeTask_ck = new JCheckBox("EPMAcknowledgeTask");
		EPMAddStatusTask_ck = new JCheckBox("EPMAddStatusTask");
		EPMConditionTask_ck = new JCheckBox("EPMConditionTask");

		EPMTask_ck.setSelected(true);
		EPMDoTask_ck.setSelected(true);
		EPMReviewTask_ck.setSelected(true);
		EPMAcknowledgeTask_ck.setSelected(true);

		panel2.add("1.1.left.center", EPMTask_ck);
		panel2.add("1.2.left.center", EPMDoTask_ck);
		panel2.add("1.3.left.center", new JLabel(" "));
		panel2.add("2.1.left.center", EPMReviewTask_ck);
		panel2.add("2.2.left.center", EPMConditionTask_ck);
		panel2.add("2.3.left.center", new JLabel(" "));
		panel2.add("3.1.left.center", EPMAcknowledgeTask_ck);
		panel2.add("3.2.left.center", EPMAddStatusTask_ck);

		JPanel panel = new JPanel(new PropertyLayout());
		panel.add("1.1.left.center", panel1);
		panel.add("2.1.left.center", panel2);
		panel.add("2.2.left.center", setButtonPanel());
		return panel;
	}

	private JPanel setButtonPanel() {
		JPanel panel = new JPanel(new PropertyLayout());
		JButton confirmBtn = new JButton("确定");
		JButton cancelBtn = new JButton("取消");
		confirmBtn.addActionListener(new buttonListener());
		cancelBtn.addActionListener(new buttonListener());

		panel.add("1.1.left.center", new JLabel("  "));
		panel.add("2.1.left.center", confirmBtn);
		panel.add("3.1.left.center", new JLabel(" "));
		panel.add("4.1.left.center", cancelBtn);
		panel.add("5.1.left.center", new JLabel(" "));
		return panel;
	}

	class buttonListener implements ActionListener {
		public void actionPerformed(ActionEvent actionevent) {
			session.setStatus("正在查询，稍等...");
			JButton obj = ((JButton) actionevent.getSource());
			if (obj.getText().equals("确定")) {
				try {
					if (startTime_jtb.getDate() == null) {
						MessageBox.post("【执行时间_自】不允许为空！", "INFO", MessageBox.INFORMATION);
						return;
					}
					Date endDate = new Date();
					if (endTime_jtb.getDate() != null) {
						endDate = endTime_jtb.getDate();
					}
					if (startTime_jtb.getDate().compareTo(endDate) >= 0) {
						MessageBox.post("【执行时间_止】应比【执行时间_自】晚", "INFO", MessageBox.INFORMATION);
						return;
					}
					List<InterfaceAIFComponent> components = new ArrayList<InterfaceAIFComponent>();
					SearchCondition searchCondition = new SearchCondition();
					String as[] = { "修改时间晚于", "修改时间早于", "ID", "类型", "ModUserID"};

					SimpleDateFormat fomat = new SimpleDateFormat("dd-M-yyyy HH:ss");
					// fomat = new SimpleDateFormat("dd-M-yyyy HH:ss:mm");

					String startTime = fomat.format(startTime_jtb.getDate());
					String endTime = fomat.format(endDate);
					/*
					 * windows HashMap<String, String> cfghm =
					 * UtilApi.getPreferenceHashMap(session,
					 * TCPreferenceService.TC_preference_site,
					 * serverInfoOption); if (cfghm == null) {
					 * MessageBox.post("没有配置首选项【" + serverInfoOption + "】!",
					 * "INFO", MessageBox.INFORMATION); return; } String
					 * isWindows = (cfghm.get("isWindowsServer") + "").trim();
					 * if (isWindows.equalsIgnoreCase("true")) { startTime =
					 * startTime_jtb.getDate().toLocaleString(); endTime =
					 * endDate.toLocaleString();
					 * System.out.println("Windows:startTime=========" +
					 * startTime); System.out.println("Windows:endTime========="
					 * + endTime); }
					 */
//					System.out.println("Windows:startTime=========" + startTime);
//					System.out.println("Windows:endTime=========" + endTime);
					searchCondition.setCreateDate(startTime);
					searchCondition.setFinishDate(endTime);

					if (!isExceptionSearch) {
						String user = (user_cmb.getSelectedItem().toString());
						if ((user.length() == 0) || (user == null)) {
							MessageBox.post("用户不允许为空！", "INFO", MessageBox.INFORMATION);
							return;
						}
						if ((!(EPMTask_ck.isSelected())) && (!(EPMDoTask_ck.isSelected())) && (!(EPMReviewTask_ck.isSelected())) && (!(EPMAcknowledgeTask_ck.isSelected())) && (!(EPMAddStatusTask_ck.isSelected()))) {
							MessageBox.post("选择查询任务类型！", "INFO", MessageBox.INFORMATION);
							return;
						}
						searchCondition.setUsername(user);
						user = user.substring(0, user.indexOf("(")).trim();
						List<String> taskList = new ArrayList<String>();
						if (EPMTask_ck.isSelected()) {
							taskList.add("EPMTask");
						}
						if (EPMDoTask_ck.isSelected()) {
							taskList.add("EPMDoTask");
						}
						if (EPMReviewTask_ck.isSelected()) {
							taskList.add("EPMReviewTask");
						}
						if (EPMAcknowledgeTask_ck.isSelected()) {
							taskList.add("EPMAcknowledgeTask");
						}
						if (EPMAddStatusTask_ck.isSelected()) {
							taskList.add("EPMAddStatusTask");
						}
						if (EPMConditionTask_ck.isSelected()) {
							taskList.add("EPMConditionTask");
						}

						for (int i = 0; i < taskList.size(); i++) {
							if (taskList.get(i).equals("EPMTask")) {
								String as1[] = { startTime, endTime, user, taskList.get(i).trim(), "*" };
								InterfaceAIFComponent[] components1 = UtilApi.getQueryList((TCSession) app.getSession(), queryName, as, as1);
								if (components1 != null) {
									for (int m = 0; m < components1.length; m++) {
										components.add(components1[m]);
									}
								}
							} else {
								if (taskList.get(i).equals("EPMReviewTask")) {
									String strID[] = { "memberUser" };
									String as1[] = { user };
									InterfaceAIFComponent[] components1 = UtilApi.getQueryList((TCSession) app.getSession(), querySelectSigoff,strID, as1);
									if (components1 != null) {
										for (int m = 0; m < components1.length; m++) {
											components.add(components1[m]);
										}
									}
								} else {
									String as1[] = { startTime, endTime, user, taskList.get(i).trim(), "*"};
									InterfaceAIFComponent[] components1 = UtilApi.getQueryList((TCSession) app.getSession(), queryName, as, as1);
									if (components1 != null) {
										for (int m = 0; m < components1.length; m++) {
											components.add(components1[m]);
										}
									}
								}
							}
						}
					} else {
						String as1[] = { startTime, endTime, "*", "EPMTask", "*" };
						InterfaceAIFComponent[] components1 = UtilApi.getQueryList((TCSession) app.getSession(), queryName, as, as1);
						if (components1 != null) {
							for (int m = 0; m < components1.length; m++) {
								TCComponentTask task = (TCComponentTask) components1[m];
								isValidTask(task, components);
							}
						}
					}
					if ((components == null) || (components.size() == 0)) {
						MessageBox.post("没有符合要求的记录！", "INFO", MessageBox.INFORMATION);
					} else {
						SearchTaskDialog.this.dispose();
						new SearchResultDialog(app, components, searchCondition, isExceptionSearch);
					}
				}
				catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				SearchTaskDialog.this.dispose();
			}
			session.setReadyStatus();
		}
	}

	private boolean isValidTask(TCComponentTask task, List<InterfaceAIFComponent> components) {
		try {
			TCComponentTask[] children = task.getSubtasks();
			for (int i = 0; i < children.length; i++) {
				TCComponentTask childrenTask = children[i];
				String childState = childrenTask.getProperty("real_state");
				if (childState.equals("待处理")) {
					TCComponentTask previousTask = childrenTask.getPrevious();
					if (previousTask != null) {
						String previousType = previousTask.getProperty("object_type");
						String previousState = previousTask.getProperty("real_state");
						if ((previousState.equals("已完成")) && (!previousType.equals("EPMConditionTask"))) {
							components.add(childrenTask);
							return false;
						} else {
							if (!isValidTask(childrenTask, components)) {
								components.add(childrenTask);
								return false;
							}
						}
					}
				}
			}
			String taskState = task.getProperty("real_state");
			if (taskState.equals("已开始")) {
				if ((children != null) && (children.length >= 3)) {
					int count = 0;
					for (int i = 0; i < children.length; i++) {
						TCComponentTask childrenTask = children[i];
						String childState = childrenTask.getProperty("real_state");
						if (childState.equals("已开始")) {
							count++;
						}
					}
					if (count == 0) {
						components.add(task);
						return false;
					}
				}
			}
		}
		catch (TCException e) {
			e.printStackTrace();
		}
		return true;
	}

	class SearchCondition {
		private String	username;
		private String	createDate;
		private String	finishDate;

		/**
		 * @return the username
		 */
		public String getUsername() {
			return username;
		}

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

		/**
		 * @return the createDate
		 */
		public String getCreateDate() {
			return createDate;
		}

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

		/**
		 * @return the finishDate
		 */
		public String getFinishDate() {
			return finishDate;
		}

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