/*
#=============================================================================
#																			   
#			Copyright (c) 2009 Origin Enterprise Solution LTD.		   
#																			   
#=============================================================================
# File name: ResultDialog.java
# File description: 										   	
#=============================================================================
#	Date		Name		Action	Description of Change					   
#	2011-4-20	liqz  		Ini		初始化(From Shaangu)										   
#=============================================================================
 */
package cn.com.customization.util;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
import com.teamcenter.rac.aif.AbstractAIFDialog;
import com.teamcenter.rac.kernel.TCAccessControlService;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentDataset;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentTcFile;
import com.teamcenter.rac.kernel.TCComponentUser;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCPreferenceService;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.kernel.TCUserService;
import com.teamcenter.rac.util.MessageBox;
import com.teamcenter.rac.util.PropertyLayout;

public class ResultDialog extends AbstractAIFDialog {

	/**
	 * 
	 */
	private static final long			serialVersionUID		= 1L;
	private TCSession					session;
	private GetCommonInfo				checkcommon;
	private ResultTableModel			dtm						= null;
	private JTable						table;
	private List<PackFailDownInfo>		tableData;
	private JButton						confirmButton			= null;
	private String						validTypeOption			= "origin_batchdown_validtype";
	// 当origin_showLogFile中的值为true则会生成日志文件：c:\\batchExportDataset.log
	private String						isShowLogOption			= "origin_showLogFile";
	private String						logFileName				= "c:\\batchExportDataset.log";
	private PackResultInfo				resultInfo;
	private boolean						isDownReleased			= false;
	private WriteAndCopyFile			writeLog;

	private int							downDataSetCount		= 0;
	private int							isNotHavePriviligeCount	= 0;
	private int							haveEqualDataSetCount	= 0;
	private int							needDownCount			= 0;
	private int							notReleasedDataSetCount	= 0;
	private int							downCount				= 0;
	private List<TCComponentDataset>	haveDownDataSet			= new ArrayList<TCComponentDataset>();
	private List<String>				notExistFiles			= new ArrayList<String>();
	private List<PackFailDownInfo>		failDownInfos			= new ArrayList<PackFailDownInfo>();

	private JLabel						existDataSetLb			= new JLabel();
	private JLabel						needLb					= new JLabel();
	private JLabel						successLb				= new JLabel();
	private JLabel						noReleaseLb				= new JLabel();
	private JLabel						noPrevilegeLb			= new JLabel();
	private JLabel						noReferenceFileLb		= new JLabel();
	private JLabel						failLb					= new JLabel();
	private List<PackSuccessfulInfo>	successfulInfos			= new ArrayList<PackSuccessfulInfo>();
	private String						successfulDir			= "c:/ugs/log";
	private TCUserService				userService				= null;
	private List<String>				logsList				= new ArrayList<String>();
	
