package com.langtech.plm.form;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Month;
import java.time.YearMonth;
import java.time.temporal.ChronoUnit;
import java.time.temporal.WeekFields;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentDataset;
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 QueryNewProdFormFram extends JFrame implements ActionListener {

	private TCSession session;
	private JTable table;
	private String[] header = new String[] { "全选", "生产订单号", "产品代码", "物料编码", "产品名称", "同步时间", "生产计划号", "批次号", "工厂",
			"ERP班组编码" };
	protected DefaultTableModel tm_part;
	private static ArrayList<String> dateConnList = new ArrayList<String>();
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	private JTextField pathJTextField = new JTextField(30);
	private JTextField ljhField = new JTextField(15);
	private JTextField fprzhField = new JTextField(15);
	private JTextField clrField = new JTextField(15);
	private JTextField gwzField = new JTextField(15);
	private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	private DateButton TaskassignmentStartButton;
	private DateButton TaskassignmentEndButton;
	private DateButton CompletionDateStartButton;
	private DateButton CompletionDateEndButton;
	private JButton btnQry;
	private JButton outputButton = new JButton("选择");
	private JButton cleanButton1 = new JButton("清除");
	private JButton cleanButton2 = new JButton("清除");
	private JButton cleanButton3 = new JButton("清除");
	private JButton cleanButton4 = new JButton("清除");
	private JTextField cpdmField;

	// 名称-系数 map
	private HashMap<String, Double> ld_taskNatureMap = new HashMap<String, Double>();
	private HashMap<String, Double> ld_taskDifficultyMap = new HashMap<String, Double>();
	private HashMap<String, Double> ld_positionGroupMap = new HashMap<String, Double>();
	private HashMap<String, Double> ld_demeritMap = new HashMap<String, Double>();

	public QueryNewProdFormFram(TCSession session) {
		// TODO Auto-generated constructor stub
		this.session = session;
		initUI();
	}

//	private String sqlString = "delete ML_CREATEORDERBOM where STATUS='2' and PRODUCTID=? and MATERIALNO=? "
//			+ "and OBJECTNAME=? and PRODPLANO=? and BATCHNO=?"
//			+ " and FACTORY=? and REPCODE=? and PRODORDERO=?";
	private String sqlString = "";

	private void initUI() {
		// TODO Auto-generated method stub
		try {
			this.setTitle("查询绩效表");
			this.setLayout(new BorderLayout());

			JPanel topPanel = getTopPanel();

			// JScrollPane pane = getTablePanel();
			// pane.setBorder(BorderFactory.createTitledBorder(""));
//			JPanel btnPanel = getRightPanel();
			JPanel btnPanel = getBtnPanel();

			this.add(topPanel, BorderLayout.NORTH);
			// this.add(pane,BorderLayout.CENTER);
			this.add(btnPanel, BorderLayout.SOUTH);
			this.setPreferredSize(new Dimension(800, 292));
			int width2 = this.getWidth();
			int height2 = this.getHeight();
			Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); // 获取屏幕尺寸
			int screenWidth = screenSize.width; // 获取屏幕宽度
			int screenHeight = screenSize.height; // 获取屏幕高度
			int x = (screenWidth - 550) / 2; // 计算Frame的左上角x坐标
			int y = (screenHeight - 300) / 2; // 计算Frame的左上角y坐标
			this.setLocation(x, y); // 设置Frame的位置

			// this.setLocationRelativeTo(null);
			this.createActionEvent();
			this.pack();

			// this.validate();
			this.setVisible(true);

//			this.setAlwaysOnTop(true);

		} catch (Exception e) {
			e.printStackTrace();
			return;
		}
	}

	// 添加监听
	public void createActionEvent() {

		this.btnDis.addActionListener(this);
		this.btnOk.addActionListener(this);

	}

	private List<TCComponent> compList = new ArrayList<TCComponent>();

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub

		Object source = e.getSource();
		System.out.println("source==>+" + source);
		if (this.btnDis.equals(source)) {
			this.dispose();
		} else if (source.equals(this.btnOk)) {
			File model_file = null;
			File output_file = null;
			String[] value2 = session.getPreferenceService().getStringValues("LD_dbinfo2");

			if (value2 == null || value2.length == 0) {
				MessageBox.post("首选项LD_dbinfo配置有误，请检查。", "提示", 2);
				return;
			} else {
				Collections.addAll(dateConnList, value2);
			}

			// 获取计算属性
			getCalculate();
			sqlString = "SELECT * FROM LD6_NewProdForm_VALUES WHERE 1=1 ";

			// 1.根据条件查询数据
			getQuerySQL();
			System.out.println(sqlString);
			Connection conn = getConn();

			List<LD6_NewProdForm_Bean> lists = new ArrayList<LD6_NewProdForm_Bean>();
			try (PreparedStatement stmt = conn.prepareStatement(sqlString)) {

				ResultSet result = stmt.executeQuery();
				while (result.next()) {
					LD6_NewProdForm_Bean ld6_NewProdForm_Bean = new LD6_NewProdForm_Bean(result.getString(1),
							result.getString(2), result.getString(3), result.getString(4), result.getString(5),
							result.getString(6), result.getString(7), result.getString(8), result.getString(9),
							result.getString(10), result.getString(11), result.getString(12), result.getDate(13),
							result.getDate(14), result.getString(15), result.getDate(16), result.getString(17),
							result.getString(18));
					System.out.println(ld6_NewProdForm_Bean);
					// 过滤有处理人的数据
					if (ld6_NewProdForm_Bean.getProcessor() != null
							&& ld6_NewProdForm_Bean.getProcessor().contains("-")) {
						lists.add(ld6_NewProdForm_Bean);
					}

				}

			} catch (SQLException e1) {
				e1.printStackTrace();
			}

			if (lists.size() == 0) {
				MessageBox.post("未查到数据，无法导出！", "提示", 2);
				return;
			} else {
				// 导出数据的逻辑

				InputStream input;
				String targetPath = null;
				try {
					String[] lD6_NewProdForm_ModelUid = session.getPreferenceService()
							.getStringValues("LD6_NewProdForm_ModelUid");

					if (lD6_NewProdForm_ModelUid == null || lD6_NewProdForm_ModelUid.length == 0) {
						MessageBox.post("首选项LD6_NewProdForm_ModelUid配置有误，请检查。", "提示", 2);
						return;
					} else {
						String pathJTextFieldStr = pathJTextField.getText();
						if(pathJTextFieldStr == null || pathJTextFieldStr.isEmpty()) {
							MessageBox.post("请选择需要导出的路径。", "提示", 2);
							return;
						}
						
						TCComponentDataset excel = (TCComponentDataset) session
								.stringToComponent(lD6_NewProdForm_ModelUid[0]);

						model_file = ((TCComponentDataset) excel).getTcFiles()[0].getFmsFile();
						String date = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
						String fileName = "绩效查询表_" + date + ".xlsx";

						// 定义源文件路径
						Path sourcePath = Paths.get(model_file.getPath()); // 替换为你的源文件路径
						// 定义目标文件路径
						// targetPath = System.getProperty("user.home")+"\\Desktop"+"\\"+fileName;
						targetPath = pathJTextFieldStr + "\\" + fileName;
						// 使用Files.copy()方法复制文件

						// Files.copy(sourcePath, targetPath);
						// 设置可写
						// makeFileWritable(System.getProperty("user.home")+"\\Desktop"+"\\"+fileName);
						// output_file = new
						// File(System.getProperty("user.home")+"\\Desktop"+"\\"+fileName);

					}
					
					
					//获取文件夹的引用
					
					
					input = new FileInputStream(model_file);
					XSSFWorkbook wb = new XSSFWorkbook(input);// (
					XSSFSheet sheet = wb.getSheetAt(0);
					sheet.getSheetName();
					for (int i = 0; i < lists.size(); i++) {
						LD6_NewProdForm_Bean ld6_NewProdForm_Bean = lists.get(i);
						
						TCComponent component = session.stringToComponent(ld6_NewProdForm_Bean.getClientProductFolderPUID());
						AIFComponentContext[] whereReferenced = component.whereReferenced();
						String object_name = "";
						for (int j = 0; j < whereReferenced.length; j++) {
							String type = whereReferenced[j].getComponent().getProperty("object_type");
							System.out.println("type============="+type);
							if(type.equals("LD6_Customer") || type.equals("客户文件夹")) {
								object_name = whereReferenced[j].getComponent().getProperty("object_name");
							}
						}
						System.out.println("name====="+object_name);
						int row = i + 2;
						XSSFRow titleRow = sheet.getRow(row);
						setCellValue(titleRow, 0, i + 1 + "", sheet, row);
						// 零件号合零件名称逻辑
						String[] split = ld6_NewProdForm_Bean.getClientProductFolderName().split("_");
						setCellValue(titleRow, 1,
								split.length == 2 ? split[0] : ld6_NewProdForm_Bean.getClientProductFolderName(), sheet,
								row);
						setCellValue(titleRow, 2,
								split.length == 2 ? split[1] : ld6_NewProdForm_Bean.getClientProductFolderName(), sheet,
								row);
						// 1
						//setCellValue(titleRow, 3, ld6_NewProdForm_Bean.getCustomerName(), sheet, row);
						setCellValue(titleRow, 3, object_name, sheet, row);
						
						setCellValue(titleRow, 4, ld6_NewProdForm_Bean.getNewProductTaskItem(), sheet, row);
						setCellValue(titleRow, 5, ld6_NewProdForm_Bean.getAssignee(), sheet, row);
						setCellValue(titleRow, 6, ld6_NewProdForm_Bean.getNewProductTaskDescription(), sheet, row);
						setCellValue(titleRow, 7, ld6_NewProdForm_Bean.getProcessor(), sheet, row);
						setCellValue(titleRow, 8, ld6_NewProdForm_Bean.getPositionGroup(), sheet, row);
						setCellValue(titleRow, 9, ld6_NewProdForm_Bean.getTaskNature(), sheet, row);
						setCellValue(titleRow, 10, ld6_NewProdForm_Bean.getDifficultyLevel(), sheet, row);
						setCellValue(titleRow, 11, ld6_NewProdForm_Bean.getUrgencyLevelCode(), sheet, row);
						setCellValue(titleRow, 12, ld6_NewProdForm_Bean.getEstimatedBusinessHours(), sheet, row);
						setCellValue(titleRow, 13, ld6_NewProdForm_Bean.getActualBusinessHours(), sheet, row);

						setCellValue(titleRow, 14, ld6_NewProdForm_Bean.getTaskAssignmentDate() == null ? ""
								: sdf.format(ld6_NewProdForm_Bean.getTaskAssignmentDate()), sheet, row);
						if (ld6_NewProdForm_Bean.getTaskAssignmentDate() != null) {
							// 转换为LocalDate
							LocalDate localDate = ld6_NewProdForm_Bean.getTaskAssignmentDate().toLocalDate();
							// 获取年份
							int year = localDate.getYear();
							int month = localDate.getMonthValue() - 1;
							WeekFields weekFields = WeekFields.of(Locale.getDefault());
							int weekOfYear = localDate.get(weekFields.weekOfWeekBasedYear());

							setCellValue(titleRow, 15, year + "", sheet, row);
							setCellValue(titleRow, 16, month + "", sheet, row);
							setCellValue(titleRow, 17, weekOfYear + "", sheet, row);
						}

						setCellValue(titleRow, 18, ld6_NewProdForm_Bean.getDueDate() == null ? ""
								: sdf.format(ld6_NewProdForm_Bean.getDueDate()), sheet, row);
						if (ld6_NewProdForm_Bean.getDueDate() != null) {
							// 转换为LocalDate
							LocalDate localDate = ld6_NewProdForm_Bean.getDueDate().toLocalDate();
							// 获取年份
							int year = localDate.getYear();
							int month = localDate.getMonthValue() - 1;
							WeekFields weekFields = WeekFields.of(Locale.getDefault());
							int weekOfYear = localDate.get(weekFields.weekOfWeekBasedYear());

							setCellValue(titleRow, 19, year + "", sheet, row);
							setCellValue(titleRow, 20, month + "", sheet, row);
							setCellValue(titleRow, 21, weekOfYear + "", sheet, row);
						}

						setCellValue(titleRow, 22, ld6_NewProdForm_Bean.getCompletionDate() == null ? ""
								: sdf.format(ld6_NewProdForm_Bean.getCompletionDate()), sheet, row);
						if (ld6_NewProdForm_Bean.getCompletionDate() != null) {
							// 转换为LocalDate
							LocalDate localDate = ld6_NewProdForm_Bean.getCompletionDate().toLocalDate();
							// 获取年份
							int year = localDate.getYear();
							int month = localDate.getMonthValue() - 1;
							// int day = localDate.getDayOfMonth();

							// 获取日期所在年份的第几周
							WeekFields weekFields = WeekFields.of(Locale.getDefault());
							int weekOfYear = localDate.get(weekFields.weekOfWeekBasedYear());
							setCellValue(titleRow, 23, year + "", sheet, row);
							setCellValue(titleRow, 24, month + "", sheet, row);
							setCellValue(titleRow, 25, weekOfYear + "", sheet, row);
							setCellValue(titleRow, 26, "已完成", sheet, row);// 完成状态
						}

						java.sql.Date dueDate = ld6_NewProdForm_Bean.getDueDate();
						java.sql.Date completionDate = ld6_NewProdForm_Bean.getCompletionDate();
						// 计算得分
						Double score = null;
						String gwz = ld6_NewProdForm_Bean.getPositionGroup();// 岗位组
						String rwxz = ld6_NewProdForm_Bean.getTaskNature();// 任务性质
						String nycd = ld6_NewProdForm_Bean.getDifficultyLevel();// 难易程度
						if (completionDate != null && gwz != null && !gwz.isEmpty() && rwxz != null && !rwxz.isEmpty()
								&& nycd != null && !nycd.isEmpty()) {
							score = ld_positionGroupMap.get(gwz) * ld_taskNatureMap.get(rwxz)
									* ld_taskDifficultyMap.get(nycd);
							setCellValue(titleRow, 27, score == null ? "" : score + "", sheet, row);// 得分
						} else if (completionDate == null) {
							setCellValue(titleRow, 27, "0", sheet, row);// 得分
						}

						// 计算超时扣分

						if (score != null && dueDate != null && completionDate != null) {
							// 计算完成时间和计划时间之间差天数

							// 比较是否超时
							// 比较两个日期
							int result = dueDate.compareTo(completionDate);

							// 判断结果
							if (result < 0) {// 逾期
								System.out.println("Completion date is after Due date.");
								// 将java.sql.Date转换为java.time.LocalDate
								LocalDate dueDateLD = dueDate.toLocalDate();
								LocalDate completionDateLD = completionDate.toLocalDate();

								// 计算两个日期之间的天数差
								long daysBetween = ChronoUnit.DAYS.between(dueDateLD, completionDateLD);
								if (daysBetween == 1) {
									System.out.println("1天内");
									Double csdf = score * ld_demeritMap.get("一般");
									setCellValue(titleRow, 28, csdf + "", sheet, row);// 超时扣分
								} else if (daysBetween == 2) {
									System.out.println("2天内");
									Double csdf = score * ld_demeritMap.get("严重");
									setCellValue(titleRow, 28, csdf + "", sheet, row);// 超时扣分
								} else if (daysBetween == 3) {
									System.out.println("3天内");
									Double csdf = score * ld_demeritMap.get("超严重");
									setCellValue(titleRow, 28, csdf + "", sheet, row);// 超时扣分
								} else if (daysBetween > 3) {
									setCellValue(titleRow, 28, "超过三天", sheet, row);// 超时扣分
								}
							}

						}

						setCellValue(titleRow, 29, ld6_NewProdForm_Bean.getRemarks(), sheet, row);

					}
//					// 调整列宽
//		            for (int i = 0; i <= lists.size(); i++) { // A-N列
//		                sheet.autoSizeColumn(i);
//		            } 

					// 写入输出文件
					try (FileOutputStream outputStream = new FileOutputStream(new File(targetPath))) {
						wb.write(outputStream);
					} catch (FileNotFoundException e1) {
						System.err.println("目标文件未找到: " + targetPath);
						e1.printStackTrace();
					} catch (IOException e2) {
						System.err.println("写入文件时发生错误: " + targetPath);
						e2.printStackTrace();
					}

					this.dispose();
					MessageBox.post("成功导出" + lists.size() + "条数据！", "提示", 2);
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

			}

		}

	}

	private void getCalculate() {
		// TODO Auto-generated method stub
		String[] ld_taskNature = session.getPreferenceService().getStringValues("ld_taskNature");// 任务性质
		String[] ld_taskDifficulty = session.getPreferenceService().getStringValues("ld_taskDifficulty");// 难易程度
		String[] ld_positionGroup = session.getPreferenceService().getStringValues("ld_positionGroup");// 岗位系数
		String[] ld_demerit = session.getPreferenceService().getStringValues("ld_demerit");// 超时扣分
		for (int i = 0; i < ld_positionGroup.length; i++) {
			ld_positionGroupMap.put(ld_positionGroup[i].split("=")[0],
					Double.parseDouble(ld_positionGroup[i].split("=")[1]));
		}

		for (int i = 0; i < ld_taskNature.length; i++) {
			ld_taskNatureMap.put(ld_taskNature[i].split("=")[0], Double.parseDouble(ld_taskNature[i].split("=")[1]));
		}

		for (int i = 0; i < ld_taskDifficulty.length; i++) {
			ld_taskDifficultyMap.put(ld_taskDifficulty[i].split("=")[0],
					Double.parseDouble(ld_taskDifficulty[i].split("=")[1]));
		}

		for (int i = 0; i < ld_demerit.length; i++) {
			ld_demeritMap.put(ld_demerit[i].split("=")[0], Double.parseDouble(ld_demerit[i].split("=")[1]));
		}
	}

