package com.langtech.plm.form;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.ComboBoxEditor;
import javax.swing.DefaultButtonModel;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;

import org.jdesktop.swingx.renderer.DefaultTableRenderer;
import org.jdesktop.swingx.renderer.FormatStringValue;
import org.jdesktop.swingx.renderer.StringValue;
import org.jdesktop.swingx.table.DatePickerCellEditor;


import com.teamcenter.rac.kernel.TCComponentForm;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCFormProperty;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.stylesheet.AbstractRendering;
import com.teamcenter.rac.util.MessageBox;

@SuppressWarnings("deprecation")
public class LD6_NewProdForm extends AbstractRendering {
	private static ArrayList<String> dateConnList = new ArrayList<String>();
	protected DefaultTableModel tm_part;
	protected JTable t_part;
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	public static final String[] HEADER = new String[] { "序号", "新品任务项", "分派人", "新品任务要求描述", "处理人", "岗位组", "任务性质", "难易程度",
			"紧急程度", "额定业务工时/小时", "实际业务工时/小时", "要求完成时间", "实际完成时间", "备注" };
	public static final int[] HEADERWIDTH = new int[] { 40, 60, 120, 100, 60, 60, 60, 60, 100, 100, 100, 120, 120,
			120 };

	private static final long serialVersionUID = 1L;
	private static Date refreshDate = null;
	private TCSession session;
	private Hashtable<TCFormProperty, JComponent> indices;
	TCComponentForm tcForm;
	private List<Component> allComponents = new ArrayList<Component>();
	private TCComponentForm arg0;
	private String[] assignee;//分配人首选项分割
	JButton jComboBox_fpr = new JButton();
	public LD6_NewProdForm(TCComponentForm arg0) throws Exception {
		super(arg0);
		this.arg0 = arg0;
		Date currDate = new Date();
		if (refreshDate == null) {
			arg0.refresh();
			refreshDate = currDate;
		} else {
			long diff = currDate.getTime() - refreshDate.getTime();
			long minutes = diff / 1000 / 60;
			if (minutes >= 1) {
				arg0.refresh();
				refreshDate = currDate;
			}
		}

		this.session = null;
		this.session = arg0.getSession();
		this.tcForm = arg0;
		indices = new Hashtable<TCFormProperty, JComponent>();

		initializeUI();
		loadRendering();

	}

