package com.connor.dongmu.plm.handlers.tmom006;

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.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

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

import com.connor.dongmu.plm.util.ExcelUtil07;
import com.connor.dongmu.plm.util.TMomFinalUtil;
import com.connor.dongmu.plm.util.TransfProgressBarThread;
import com.teamcenter.rac.aif.AbstractAIFDialog;
import com.teamcenter.rac.aif.AbstractAIFUIApplication;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentDataset;
import com.teamcenter.rac.kernel.TCComponentFolder;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentProject;
import com.teamcenter.rac.kernel.TCComponentProjectType;
import com.teamcenter.rac.kernel.TCComponentScheduleTask;
import com.teamcenter.rac.kernel.TCComponentTcFile;
import com.teamcenter.rac.kernel.TCComponentType;
import com.teamcenter.rac.kernel.TCComponentUser;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCPreferenceService;
import com.teamcenter.rac.kernel.TCProperty;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.FileUtility;
import com.teamcenter.rac.util.MessageBox;
import com.teamcenter.rac.util.PropertyLayout;

public class TMomExportTaskReportDialog extends AbstractAIFDialog implements
		ActionListener {
	private AbstractAIFUIApplication app;
	private TCSession session;
	private JPanel rootPanel;
	private JPanel panel1;
	private JPanel panel2;
	private JButton okButton;
	private JButton celButton;
	private JComboBox<TMomExportTaskReportOptionBean> selectBox;
	private List<TMomExportTaskReportOptionBean> optionBeanList;
	// private List<TMomExportTaskReportOptionBean> optionBeanTypeList;
	// CheckListѡ
	private final String CheckListTotleOptions = "CheckListTotleOptions";
	private final String CheckListTotleTypeOptions = "CheckListStageTypeTotleOptions";
	private List<TCComponentScheduleTask> secheduleTaskList;
	private List<TMomExportTaskReportBean> beanList;
	private TCComponentDataset excelDataset;
	private String projectID;
	// private String nowTime;
	private SimpleDateFormat sdf;

	public TMomExportTaskReportDialog(AbstractAIFUIApplication app,
			TCSession session, List<TCComponentScheduleTask> secheduleTaskList,
			List<TMomExportTaskReportBean> beanList) {
		this.app = app;
		this.session = session;
		this.secheduleTaskList = secheduleTaskList;
		this.beanList = beanList;
		sdf = new SimpleDateFormat("yyyy-MM-dd");
		// nowTime = sdf.format(new Date());
		getOption();
	}

	/**
	 * ȡѡ
	 */
	public void getOption() {
		optionBeanList = new ArrayList<>();
		TCPreferenceService service = this.session.getPreferenceService();
		String[] options = service.getStringArray(
				TCPreferenceService.TC_preference_site, CheckListTotleOptions);
		if (options == null || options.length < 1) {
			return;
		}
		for (int i = 0; i < options.length; i++) {
			String[] subOptions = options[i].split("\\:");
			if (subOptions == null || subOptions.length != 2) {
				continue;
			}
			String[] subSingleOptions = service.getStringArray(
					TCPreferenceService.TC_preference_user, subOptions[1]);
			TMomExportTaskReportOptionBean bean = new TMomExportTaskReportOptionBean();
			if (subOptions[0].indexOf("/") != -1) {
				bean.setDisName(subOptions[0].substring(0,
						subOptions[0].indexOf("/")));
			} else {
				bean.setDisName(subOptions[0]);
			}

			bean.setDisNameDisplay(subOptions[0]);
			bean.setName(subOptions[1]);
			bean.setValuesList(Arrays.asList(subSingleOptions));
			System.out.println("bean values="
					+ Arrays.toString(bean.getValuesList().toArray()));
			optionBeanList.add(bean);
			getTypeOption();

		}
	}

	/**
	 * ȡ׶ѡ
	 */
	public void getTypeOption() {
		// optionBeanList = new ArrayList<>();
		TCPreferenceService service = this.session.getPreferenceService();
		String[] options = service.getStringArray(
				TCPreferenceService.TC_preference_site,
				CheckListTotleTypeOptions);
		if (options == null || options.length < 1) {
			return;
		}
		for (int i = 0; i < options.length; i++) {
			String[] subOptions = options[i].split("\\:");
			if (subOptions == null || subOptions.length != 2) {
				continue;
			}
			String[] subSingleOptions = service.getStringArray(
					TCPreferenceService.TC_preference_site, subOptions[1]);
			// TMomExportTaskReportOptionBean bean = new
			// TMomExportTaskReportOptionBean();
			// bean.setDisName(subOptions[0]);
			// bean.setName(subOptions[1]);
			System.out.println("Type =" + Arrays.toString(subSingleOptions));
			for (TMomExportTaskReportOptionBean bean : optionBeanList) {
				if (bean.getDisName().equals(subOptions[0])) {
					bean.setTypeList(Arrays.asList(subSingleOptions));
					break;
				}
			}

			// optionBeanList.add(bean);
		}
	}

	/**
	 * ʼ
	 */
	public void init() {
		this.setTitle("Ŀ");
		this.setPreferredSize(new Dimension(450, 180));
		panel1 = new JPanel(new PropertyLayout());
		selectBox = new JComboBox<TMomExportTaskReportOptionBean>(
				optionBeanList
						.toArray(new TMomExportTaskReportOptionBean[optionBeanList
								.size()]));
		panel1.add("1.1.right.top.preferred.preferred", new JLabel("    "));
		panel1.add("2.1.right.top.preferred.preferred", new JLabel(
				"CheckList׶:"));
		panel1.add("2.2.left.top.preferred.preferred", selectBox);

		panel2 = new JPanel(new FlowLayout());
		okButton = new JButton("ȷ");
		celButton = new JButton("ȡ");
		okButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				okEvent(e);
			}
		});

		celButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				celEvent(e);
			}
		});
		panel2.add(okButton);
		panel2.add(new JLabel("   "));
		panel2.add(celButton);

		rootPanel = new JPanel(new BorderLayout());
		rootPanel.add(panel1, BorderLayout.CENTER);
		rootPanel.add(panel2, BorderLayout.SOUTH);
		this.add(rootPanel, "Center");
		this.pack();
		this.centerToScreen();
		this.showDialog();
	}

	public void okEvent(ActionEvent e) {
		this.dispose();
		exportTaskReport();
	}

	public void celEvent(ActionEvent e) {
		this.dispose();
	}

	@Override
	public void actionPerformed(ActionEvent e) {

	}

	public void exportTaskReport() {
		TransfProgressBarThread thread = new TransfProgressBarThread(
				"Check List", "CheckList ......");
		try {
			thread.start();
			InterfaceAIFComponent comp = this.app.getTargetComponent();

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			if (comp instanceof TCComponentItem
					|| comp instanceof TCComponentItemRevision) {
				TCComponent comp1 = (comp instanceof TCComponentItem) ? ((TCComponentItem) comp)
						.getLatestItemRevision() : ((TCComponent) comp);
				TCComponent[] comps2 = comp1
						.getReferenceListProperty("TC_Attaches");
				if (comps2 == null || comps2.length != 1) {
					MessageBox.post("ûҵ", "", MessageBox.ERROR);
					return;
				}
				comp1 = comps2[0];
				if (comp1 != null && comp1.getType().equals(Util.EXCEL_TYPE)) {

					TCComponentDataset excel = (TCComponentDataset) comp1;
					this.excelDataset = excel;
					AIFComponentContext[] context = ((TCComponent) comp)
							.whereReferenced();
					if (context != null && context.length != 0) {
						boolean haveTask = false;
						for (AIFComponentContext cont : context) {
							System.out
									.println(" cont ="
											+ ((TCComponent) cont
													.getComponent())
													.getStringProperty("object_string"));
							TCComponentFolder folder = null;
							if (cont.getComponent() instanceof TCComponentFolder) {
								folder = (TCComponentFolder) cont
										.getComponent();
							} else {
								continue;
							}
							if (folder == null
									|| (folder != null && !(folder instanceof TCComponentFolder))) {
								continue;
							}
							TCComponent[] workTasks = folder
									.getReferenceListProperty("fnd0MyWorkflowTasks");// 
							if (workTasks != null && workTasks.length != 0) {
								for (int i = 0; i < workTasks.length; i++) {
									TCComponent task = workTasks[i];

									TCComponent[] sechedules = task
											.getReferenceListProperty("project_task_attachments");
									if (sechedules != null
											&& sechedules.length != 0) {
										for (TCComponent sechedule : sechedules) {
											System.out
													.println(" secheduleType ="
															+ sechedule
																	.getType());
											if (sechedule instanceof TCComponentScheduleTask) {

												String[] projectIDs = ((TCComponentScheduleTask) sechedule)
														.getTCProperty(
																"schedule_tag")
														.getReferenceValue()
														.getTCProperty(
																"project_ids")
														.getStringValue()
														.split(";");
												if (projectIDs == null
														|| projectIDs.length != 1) {
													MessageBox
															.post("ǰʱûйĿָĿִд˲",
																	"",
																	MessageBox.ERROR);
													return;
												}

												this.projectID = projectIDs[0];
												HashMap<String, TMomExportTaskReportProjBean> projMapping = getProjNode(projectID);
												sechedule = ((TCComponentScheduleTask) sechedule)
														.getTCProperty(
																"schedule_tag")
														.getReferenceValue()
														.getTCProperty(
																"sch_summary_task")
														.getReferenceValue();

												secheduleTaskList = getDependencys(
														sechedule,
														secheduleTaskList, 0);
												System.out
														.println("secheduleTaskList.size = "
																+ secheduleTaskList
																		.size());
												TCProperty[][] props = TCComponentType
														.getTCPropertiesSet(
																secheduleTaskList,
																new String[] {
																		"object_name",// 
																		"sch_task_deliverable_list",// 
																		"fnd0state",// ״̬
																		"fnd0workflow_owner",// 
																		"finish_date",// ƻʱ
																		"workflow_process" });// 
												if (props != null) {
													for (int w = 0; w < props.length; w++) {
														TMomExportTaskReportBean bean = new TMomExportTaskReportBean();
														bean.setKeyNode(true);
														if (props[w][0] != null) {
															bean.setName(props[w][0]
																	.getStringValue());
															if (((TMomExportTaskReportOptionBean) this.selectBox
																	.getSelectedItem())
																	.getValuesList()
																	.contains(
																			props[w][0]
																					.getStringValue())) {
																// TODO ڵ
																bean.setMustNode(true);
															}

														}
														if (props[w][2] != null) {
															bean.setState(props[w][2]
																	.getDisplayValue());
															System.out
																	.println("STATE = "
																			+ props[w][2]
																					.getStringValue());
														}
														if (props[w][3] != null) {
															String userName = props[w][3]
																	.getReferenceValue() == null ? ""
																	: ((TCComponentUser) props[w][3]
																			.getReferenceValue())
																			.getStringProperty("user_name");
															bean.setPersion(userName);
														}
														if (props[w][4] != null) {
															Date date = props[w][4]
																	.getDateValue();
															bean.setFinishDate(date == null ? ""
																	: sdf.format(date));
														}
														// if
														// (bean.getState().equals(
														// "")
														// || bean.getState()
														// .equals("complete"))
														if (props[w][5] != null) {
															TCComponent processTask = props[w][5]
																	.getReferenceValue();
															if (processTask != null) {
																TCComponent rootTask = processTask
																		.getReferenceProperty("root_task");
																Date date = rootTask
																		.getDateProperty("last_mod_date");
																bean.setActureFinishDate(sdf
																		.format(date));
																bean.setFileName(getTargetComponent(
																		rootTask,
																		bean));
																if (projMapping
																		.containsKey(props[w][0]
																				.getStringValue())) {
																	System.out
																			.println("ؼڵĿ");
																	TMomExportTaskReportProjBean projectBean = projMapping
																			.get(props[w][0]
																					.getStringValue());
																	// TODO Ŀ
																	getProjData(
																			projectBean
																					.getFileNameList(),
																			bean);
																	projectBean
																			.setSelect(true);

																}
															}
														} else {
															TMomExportTaskReportProjBean projectBean = projMapping
																	.get(props[w][0]
																			.getStringValue());
															// TODO Ŀ
															getProjData(
																	projectBean
																			.getFileNameList(),
																	bean);
															projectBean
																	.setSelect(false);

														}
														this.beanList.add(bean);
													}
													getAllProjData(projMapping,
															beanList);
													// TODO ߼

													writeAllBeanExcel(orderByBeanList(beanList));
												}
											}
										}
									} else {
										thread.stopBar();
										MessageBox.post("ѡĶʱ", "",
												MessageBox.ERROR);
									}
								}
								haveTask = true;
							} else {
								continue;
							}
						}
						if (!haveTask) {
							thread.stopBar();
							MessageBox.post("ѡĶڹб", "",
									MessageBox.ERROR);
						}
					} else {
						thread.stopBar();
						MessageBox.post("ѡEXCELв", "",
								MessageBox.ERROR);
					}

				} else {
					thread.stopBar();
					MessageBox.post("ѡEXCELٽв", "", MessageBox.ERROR);
				}

			} else {
				// TODO
			}
		} catch (Exception e) {
			e.printStackTrace();
			thread.stopBar();
			MessageBox.post("Ŀ쳣", "", MessageBox.ERROR);
		}
		thread.stopBar();
		MessageBox.post("Ŀ", "ʾ", MessageBox.INFORMATION);
	}

	public List<TMomExportTaskReportBean> orderByBeanList(
			List<TMomExportTaskReportBean> list) {
		List<TMomExportTaskReportBean> beanAll = new ArrayList<>();
		List<TMomExportTaskReportBean> keyAll = new ArrayList<>();
		List<TMomExportTaskReportBean> mustAll = new ArrayList<>();
		List<TMomExportTaskReportBean> nullAll = new ArrayList<>();
		for (TMomExportTaskReportBean bean : list) {
			if (!bean.isKeyNode())
				if (bean.getName() == null || bean.getName().trim().isEmpty()
						|| bean.getFileName() == null
				// || bean.getFileName().length == 0
				// || bean.getFileName()[0].getFileName().trim().isEmpty()
				) {
					continue;
				}
			if (bean.isMustNode()) {
				mustAll.add(bean);
			} else if (!bean.isMustNode() && bean.isKeyNode()) {
				keyAll.add(bean);
			} else {
				nullAll.add(bean);
			}

		}
		for (TMomExportTaskReportBean bean : mustAll) {
			beanAll.add(bean);
		}
		for (TMomExportTaskReportBean bean : keyAll) {
			beanAll.add(bean);
		}

		beanAll.add(new TMomExportTaskReportBean());

		for (TMomExportTaskReportBean bean : nullAll) {
			beanAll.add(bean);
		}

		return beanAll;

	}

	/**
	 * ȡĿе
	 * 
	 * @param mapping
	 * @param beanList
	 */
	public void getAllProjData(
			HashMap<String, TMomExportTaskReportProjBean> mapping,
			List<TMomExportTaskReportBean> beanList) {
		Iterator<Entry<String, TMomExportTaskReportProjBean>> iterator = mapping
				.entrySet().iterator();
		System.out.println("ȡĿ");
		while (iterator.hasNext()) {

			Entry<String, TMomExportTaskReportProjBean> entry = iterator.next();

			TMomExportTaskReportProjBean bean = entry.getValue();
			System.out.println(" entry key = "
					+ entry.getKey()
					+ " select= "
					+ bean.isSelect()
					+ " count ="
					+ (bean.getFileNameList() == null ? "NULL" : bean
							.getFileNameList().size()));
			List<TCComponent> comps = bean.getFileNameList();
			TMomExportTaskReportBean reportBean = new TMomExportTaskReportBean();
			reportBean.setName(entry.getKey());
			List<TMomExportTaskReportFileBean> fileList = new ArrayList<TMomExportTaskReportFileBean>();
			if (!bean.isSelect()) {
				// TODO ûбѡеʱ
				String nodeName = bean.getNodeName();
				if (((TMomExportTaskReportOptionBean) this.selectBox
						.getSelectedItem()) == null
						|| !((TMomExportTaskReportOptionBean) this.selectBox
								.getSelectedItem()).getTypeList().contains(
								nodeName)) {
					// reportBean.setMustNode(true);
					continue;
				} else {
					reportBean.setMustNode(false);
					reportBean.setKeyNode(false);
				}
				TCProperty[][] obProps;
				try {
					obProps = TCComponentType.getTCPropertiesSet(comps,
							new String[] { "object_string", // 
									"owning_user",// 
									"date_released" });

					if (obProps != null) {

						for (int i = 0; i < obProps.length; i++) {
							TMomExportTaskReportFileBean fileBean = new TMomExportTaskReportFileBean();
							if (null != obProps[i][0]) {
								fileBean.setFileName(obProps[i][0]
										.getStringValue());
								reportBean
										.setFinishDate(sdf.format(new Date()));
							} else {
								fileBean.setFileName("");
							}
							if (null != obProps[i][1]) {
								fileBean.setPersion(obProps[i][1]
										.getReferenceValue().getStringProperty(
												"user_name"));
							} else {
								fileBean.setPersion("");
							}
							if (null != obProps[i][2]
									&& obProps[i][2].getDateValue() != null) {
								fileBean.setActureFinishDate(sdf
										.format(obProps[i][2].getDateValue()));
								fileBean.setState("");

							} else {
								fileBean.setActureFinishDate("");
								fileBean.setState("δ");
							}
							fileList.add(fileBean);
						}

					}
				} catch (TCException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				// TODO
				if (fileList.size() == 0) {
					fileList.add(new TMomExportTaskReportFileBean());
				}
				reportBean.setFileName(fileList
						.toArray(new TMomExportTaskReportFileBean[fileList
								.size()]));

				beanList.add(reportBean);

			}

		}
	}

	/**
	 * ȡĿеĽڵ
	 * 
	 * @param comps
	 * @param bean
	 */
	public void getProjData(List<TCComponent> comps,
			TMomExportTaskReportBean bean) {
		List<TMomExportTaskReportFileBean> fileList = new ArrayList<TMomExportTaskReportFileBean>();
		TMomExportTaskReportFileBean[] beans = bean.getFileName();
		for (TMomExportTaskReportFileBean sinBean : beans) {
			if (!sinBean.getFileName().trim().isEmpty()) {
				fileList.add(sinBean);
			}
		}
		try {
			System.out.println("ȡĿ");
			TMomExportTaskReportFileBean fileBean = new TMomExportTaskReportFileBean();

			TCProperty[][] obProps = TCComponentType.getTCPropertiesSet(comps,
					new String[] { "object_string", // 
							"owning_user",// 
							"date_released" });
			if (obProps != null) {
				for (int i = 0; i < obProps.length; i++) {
					if (null != obProps[i][0]) {
						fileBean.setFileName(obProps[i][0].getStringValue());
					} else {
						fileBean.setFileName("");
					}
					if (null != obProps[i][1]) {
						fileBean.setPersion(obProps[i][1].getReferenceValue()
								.getStringProperty("user_name"));
					} else {
						fileBean.setPersion("");
					}
					if (null != obProps[i][2]
							&& obProps[i][2].getDateValue() != null) {
						fileBean.setActureFinishDate(sdf.format(obProps[i][2]
								.getDateValue()));
						fileBean.setState("");
					} else {
						fileBean.setActureFinishDate("");
						fileBean.setState("δ");
					}
					fileList.add(fileBean);
				}
			}

		} catch (TCException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (fileList == null || fileList.size() == 0) {
			fileList.add(new TMomExportTaskReportFileBean());
		}
		bean.setFileName(fileList
				.toArray(new TMomExportTaskReportFileBean[fileList.size()]));

	}

	/**
	 * ȡĿ
	 * 
	 * @param comp
	 * @return
	 */
	public TMomExportTaskReportFileBean[] getTargetComponent(TCComponent comp,
			TMomExportTaskReportBean bean) {
		List<TMomExportTaskReportFileBean> strList = new ArrayList<>();
		try {
			TCComponent[] comps = comp.getReferenceListProperty("attachments");
			if (comps != null) {
				for (TCComponent compT : comps) {
					if (compT instanceof TCComponentFolder) {
						TCComponent[] compTT = compT
								.getReferenceListProperty("contents");

						for (TCComponent compTTT : compTT) {
							TMomExportTaskReportFileBean fileBean = new TMomExportTaskReportFileBean();
							TCProperty[] obProps = compTTT
									.getTCProperties(new String[] {
											"object_string", // 
											"owning_user",// 
											"date_released" });// 󷢲ʱ
							if (null != obProps[0]) {
								fileBean.setFileName(obProps[0]
										.getStringValue());
							} else {
								fileBean.setFileName("");
							}
							if (null != obProps[1]) {
								fileBean.setPersion(obProps[1]
										.getReferenceValue().getStringProperty(
												"user_name"));
							} else {
								fileBean.setPersion("");
							}
							if (null != obProps[2]
									&& obProps[2].getDateValue() != null) {
								fileBean.setActureFinishDate(sdf
										.format(obProps[2].getDateValue()));
								fileBean.setState("");
							} else {
								fileBean.setActureFinishDate("");
								fileBean.setState("δ");
							}
							strList.add(fileBean);
						}
					}
				}
			}
		} catch (TCException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		}
		if (strList.size() == 0) {
			strList.add(new TMomExportTaskReportFileBean());
		}
		return strList
				.toArray(new TMomExportTaskReportFileBean[strList.size()]);

	}

	/**
	 * гĿеļ
	 * 
	 * @param projID
	 * @return
	 */
	public HashMap<String, TMomExportTaskReportProjBean> getProjNode(
			String projID) {
		HashMap<String, TMomExportTaskReportProjBean> projectNodeMapping = new HashMap<>();
		TCComponentProject project = null;
		try {
			TCComponentProjectType projectType = (TCComponentProjectType) session
					.getTypeComponent("TC_Project");
			project = projectType.find(projID);
		} catch (TCException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			System.out.println("ȡĿTYPE");
			return new HashMap<>();
		}

		if (project == null) {
			System.out.println("ĿΪ");
			return null;
		}
		try {
			TCComponent[] dataComps = project
					.getReferenceListProperty("project_data");
			if (dataComps != null) {// ȡһ
				TCProperty[][] props = TCComponentType.getTCPropertiesSet(
						Arrays.asList(dataComps),
						new String[] { "project_data" });
				for (int i = 0; i < props.length; i++) {// ȡڶ
					if (props[i][0] != null) {
						TCProperty[][] fileProps = TCComponentType
								.getTCPropertiesSet(Arrays.asList(props[i][0]
										.getReferenceValueArray()),
										new String[] { "folder_name",
												"project_data" });
						for (int j = 0; (fileProps != null && j < fileProps.length); j++) {
							TMomExportTaskReportProjBean bean = new TMomExportTaskReportProjBean();
							if (fileProps[j][0] != null) {
								bean.setNodeName(fileProps[j][0]
										.getStringValue());
							}
							if (fileProps[j][1] != null) {
								TCProperty[][] objectProps = TCComponentType
										.getTCPropertiesSet(
												Arrays.asList(fileProps[j][1]
														.getReferenceValueArray()),
												new String[] { "object_name" });
								List<TCComponent> objecNameList = new ArrayList<>();

								System.out.println("Project Node Name = "
										+ bean.getNodeName());
								if (fileProps[j][1].getReferenceValueArray() != null) {
									List<TCComponent> listComps = new ArrayList<>();
									if (fileProps[j][1]
											.getReferenceValueArray() != null) {
										for (TCComponent compSin : fileProps[j][1]
												.getReferenceValueArray()) {
											if (compSin instanceof TCComponentItem) {
												if (!listComps
														.contains(((TCComponentItem) compSin)
																.getLatestItemRevision()))
													listComps
															.add(((TCComponentItem) compSin)
																	.getLatestItemRevision());
											} else if (compSin instanceof TCComponentItemRevision) {
												if (!listComps
														.contains(((TCComponentItemRevision) compSin)
																.getItem()
																.getLatestItemRevision()))
													listComps
															.add(((TCComponentItemRevision) compSin)
																	.getItem()
																	.getLatestItemRevision());
											} else {
												listComps.add(compSin);
											}
										}
									}

									bean.setFileNameList(listComps);
									// bean.setFileNameList(Arrays
									// .asList(fileProps[j][1]
									// .getReferenceValueArray()));
								}

							}
							projectNodeMapping.put(bean.getNodeName(), bean);
						}
					}
				}
			}
		} catch (TCException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return projectNodeMapping;
	}

	/**
	 * ȡڵ
	 * 
	 * @param dependenceTask2
	 * @param listTask
	 * @return
	 */
	public List<TCComponentScheduleTask> getDependencys(
			TCComponent dependenceTask2,
			List<TCComponentScheduleTask> listTask, int stage) {
		try {

			TCComponent[] dependenceTasks = dependenceTask2
					.getReferenceListProperty("child_task_taglist");// TaskDependency
			if (dependenceTasks != null && dependenceTasks.length != 0) {
				for (TCComponent dependenceTask : dependenceTasks) {
					String objectName = dependenceTask
							.getStringProperty("object_name");
					System.out.println("Schedule Node Name =" + objectName);
					if (stage == 0
							&& (selectBox.getSelectedIndex() == -1 || !objectName
									.equals(((TMomExportTaskReportOptionBean) selectBox
											.getSelectedItem()).getDisName()))) {
						System.out
								.println(selectBox.getSelectedIndex() != -1 ? "selectBox Select Name ="
										+ ((TMomExportTaskReportOptionBean) selectBox
												.getSelectedItem())
												.getDisName()
										: "selectBox Select Index = -1");
						System.out.println("ѭ");
						continue;
					}
					System.out.println("xxxxs");
					getDependencys(dependenceTask, listTask, 1);
					if (stage != 0)
						listTask.add((TCComponentScheduleTask) dependenceTask);
				}
			}
		} catch (TCException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return listTask;
	}

	public void writeAllBeanExcel(List<TMomExportTaskReportBean> beanListAll) {
		// excelDataset
		InputStream is = TMomExportTaskReportCommond.class
				.getResourceAsStream("Ƶ.xlsx");
		String outExcelPath = System.getenv("TEMP") + "\\Ƶ.xlsx";

		ExcelUtil07 util = new ExcelUtil07();
		try {
			util.writeExcel2(is, outExcelPath, beanListAll, 3);
			changeDataSet(excelDataset, "excel", "MSExcelX", outExcelPath);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TCException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * ıݼ
	 * 
	 * @param tccomponentDataset
	 * @param quote
	 * @param type
	 * @param path
	 * @throws TCException
	 */
	public static void changeDataSet(TCComponentDataset tccomponentDataset,
			String quote, String type, String path) throws TCException {
		String myPath[] = { path };
		String myQuote[] = { quote };// "excel"
		String myType[] = { type };// "MSExcelX"
		String myPlain[] = { "Plain" };

		// ɾݼ
		deleDateSetRef(tccomponentDataset);
		// ݼ滻
		tccomponentDataset.setFiles(myPath, myType, myPlain, myQuote);

	}

	/**
	 * ɾݼ
	 * 
	 * @param dataset
	 * @throws TCException
	 */
	private static void deleDateSetRef(TCComponentDataset dataset)
			throws TCException {

		TCComponentTcFile[] tcFiles = dataset.getTcFiles();
		for (int i = 0; i < tcFiles.length; i++) {
			// õݼ
			String str_temp = getNamedRefType(dataset, tcFiles[i]);
			// ɾ
			dataset.removeNamedReference(str_temp);
		}

	}

	/**
	 * õݼ
	 * 
	 * @param datasetComponent
	 * @param tccomponent
	 * @return
	 * @throws TCException
	 */
	private static String getNamedRefType(TCComponentDataset datasetComponent,
			TCComponentTcFile tccomponent) throws TCException {
		String s;
		s = "";
		TCProperty tcproperty;
		TCProperty tcproperty1;
		TCComponent atccomponent[];
		String as[];
		int i;
		int j;
		int k;
		try {
			tcproperty = datasetComponent.getTCProperty("ref_list");
			tcproperty1 = datasetComponent.getTCProperty("ref_names");
			if (tcproperty == null || tcproperty1 == null)
				return s;
		} catch (TCException tcexception) {
			return s;
		}
		atccomponent = tcproperty.getReferenceValueArray();
		as = tcproperty1.getStringValueArray();
		if (atccomponent == null || as == null)
			return s;
		i = atccomponent.length;
		if (i != as.length)
			return s;
		j = -1;
		k = 0;
		do {
			if (k >= i)
				break;
			if (tccomponent == atccomponent[k]) {
				j = k;
				break;
			}
			k++;
		} while (true);
		if (j != -1)
			s = as[j];
		return s;
	}

	/**
	 * ȡ
	 * 
	 * @param prop
	 * @param isEmpty
	 * @return
	 */
	public String getTcproptertyToStr(TCProperty prop, String compType) {
		if (prop == null) {
			return "";
		}
		String tempPath = System.getenv("TEMP");
		if (tempPath == null) {
			tempPath = "";
		} else if (!tempPath.endsWith("\\")) {
			tempPath = tempPath + "\\";
		}
		String propValue = new String();
		int propType = prop.getPropertyType();
		switch (propType) {
		case TCProperty.PROP_untyped_relation:
			TCComponent[] comps = prop.getReferenceValueArray();
			try {
				propValue = downLoadFile(comps, compType);
			} catch (TCException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			break;
		case TCProperty.PROP_int:
			propValue = "" + prop.getIntValue();
			break;
		case TCProperty.PROP_string:
			propValue = prop.getStringValue();
			break;
		case TCProperty.PROP_date:

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date date = prop.getDateValue();
			if (date != null)
				propValue = sdf.format(date);
			else
				propValue = "";
			break;
		}
		return propValue;
	}

	/**
	 * ļ
	 * 
	 * @param comps
	 * @return
	 * @throws TCException
	 * @throws IOException
	 */
	public String downLoadFile(TCComponent[] comps, String compType)
			throws TCException, IOException {
		if (comps == null) {
			return "";
		}
		String value = "";
		String tempPath = System.getenv("TEMP");
		// MessageBox.post(" tempPath = "+tempPath,"INFO",MessageBox.INFORMATION);
		if (tempPath == null) {
			tempPath = "";
		} else if (!tempPath.endsWith("\\")) {
			tempPath = tempPath + "\\";
		}
		SimpleDateFormat sdf = new SimpleDateFormat(TMomFinalUtil.TIME_FORMAT2);
		for (TCComponent comp : comps) {
			if (comp instanceof TCComponentDataset) {
				if (!comp.getType().equals(compType)) {
					continue;
				}
				TCComponentTcFile[] tcFiles = ((TCComponentDataset) comp)
						.getTcFiles();
				File file = null;
				if (tcFiles != null) {
					file = tcFiles[0].getFmsFile();
					String fileName = file.getName();
					String fileDix = fileName.substring(
							fileName.lastIndexOf("."), fileName.length());
					fileName = tempPath + sdf.format(new Date()) + fileDix;
					File dirFile = new File(fileName);
					FileUtility.copyFile(file, dirFile);
					if (compType.equals(TMomFinalUtil.JF3_DATASET_TYPE)) {
						this.excelDataset = (TCComponentDataset) comp;
					}
					return fileName;
				}
			}
		}
		return value;
	}

}