//	  public int getWeekOfMonth(int day) {
//		  if(day % 7 != 0) {
//			  return day / 7 + 1;
//		  }else {
//			  return day / 7;
//		  }
//	    }
//	

	/**
	 * 文件可写
	 * 
	 * @param filePath
	 */
	public static void makeFileWritable(String filePath) {
		File file = new File(filePath);
		if (!file.exists()) {
			System.out.println("File does not exist.");
			return;
		}
		try {
			// 设置文件可写，true 表示可写，false 表示不可写，null 表示使用系统默认值
			boolean success = file.setWritable(true, false); // 第二个参数表示是否只改变文件所有者的权限
			if (success) {
				System.out.println("File permissions set to writable.");
			} else {
				System.out.println("Failed to set file as writable.");
			}
		} catch (SecurityException se) {
			System.err.println("Security exception: " + se.getMessage());
		}
	}

	public static void setCellValue(XSSFRow row, int colum, String str, XSSFSheet sheet, int rowNum) {
		if (row == null) {
			// 处理空行的情况，比如插入一行或者给出提示
			row = sheet.createRow(rowNum);
		}
		XSSFCell cell = row.getCell(colum);
		if (cell == null) {
			cell = row.createCell(colum);
		}
		cell.setCellValue(str);
	}

	private void getQuerySQL() {
		// TODO Auto-generated method stub
		String cpwjjmc = ljhField.getText();
		if (!cpwjjmc.isEmpty()) {
			// 如果多值
			if (cpwjjmc.contains(";") || cpwjjmc.contains("；")) {
				String[] split = cpwjjmc.split(";");
				if (split.length == 0) {
					split = cpwjjmc.split("；");
				}
				for (int i = 0; i < split.length; i++) {
					sqlString += "AND ClientProductFolderName LIKE '%" + split[i] + "%' ";
				}
			} else {
				sqlString += "AND ClientProductFolderName LIKE '%" + cpwjjmc + "%' ";
			}
		}

		String fprzh = fprzhField.getText();
		if (!fprzh.isEmpty()) {
			sqlString += "AND Assignee LIKE '%" + fprzh + "%' ";
		}

		String clr = clrField.getText();
		if (!clr.isEmpty()) {
			sqlString += "AND Processor = '%" + clr + "%' ";
		}

		String gwz = gwzField.getText();
		if (!gwz.isEmpty()) {
			sqlString += "AND PositionGroup = '%" + gwz + "%' ";
		}

		if (TaskassignmentStartButton.getDate() != null) {
			sqlString += "AND TaskAssignmentDate <='" + dateFormat.format(TaskassignmentStartButton.getDate()) + "' ";
		}

		if (TaskassignmentEndButton.getDate() != null) {
			sqlString += "AND TaskAssignmentDate >='" + dateFormat.format(TaskassignmentEndButton.getDate()) + "' ";
		}

		if (CompletionDateStartButton.getDate() != null) {
			sqlString += "AND CompletionDate <='" + dateFormat.format(CompletionDateStartButton.getDate()) + "' ";
		}

		if (CompletionDateEndButton.getDate() != null) {
			sqlString += "AND CompletionDate >='" + dateFormat.format(CompletionDateEndButton.getDate()) + "' ";
		}

	}

	private JButton btnOk;
	private JButton btnDis;

	private JPanel getBtnPanel() {
		JPanel topPanel = new JPanel();
		topPanel.setLayout(new PropertyLayout());
		btnOk = new JButton("导出");
		btnDis = new JButton("取消");
		topPanel.add("1.1.center", btnOk);

		topPanel.add("1.2.center", btnDis);
		return topPanel;
	}

	// 查询部分
	private JPanel getTopPanel() {
		// TODO Auto-generated method stub
		JPanel topPanel = new JPanel();
		topPanel.setLayout(new PropertyLayout());
		topPanel.setBorder(new EmptyBorder(5, 5, 5, 5));

//			topPanel.add("1.1.left.center",field);
		topPanel.setBorder(BorderFactory.createTitledBorder("查询条件"));

		topPanel.add("1.1.left.center", new JLabel(" "));
		topPanel.add("2.1.left.center", getJLabel("零件号："));
		topPanel.add("2.2.left.center", ljhField);
		topPanel.add("2.3.left.center", cleanButton1);

		topPanel.add("2.4.left.center", getJLabel("分派人账号："));
		topPanel.add("2.5.left.center", fprzhField);
		topPanel.add("2.6.left.center", cleanButton2);

		topPanel.add("3.1.left.center", getJLabel("处理人："));
		topPanel.add("3.2.left.center", clrField);
		topPanel.add("3.3.left.center", cleanButton3);

		topPanel.add("3.4.left.center", getJLabel("岗位组："));
		topPanel.add("3.5.left.center", gwzField);
		topPanel.add("3.6.left.center", cleanButton4);




		
		TaskassignmentStartButton = new DateButton(dateFormat);
		TaskassignmentEndButton = new DateButton(dateFormat);
		TaskassignmentStartButton.setDate("未设置日期");
		TaskassignmentEndButton.setDate("未设置日期");
		CompletionDateStartButton = new DateButton(dateFormat);
		CompletionDateEndButton = new DateButton(dateFormat);
		CompletionDateStartButton.setDate("未设置日期");
		CompletionDateEndButton.setDate("未设置日期");
//		startButton.set
		topPanel.add("4.1.left.center", getJLabelDate("任务分派时间（早于）："));
		topPanel.add("4.2.left.center", TaskassignmentStartButton);
		topPanel.add("4.3.left.center", new JLabel("                   ")); // 添加空面板作为间距
		
		topPanel.add("4.4.center.center", getJLabelDate("任务分派时间（晚于）："));
		topPanel.add("4.5.left.center", TaskassignmentEndButton);
		topPanel.add("5.1.left.center", getJLabelDate("实际完成时间（早于）："));
		topPanel.add("5.2.left.center", CompletionDateStartButton);
		topPanel.add("5.3.left.center",  new JLabel("                   ")); // 添加空面板作为间距
		
		topPanel.add("5.4.center.center", getJLabelDate("实际完成时间（晚于）："));
		topPanel.add("5.5.left.center", CompletionDateEndButton);

		topPanel.add("6.1.left.center", new JLabel(""));


		topPanel.add("7.1.left.center", new JLabel("保存路径："));
		topPanel.add("7.2.left.center", pathJTextField);
		topPanel.add("7.3.left.center", outputButton);
		
		
		// 增加清除按钮监听
		cleanButton1.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				ljhField.setText("");
			}
		});

		cleanButton2.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				fprzhField.setText("");
			}
		});

		cleanButton3.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				clrField.setText("");
			}
		});

		cleanButton4.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				gwzField.setText("");
			}
		});
		// 注册输出按钮的点击事件监听器
		outputButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// 创建文件选择器
				JFileChooser fileChooser = new JFileChooser();
				// 设置文件选择器只能选择文件夹
				fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				int result = fileChooser.showOpenDialog(topPanel);
				if (result == JFileChooser.APPROVE_OPTION) {
					// 获取用户选择的路径
					String selectedPath = fileChooser.getSelectedFile().getPath();
					// 输出用户选择的路径
					System.out.println("用户选择的路径：" + selectedPath);
					pathJTextField.setText(selectedPath);
				}
			}
		});
		return topPanel;
	}