	private void initializeUI() {
		try {
			//获取分派人首选项
			String[] form_defoult_value = session.getPreferenceService().getStringValues("LD6_NewProdForm_defoult_value");
			assignee = form_defoult_value[1].split("-");//分派人
			setLayout(new BorderLayout());
			setBackground(new JLabel("").getBackground());
			JTabbedPane tabPane = new JTabbedPane();
			tabPane.addTab("表单", getProjectManInfoPanel());
			add(BorderLayout.WEST, new JLabel(" "));
			add(BorderLayout.CENTER, tabPane);
			add(BorderLayout.EAST, new JLabel(" "));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private JScrollPane getProjectManInfoPanel() {

		JScrollPane returnPanel = new JScrollPane();
		returnPanel.setViewportView(getTablePanel());
		return returnPanel;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void loadRendering() throws TCException {
		System.out.println("loadForm------------------------start");
		
		
		
		// 查数据库渲染table
		String formUid = arg0.getUid();

		String[] value2 = session.getPreferenceService().getStringValues("LD_dbinfo2");

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

		Connection conn = getConn();
		// MES:写入数据库
		String selectSql = "SELECT * FROM LD6_NewProdForm_VALUES WHERE FormUid = ?";
		System.out.println(selectSql);

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

			// 执行插入语句
			stmt.setString(1, formUid);
			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);
				lists.add(ld6_NewProdForm_Bean);
			}

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

		// 表里lists
		for (int i = 0; i < lists.size(); i++) {
			LD6_NewProdForm_Bean ld6_NewProdForm_Bean = lists.get(i);

			tm_part.addRow(new Object[] { i + 1, ld6_NewProdForm_Bean.getNewProductTaskItem(),
					ld6_NewProdForm_Bean.getAssignee(), ld6_NewProdForm_Bean.getNewProductTaskDescription(),
					ld6_NewProdForm_Bean.getProcessor(), ld6_NewProdForm_Bean.getPositionGroup(),
					ld6_NewProdForm_Bean.getTaskNature(), ld6_NewProdForm_Bean.getDifficultyLevel(),
					ld6_NewProdForm_Bean.getUrgencyLevelCode(), ld6_NewProdForm_Bean.getEstimatedBusinessHours(),
					ld6_NewProdForm_Bean.getActualBusinessHours(), ld6_NewProdForm_Bean.getDueDate(),
					ld6_NewProdForm_Bean.getCompletionDate(), ld6_NewProdForm_Bean.getRemarks() });

		}
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.teamcenter.rac.form.AbstractTCForm#saveForm()
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void saveRendering() {
		System.out.println("触发保存");
		// 数据保存到数据库
		Connection conn = getConn();
		// MES:写入数据库
		String updateSql = "UPDATE LD6_NewProdForm_VALUES SET NewProductTaskItem = ?,Assignee = ?,NewProductTaskDescription = ?,Processor = ?,PositionGroup = ?,TaskNature = ?,DifficultyLevel = ?,UrgencyLevelCode = ?,EstimatedBusinessHours = ?,ActualBusinessHours = ?,DueDate = ?,Remarks = ? WHERE FormUid = ? AND NewProductTaskItem = ?";

		for (int j = 0; j < t_part.getRowCount(); j++) {
			// 添加表单数据到数据库
			try (PreparedStatement stmt = conn.prepareStatement(updateSql)) {
				stmt.setString(1, (String) t_part.getValueAt(j, 1));
				stmt.setString(2, (String) t_part.getValueAt(j, 2));
				stmt.setString(3, (String) t_part.getValueAt(j, 3));
				stmt.setString(4, (String) t_part.getValueAt(j, 4));
				stmt.setString(5, (String) t_part.getValueAt(j, 5));
				stmt.setString(6, (String) t_part.getValueAt(j, 6));
				stmt.setString(7, (String) t_part.getValueAt(j, 7));
				stmt.setString(8, (String) t_part.getValueAt(j, 8));
				stmt.setString(9, (String) t_part.getValueAt(j, 9));
				stmt.setString(10, (String) t_part.getValueAt(j, 10));

				//java.util.date 转成Java.sql.date
				java.sql.Date date = new java.sql.Date(((java.util.Date)t_part.getValueAt(j, 11)).getTime());
				
				stmt.setDate(11, date);
				//stmt.setDate(12, new java.sql.Date(10000000));
				stmt.setString(12, (String) t_part.getValueAt(j, 13));
				stmt.setString(13, arg0.getUid());
				stmt.setString(14, (String) t_part.getValueAt(j, 1));
				// 执行插入语句
				stmt.executeUpdate();
				System.out.println("保存成功");
			} catch (SQLException e1) {
				e1.printStackTrace();
			}

		}

	}

	private JPanel getTablePanel() {
		JPanel panel = new JPanel(new BorderLayout());
		tm_part = new DefaultTableModel();
		t_part = new JTable(tm_part) {
			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			@Override
			public boolean isCellEditable(int row, int column) {
				if (column == 2 || column == 0 || column == 1 || column == 5 || column == 12) {// 不可编辑的列
					return false;
				}
//				else if(column == 2) {
//					
//						if(assignee[row].contains("、")) {
//							return true;
//						}else {
//							return false;
//						}
//					
//				}
				else {
					return true;
				}
				
				
			}


		};
		tm_part.setDataVector(null, HEADER);
		t_part.getTableHeader().setReorderingAllowed(false); // 设置列不可移动，否则会发生类型转换错误（第三列）
		this.t_part.setRowHeight(23);

		TableColumnModel colModel = this.t_part.getColumnModel();
		int colCnt = HEADERWIDTH.length;
		colModel.getColumn(0).setMaxWidth(HEADERWIDTH[0]);
		for (int i = 0; i < colCnt; i++) {
			colModel.getColumn(i).setPreferredWidth(HEADERWIDTH[i]);
		}
		// 获取首选项值
		String[] ld_taskNature = session.getPreferenceService().getStringValues("ld_taskNature");// 任务性质
		String[] ld_taskDifficulty = session.getPreferenceService().getStringValues("ld_taskDifficulty");// 难易程度
		String[] ld_urgency = session.getPreferenceService().getStringValues("ld_urgency");// 紧急程度

		Map<String, Double> ld_taskNatureMap = new HashMap<String, Double>();
		Map<String, Double> ld_taskDifficultyMap = new HashMap<String, Double>();
		Map<String, Double> ld_urgencyMap = new HashMap<String, Double>();

		// 塞下拉框值

		JComboBox<String> jComboBox1 = new JComboBox<String>();
		JComboBox<String> jComboBox2 = new JComboBox<String>();
		JComboBox<String> jComboBox3 = new JComboBox<String>();
		for (int i = 0; i < ld_taskNature.length; i++) {
			String[] split = ld_taskNature[i].split("=");
			ld_taskNatureMap.put(split[0], Double.parseDouble(split[1]));
			jComboBox1.addItem(split[0]);
		}

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

		for (int i = 0; i < ld_urgency.length; i++) {
			String[] split = ld_urgency[i].split("=");
			ld_urgencyMap.put(split[0], Double.parseDouble(split[1]));
			jComboBox3.addItem(split[0]);
		}

//		JButtonEditor buttonEditor = new JButtonEditor("Button Text", new ActionListener() {
//		    @Override
//		    public void actionPerformed(ActionEvent e) {
//		        // 在这里处理按钮点击事件
//		  
//		    }
//		});

		//t_part.getColumnModel().getColumn(2).setCellEditor(buttonEditor);
		t_part.getColumnModel().getColumn(6).setCellEditor(new DefaultCellEditor(jComboBox1));
		t_part.getColumnModel().getColumn(7).setCellEditor(new DefaultCellEditor(jComboBox2));
		t_part.getColumnModel().getColumn(8).setCellEditor(new DefaultCellEditor(jComboBox3));
		
		
//		jComboBox_fpr.addActionListener(new ActionListener() {
//            @Override
//            public void actionPerformed(ActionEvent e) {
//                if (((String) jComboBox_fpr.getSelectedItem()).isEmpty()) {
//                    // 恢复上一次的选择
//                	
//                	jComboBox_fpr.setSelectedIndex(jComboBox_fpr.getSelectedIndex() - 1);
//                }
//            }
//        });
		
		StringValue sv = new FormatStringValue(sdf);
		TableCellRenderer r = new DefaultTableRenderer(sv);
		t_part.getColumnModel().getColumn(11).setCellEditor(new DatePickerCellEditor(sdf));
		t_part.getColumnModel().getColumn(11).setCellRenderer(r);
		

		 // 添加鼠标监听器
		t_part.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2 && t_part.columnAtPoint(e.getPoint()) == 2) { // 判断是否双击并且是在第二列
                    int row = t_part.rowAtPoint(e.getPoint());
                    int column = t_part.columnAtPoint(e.getPoint());
                    if (column == 2) {
                        // 获取被双击的单元格的数据
                        String value = (String) t_part.getModel().getValueAt(row, column);
                        // 在这里处理双击事件
                        System.out.println("Double-clicked on cell: Row=" + row + ", Column=" + column + ", Value=" + value);
                        // 这里可以添加更多的逻辑来处理双击事件
                        String string = assignee[row];
                        if(string.contains("、")) {
                        	String[] split = string.split("、");
                        	 new ChooseDialog(split,row,column,tm_part);
                        }
                       
                    }
                }
            }
        });

		//添加处理人监听
		tm_part.addTableModelListener(new TableModelListener() {
	            @Override
	            public void tableChanged(TableModelEvent e) {
	                if (e.getType() == TableModelEvent.UPDATE) {
	                    int row = e.getFirstRow();
	                    int column = e.getColumn();
	                    
	                    if(column == 4) {
	                    	String value = (String)tm_part.getValueAt(row, column);
		                    System.out.println("Cell changed at row " + row + ", column " + column + ": new value = " + value);
		                    String[] split = value.split("-");
		                    if(split.length == 2) {
		                    	  tm_part.setValueAt(split[1], row, column+1);
		                    }else {
		                    	MessageBox.post("请按规定的格式:“处理人-岗位组”填写", "提示", 2);
		                    }
		                  
	                    }
	                }
	            }
	        });
	
		this.t_part.getTableHeader().setBackground(Color.blue);
		
	
		

		
		

		JScrollPane scroll = new JScrollPane(t_part);
		panel.add(BorderLayout.CENTER, scroll);


		panel.setBorder(BorderFactory.createLoweredBevelBorder());
		return panel;
	}

	// 获取数据库连接
	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;
	}

	

	
	