	public ResultDialog(PackResultInfo resultInfo, TCSession session) {
		super(true);
		this.resultInfo = resultInfo;
		this.session = session;
		checkcommon = new GetCommonInfo(session);
		this.tableData = resultInfo.getFailDownInfo();
		writeLog = new WriteAndCopyFile();
		userService = (TCUserService) session.getUserService();
		
		if (isShowLog()) {
			File file = new File(logFileName);
			if (file.exists()) {
				writeLog.writeFile(logFileName, true, "\n");
			} else {
				try {
					file.createNewFile();
					writeLog.writeFile(logFileName, true, "\n");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} else {
			File file = new File(logFileName);
			if (file.exists()) {
				file.delete();
			}
		}
		initUI();
	}

	public void initUI() {
		// setPersistentDisplay(true);
		setOptimalDisplay(false);
		this.setTitle("下载结果");
		BorderLayout borderLayout = new BorderLayout();
		JPanel panel = new JPanel(borderLayout);
		panel.add(setTopPanel(), BorderLayout.NORTH);
//		panel.add(setCenterPanel(), BorderLayout.CENTER);
		panel.add(setBottomPanel(), BorderLayout.SOUTH);
		getContentPane().add(panel);
		Dimension screen = getToolkit().getScreenSize();
		setPreferredSize(new Dimension(400,300));
//		setLocation((screen.width - getSize().width) / 2, (screen.height - getSize().height) / 2);
		centerToScreen();
		this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				dispose();
			}
		});
		pack();
		this.setVisible(true);
	}

	private JPanel setTopPanel() {
		JPanel panel1 = new JPanel(new PropertyLayout());
		JLabel infoLb = new JLabel(" 下载文件统计：");
		existDataSetLb.setText(" 存在数据集：" + resultInfo.getExistDataSetCount());
		noReleaseLb.setText(" 未发布数据集:" + resultInfo.getNoReleasedNum());
		noPrevilegeLb.setText(" 无权限数据集:" + resultInfo.getNoPrivilegelNum());
		needLb.setText(" 需要下载文件:" + resultInfo.getNeedNum());
		successLb.setText(" 成功下载文件:" + resultInfo.getSuccessNum());
		noReferenceFileLb.setText(" 无引用文件数据集:" + resultInfo.getNoReferenceNum());
		failLb.setText(" 未成功下载文件个数：" + resultInfo.getFailNum());

		panel1.add("1.1.left.center", new JLabel());
		panel1.add("2.1.left.center", existDataSetLb);
		panel1.add("3.1.left.center", noReleaseLb);
		panel1.add("4.1.left.center", noPrevilegeLb);
		panel1.add("5.1.left.center", needLb);
		panel1.add("6.1.left.center", successLb);
		panel1.add("7.1.left.center", noReferenceFileLb);

		JPanel panel2 = new JPanel(new PropertyLayout());
		panel2.add("1.1.left.center", new JLabel());
		panel2.add("2.1.left.center", failLb);

		JPanel panel = new JPanel(new PropertyLayout());
		panel.add("1.1.left.center", new JLabel());
		panel.add("2.1.left.center", infoLb);
		panel.add("3.1.left.center", panel1);
		panel.add("4.1.left.center", panel2);
		return panel;
	}

	private JPanel setCenterPanel() {
		JPanel panel = new JPanel(new PropertyLayout());
		dtm = new ResultTableModel(tableData);
		table = new JTable(dtm);
		table.setRowHeight(20);
		dtm.setTableColumnsWidth(table);
		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		// 对列进行渲染
		table.getColumnModel().getColumn(0).setCellRenderer(new TableColumnRender());
		table.getColumnModel().getColumn(7).setCellRenderer(new CheckBoxColumnRender());

		JScrollPane scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
		scrollPane.setAutoscrolls(true);
		scrollPane.setPreferredSize(new Dimension(690, 200));
		panel.add("1.1.left.center", scrollPane);
		panel.add("2.1.left.center", new JLabel(" "));
		panel.setBorder(new TitledBorder(""));
		return panel;
	}

	private JPanel setBottomPanel() {
		JPanel southPanel = new JPanel(new FlowLayout());
		southPanel.setSize(60, 10);
		confirmButton = new JButton("重新下载");
		confirmButton.addActionListener(new buttonListener());
		JButton exitButton = new JButton("取消");
		exitButton.addActionListener(new buttonListener());
		southPanel.add(confirmButton);
		southPanel.add(exitButton);
		return southPanel;
	}

	class buttonListener implements ActionListener {
		public void actionPerformed(ActionEvent event) {
			String name = ((JButton) event.getSource()).getText();
			if (name.equals("重新下载")) {
				confirmButtonAction();
			} else {
				if (name.equals("取消")) {
					dispose();
				}
			}
		}
	}

	private void writeSuccessfulLogFile(String fileName, String content) {
		content = content + "\n";
		writeLog.writeFile(fileName, true, content);
		logsList.add(content);
	}

	private void confirmButtonAction() {
		System.out.println("tableData.size()......." + tableData.size());
		if (tableData.size() > 0) {
			writeLogFile(logFileName, "\n");
			writeLogFile(logFileName, "重新下载:\n");
			PackSuccessfulInfo succesfulDataset = new PackSuccessfulInfo();
			succesfulDataset.setIndex("序号");
			succesfulDataset.setItemID("零组件ID");
			succesfulDataset.setItemRev("版本");
			succesfulDataset.setItemOwner("所有者");
			succesfulDataset.setDataset("数据集");
			succesfulDataset.setRefFile("命名的引用");
			successfulInfos.add(succesfulDataset);

			boolean need = false;
			for (int i = 0; i < tableData.size(); i++) {
				TCComponentDataset dataSet = tableData.get(i).getDataSet();
				String needDown = tableData.get(i).getNeedDown();
				if (needDown.equals("true")) {
					need = true;
					String filePath = tableData.get(i).getFilePath();
					String itemId = tableData.get(i).getItemId();
					String rev = tableData.get(i).getRev();
					String owner = tableData.get(i).getOwner();
					TCComponentItemRevision itemRevision = tableData.get(i).getItemRev();
					datasetFileDown(itemRevision, dataSet, filePath, itemId, rev, owner);
				}
			}

			SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd:HHmmss");
			String time = date.format(new Date());
			String logPath = successfulDir + "/陕鼓批量下载文件日志_" + (new SimpleDateFormat("yyyyMMdd")).format(new Date()) + ".log";
			writeSuccessfulLogFile(logPath, "  ");
			writeSuccessfulLogFile(logPath, "===========================================================================================================================");
			writeSuccessfulLogFile(logPath, "时间:" + time + "     下载人:" + resultInfo.getPerson() + "     所选流程(目录):" + resultInfo.getJob());
			writeSuccessfulLogFile(logPath, "  ");
			writeSuccessfulLogFile(logPath, "存在数据集:" + haveDownDataSet.size());
			writeSuccessfulLogFile(logPath, "未发布数据集:" + notReleasedDataSetCount);
			writeSuccessfulLogFile(logPath, "无权限数据集:" + isNotHavePriviligeCount);
			writeSuccessfulLogFile(logPath, "需下载文件:" + needDownCount);
			writeSuccessfulLogFile(logPath, "成功下载文件:" + downDataSetCount);
			writeSuccessfulLogFile(logPath, "无引用文件数据集:" + notExistFiles.size());
			writeSuccessfulLogFile(logPath, "  ");
			writeSuccessfulLogFile(logPath, "已成功下载文件列表:");
			writeSuccessfulLogFile(logPath, "---------------------------------------------------------------------------");
			for (int i = 0; i < successfulInfos.size(); i++) {
				PackSuccessfulInfo successfulInfo = successfulInfos.get(i);
				writeSuccessfulLogFile(logPath, appendSpace(successfulInfo.getIndex().trim(), 5) + appendSpace(successfulInfo.getItemID().trim(), 32) + appendSpace(successfulInfo.getItemRev().trim(), 5) + appendSpace(successfulInfo.getItemOwner().trim(), 25) + appendSpace(successfulInfo.getDataset().trim(), 50) + appendSpace(successfulInfo.getRefFile().trim(), 50));
			}
			writeSuccessfulLogFile(logPath, "  ");
			// 服务器端日志
			try {
				Object objs[] = new Object[1];
				objs[0] = logsList.toArray();
				userService.call("DatasetDownLog", objs);
			} catch (TCException e) {
				e.printStackTrace();
			}

			if (need) {
				writeLogFile(logFileName, " ");
				writeLogFile(logFileName, "总结：");
				writeLogFile(logFileName, "存在数据集:" + haveDownDataSet.size() + "个");
				writeLogFile(logFileName, "未发布数据集:" + notReleasedDataSetCount + "个");
				writeLogFile(logFileName, "无权限数据集:" + isNotHavePriviligeCount + "个");
				writeLogFile(logFileName, "需要下载文件:" + needDownCount + "个");
				writeLogFile(logFileName, "成功下载文件:" + downDataSetCount + "个");
				writeLogFile(logFileName, "无引用文件数据集:" + notExistFiles.size() + "个");
				writeLogFile(logFileName, "未成功下载文件:" + (needDownCount - downDataSetCount) + "个");

				resultInfo.setExistDataSetCount(haveDownDataSet.size());
				resultInfo.setNeedNum(needDownCount);
				resultInfo.setSuccessNum(downDataSetCount);
				resultInfo.setNoReleasedNum(notReleasedDataSetCount);
				resultInfo.setNoPrivilegelNum(isNotHavePriviligeCount);
				resultInfo.setNoReferenceNum(notExistFiles.size());
				resultInfo.setEqualNameNum(haveEqualDataSetCount);
				resultInfo.setFailNum(failDownInfos.size());
				resultInfo.setFailDownInfo(failDownInfos);
				updateDialog();
			} else {
				MessageBox.post("没有需要重新下载的数据集!", "INFO", MessageBox.INFORMATION);
			}
		} else {
			MessageBox.post("没有需要重新下载的数据集!", "INFO", MessageBox.INFORMATION);
		}
	}

	private String appendSpace(String str, int num) {
		if (str.length() < num) {
			for (int i = UtilApi.length(str) + 1; i <= num; i++) {
				str += " ";
			}
		}
		return str;
	}

	private void updateDialog() {
		existDataSetLb.setText(" 存在数据集：" + resultInfo.getExistDataSetCount());
		noReleaseLb.setText(" 未发布数据集:" + resultInfo.getNoReleasedNum());
		noPrevilegeLb.setText(" 无权限数据集:" + resultInfo.getNoPrivilegelNum());
		needLb.setText(" 需要下载文件:" + resultInfo.getNeedNum());
		successLb.setText(" 成功下载文件:" + resultInfo.getSuccessNum());
		noReferenceFileLb.setText(" 无引用文件数据集:" + resultInfo.getNoReferenceNum());
		failLb.setText(" 需重新下载：" + resultInfo.getFailNum());

		tableData = resultInfo.getFailDownInfo();
		dtm = new ResultTableModel(tableData);
		table.setModel(dtm);
		table.setRowHeight(20);
		dtm.setTableColumnsWidth(table);
		table.getColumnModel().getColumn(0).setCellRenderer(new TableColumnRender());
		table.getColumnModel().getColumn(7).setCellRenderer(new CheckBoxColumnRender());
		dtm.setTableColumnsWidth(table);

		downDataSetCount = 0;
		isNotHavePriviligeCount = 0;
		haveEqualDataSetCount = 0;
		needDownCount = 0;
		notReleasedDataSetCount = 0;
		downCount = 0;
		failDownInfos = new ArrayList<PackFailDownInfo>();
		haveDownDataSet = new ArrayList<TCComponentDataset>();
		notExistFiles = new ArrayList<String>();
	}

	/**
	 * datasetFileDown:导出数据集对象的引用文件
	 * @param @return 设定文件
	 * @param dataset
	 * @param fileCurrentPath
	 * @return String 对象类型
	 * @throws
	 * @since CodingExample　Ver 1.1
	 */

	private void datasetFileDown(TCComponentItemRevision itemRevision, TCComponentDataset dataSet, String currentPath, String itemId, String rev, String owner) {
		
		try {
			dataSet.refresh();
		} catch (TCException e2) {
			e2.printStackTrace();
		}
		if (haveDownDataSet != null) {
			if (haveDownDataSet.contains(dataSet)) {
				return;
			}
		}
		String fileCurrentPath = currentPath;
		haveDownDataSet.add(dataSet);
		writeLogFile(logFileName, "存在数据集:" + dataSet.toString());
		System.out.println("dataSet............" + dataSet.toString());
		PackFailDownInfo dataSetInfo = new PackFailDownInfo();
		dataSetInfo.setItemId(itemId);
		dataSetInfo.setRev(rev);
		dataSetInfo.setDatasetName(dataSet.toString());
		dataSetInfo.setDataSet(dataSet);
		dataSetInfo.setOwner(owner);
		dataSetInfo.setItemRev(itemRevision);
		try {
			String release = dataSet.getProperty("release_status_list").trim();
			if (release != null) {
				String regex = ".*Released.*";
				Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
				Matcher match = pattern.matcher(release);
				boolean find = match.find();
				if (!find) {
					notReleasedDataSetCount++;
					writeLogFile(logFileName, "未发布");
					if (isDownReleased) {
						dataSetInfo.setReason("未发布");
						failDownInfos.add(dataSetInfo);
						writeLogFile(logFileName, "");
						return;
					}
				} else {
					writeLogFile(logFileName, "已经发布");
				}
			}
		} catch (TCException e2) {
			e2.printStackTrace();
		}
		try {
			boolean isCanExport = false;
			isCanExport = checkAccessPrivilige(session.getUser(), dataSet, "EXPORT");
			if (!isCanExport) {
				++isNotHavePriviligeCount;
				dataSetInfo.setReason("没有导出权限");
				failDownInfos.add(dataSetInfo);
				writeLogFile(logFileName, "没有导出权限");
				writeLogFile(logFileName, " ");
				return;
			} else {
				writeLogFile(logFileName, "有导出权限 ");
			}
		} catch (TCException e1) {
			e1.printStackTrace();
		}
		TCComponentTcFile tcFile = null;
		String fileName = "";
		try {
			if ((dataSet.getTcFiles() != null) && (dataSet.getTcFiles().length > 0)) {
//				if (itemRevision != null) {
//					String revType = itemRevision.getType();
//					if (revType.equals("GGDitem Revision") || revType.equals("HTDitem Revision")) {
//						fileCurrentPath = createFile(fileCurrentPath, changePackageName);
//					}
//				}

				for (int i = 0; i < dataSet.getTcFiles().length; i++) {
					tcFile = dataSet.getTcFiles()[i];
					if (tcFile == null) {
						return;
					}
					tcFile.refresh();
					fileName = tcFile.getProperty("original_file_name");
					if (fileName != null) {
						needDownCount++;
						dataSetInfo.setReference_file(fileName);
						dataSetInfo.setFilePath(fileCurrentPath);
						dataSetInfo.setNeedDown("true");
						String fileType = "";
						String preFileName = "";
						int index = fileName.lastIndexOf(".");
						if (index > 0) {
							fileType = fileName.substring(index, fileName.length());
							preFileName = fileName.substring(0, index);
						} else {
							preFileName = fileName;
						}
						boolean flag = checkcommon.existFile(fileCurrentPath, fileName);
						if (flag) {
							haveEqualDataSetCount++;
							int pos = fileName.indexOf('.');
							if (pos > 0) {
								fileName = preFileName + "_" + UtilApi.getTimeNum() + fileType;
							}
						}
						if (fileName.indexOf('/') >= 0) {
							fileName = fileName.replace('/', '_');
						}
						downCount = 0;
						getTCFile(tcFile, fileCurrentPath, fileName, dataSetInfo);
					}
				}
			} else {
				dataSetInfo.setReason("不存在引用文件");
				failDownInfos.add(dataSetInfo);
				notExistFiles.add(dataSet.toString());
				writeLogFile(logFileName, "不存在引用文件！");
			}
			writeLogFile(logFileName, " ");
		} catch (Throwable e) {
			writeLogFile(logFileName, "导出文件时出现异常！");
			writeLogFile(logFileName, e.getMessage());
			writeLogFile(logFileName, " ");
			e.printStackTrace();
		}
	}

	private File getTCFile(TCComponentTcFile tcFile, String fileCurrentPath, String fileName, PackFailDownInfo dataSetInfo) {
		++downCount;
		if (downCount == 2) {
			writeLogFile(logFileName, "第二次下载");
		}
		File file = null;
		try {
			file = tcFile.getFile(fileCurrentPath, fileName);
			if (file != null) {
				++downDataSetCount;
				writeLogFile(logFileName, "导出文件:" + fileName + "      " + getTime());
				writeLogFile(logFileName, " ");

				// successfulInfos
				PackSuccessfulInfo succesfulDataset = new PackSuccessfulInfo();
				succesfulDataset.setIndex(String.valueOf(downDataSetCount));
				succesfulDataset.setItemID(dataSetInfo.getItemId());
				succesfulDataset.setItemRev(dataSetInfo.getRev());
				succesfulDataset.setItemOwner(dataSetInfo.getOwner());
				succesfulDataset.setDataset(dataSetInfo.getDatasetName());
				succesfulDataset.setRefFile(file.getName());
				successfulInfos.add(succesfulDataset);
			} else {
				writeLogFile(logFileName, "没有导出文件！");
			}
		} catch (Throwable e) {
			writeLogFile(logFileName, "文件导出时出现异常");
			String exceptionMessage = e.getMessage();
			writeLogFile(logFileName, exceptionMessage);
			writeLogFile(logFileName, " ");
			e.printStackTrace();
			if (downCount < 2) {
				file = getTCFile(tcFile, fileCurrentPath, fileName, dataSetInfo);
			} else {
				dataSetInfo.setReason(exceptionMessage);
				failDownInfos.add(dataSetInfo);
			}
		}
		return file;
	}

	private void writeLogFile(String fileName, String content) {
		if (isShowLog()) {
			content = content + "\n";
			writeLog.writeFile(fileName, true, content);
		}
	}

	public String getTime() {
		String strTime = "";
		try {
			SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss:SSS");
			strTime = bartDateFormat.format(new Date());
			// System.out.println(strTime);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strTime;
	}

	/**
	 * checkAccessPrivilige:检查用户对给Component是否有权限
	 * @param @return 设定文件
	 * @return String 对象类型
	 * @throws
	 * @since CodingExample　Ver 1.1
	 */
	private boolean checkAccessPrivilige(TCComponentUser user, TCComponent comp, String accessName) throws TCException {
		TCAccessControlService accessService = ((TCSession) session).getTCAccessControlService();
		boolean returnboolean = accessService.checkUsersPrivilege(user, comp, accessName);
		return returnboolean;
	}

	private boolean isShowLog() {
		boolean isShowLog = false;
		TCPreferenceService preSer = session.getPreferenceService();
		String value = preSer.getString(4, isShowLogOption).trim();
		if (value.equalsIgnoreCase("true")) {
			isShowLog = true;
		}
		return isShowLog;
	}

	public void isDownReleased() {
		TCPreferenceService preSer = session.getPreferenceService();
		String type = preSer.getString(4, validTypeOption).trim();
		if (type.equalsIgnoreCase("released")) {
			isDownReleased = true;
		}
	}
}