//	private JScrollPane getTablePanel() {
//		// TODO Auto-generated method stub
//		table = getJTable(null, null, header, null);
//		table.setRowHeight(30);
//		//table.setPreferredSize(new Dimension(1200,400));
//		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); // 设置表格的自动调整模式为关闭自动调整
//		table.getColumnModel().getColumn(0).setPreferredWidth(50);
//		table.addMouseListener(new MouseListener() {
//			
//			@Override
//			public void mouseReleased(MouseEvent e) {
//				// TODO Auto-generated method stub
//				
//			}
//			
//			@Override
//			public void mousePressed(MouseEvent e) {
//				// TODO Auto-generated method stub
//				
//			}
//			
//			@Override
//			public void mouseExited(MouseEvent e) {
//				// TODO Auto-generated method stub
//				
//			}
//			
//			@Override
//			public void mouseEntered(MouseEvent e) {
//				// TODO Auto-generated method stub
//				
//			}
//			
//			@Override
//			public void mouseClicked(MouseEvent e) {
//				// TODO Auto-generated method stub
//				int selectColumn = table.getTableHeader().columnAtPoint(e.getPoint());
//				int selectedRow = table.rowAtPoint(e.getPoint());
////				System.out.println("selectColumn==>"+selectColumn);
//		        if(selectColumn != 0)
//		        {
//	      		  	return;
//	      	  	}else {
//		      	  	Object valueAt = table.getValueAt(selectedRow, selectColumn);
//		      	  	if(valueAt.toString().equals("1")) {
//		      	  		table.setValueAt("0", selectedRow, selectColumn);
//		      	  	}else {
//		      	  		table.setValueAt("1", selectedRow, selectColumn);
//		      	  	}
//	      	  	}
//			}
//		});
//		JScrollPane pane = new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
//		pane.setPreferredSize(new Dimension(1200,400));
//		pane.setViewportView(table);//为scrollPane指定显示对象为table
//		return pane;
//	}
//	private DefaultTableModel map;
//	public JTable getJTable(JTable partsTable, DefaultTableModel dtm, Object[] titleNames, Object[][] values) {
//		int simpleLen = 150;
////		int totleLen = 1000;
//		if (partsTable == null) {
//			map = new DefaultTableModel(values, titleNames) {
//				@Override
//				public boolean isCellEditable(int row, int column) {
//					return false;
//				}
//			};
//
//			partsTable = new JTable(map) ;
//			
//			partsTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
////			Adapter1 adapter = new Adapter1(partsTable);
//			partsTable.getTableHeader().setDefaultRenderer(new CheckHeaderCellRenderer(partsTable));
////			setDefaultRenderer(new CheckHeaderCellRenderer(table));
//			
//			partsTable.setRowHeight(30);
//			// //设置显示器渲染
//			partsTable.getColumnModel().getColumn(0).setCellRenderer(new TableCellCheckboxRenderer(partsTable));
////			partsTable.setDefaultRenderer(Object.class, renderer);
//			partsTable.getTableHeader().setReorderingAllowed(false);
////			if (simpleLen * titleNames.length >= totleLen) {
//			for (int i = 0; i < titleNames.length; i++) {
//				partsTable.getColumnModel().getColumn(i).setPreferredWidth(simpleLen);
//			}
//			partsTable.setAutoResizeMode(0);
////			} else {
////				partsTable.setAutoResizeMode(1);
////			}
//		}
//		
//		//++
//		return partsTable;
//	}
	private JLabel getJLabel(String name) {
		JLabel label = new JLabel(name);
		label.setPreferredSize(new Dimension(100, 30));
		return label;
	}

	private JLabel getJLabelDate(String name) {
		JLabel label = new JLabel(name);
		label.setPreferredSize(new Dimension(140, 30));
		return label;
	}

	// 获取数据库连接
	public static Connection getConn() {
		Connection conn = null;
		try {
			conn = DbPool.getConnection(dateConnList.get(0), dateConnList.get(1));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}

}