//	class CustomCellEditor extends DefaultCellEditor {
//	    private JComboBox comboBox;
//	    
//	    public CustomCellEditor(JComboBox comboBox) {
//	        super(comboBox);
//	        this.comboBox = comboBox;
//	        comboBox.addMouseListener(new MouseAdapter() {
//	            @Override
//	            public void mouseClicked(MouseEvent e) {
////					// 得到选中的行列的索引值
//					int r = t_part.getSelectedRow();
//					int c = t_part.getSelectedColumn();
//					if(c == 2) {
//	
//						
//						if(assignee[r].contains("、")) {
//							String[] split = assignee[r].split("、");
//							jComboBox_fpr.removeAllItems();
//							for (int i = 0; i < split.length; i++) {
//								jComboBox_fpr.addItem(split[i]);
//							}
//							//t_part.getColumnModel().getColumn(2).setCellEditor(new CustomCellEditor(tempCom));
//						}else {
//							//JComboBox<String> tempCom = new JComboBox<String>();
//							jComboBox_fpr.removeAllItems();
//							jComboBox_fpr.addItem(assignee[r]);
//							//t_part.getColumnModel().getColumn(2).setCellEditor(new CustomCellEditor(tempCom));
//						}
//
//					}
//	            }
//	        });
//	    }
//
//	}
	
	

}
