package com.connor.erp.BomChgTransferToERP;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.ListSelectionModel;
import javax.swing.RowSorter;
import javax.swing.SwingConstants;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

import org.apache.xalan.xsltc.compiler.util.StringStack;

import com.connor.erp.BomAddTransferToERP.AssemblyResult;
import com.connor.erp.BomAddTransferToERP.BomAddEntry;
import com.connor.erp.ProcessImport.ProcessAddTransferToERP.RootCheckResult;
import com.connor.erp.ProcessImport.ProcessAddTransferToERP.RouteLineCheck;
import com.connor.erp.processresource.EquipmentAcquiredFromERP.TCPreferenceUitl;
import com.connor.erp.toolkit.HttpUtil;
import com.connor.touliao.MessageDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentItemType;
import com.teamcenter.rac.kernel.TCComponentQuery;
import com.teamcenter.rac.kernel.TCComponentQueryType;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCPreferenceService;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;
import com.teamcenter.rac.util.VerticalLayout;
import com.teamcenter.soa.client.model.ModelObject;
import com.teamcenter.soa.client.model.ServiceData;
import com.teamcenter.soaictstubs.booleanSeq_tHolder;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class DBUtils {
	 private static String erpPreference = "connor_tc_to_erp_url";
	private static SimpleDateFormat df = new SimpleDateFormat("yyyy-M-dd HH:mm");
//	private JTree leftTree;
	
	
	
	public static String getStdOpNumber( String itemID,int num) {
		
		
		DecimalFormat df = new DecimalFormat("000");
		String newID = "010";
		// String idTemp =
		try {
			int i = 10;
			while (itemID.compareTo(newID) != 0) {
				i = i+1;
				newID = df.format(i);
			}
			newID = df.format(i+num);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return newID;
	}
	public static void main(String[] args) {
		
		String string="123\n123";
		System.out.println(string);
		
//		String bl_sequence_no = "D:\\sss";
//		
//		System.out.println(bl_sequence_no);
//		
//		bl_sequence_no = bl_sequence_no.replaceAll("\\\\", "_");
//		
//		
//		System.out.println(bl_sequence_no);
		
//		String path = "/dadw";
//		if ('/' == path.charAt(0)) {
//			path = path.substring(1);
//		}
//		System.out.println(path);
//		
//		List<String> selectedDeliveryNameList = new ArrayList<String>();
//		selectedDeliveryNameList.add("0");
//		selectedDeliveryNameList.add("1");
//		selectedDeliveryNameList.add("2");
//		boolean indexOf = selectedDeliveryNameList.contains("2");
//		System.out.println(indexOf);
//		
//		String sql = "select * from AHMC_TASK_CHECK a WHERE a.STAGE = \'%s\'";
//		String selectSql = String.format(
//				sql, "第一阶段");
//		System.out.println(selectSql);
//		List<String> list2=new ArrayList<String>(2);
//		list2.add(0, erpPreference);
//		list2.add(1, erpPreference);
//		list2.add(2, erpPreference);
//		System.out.println(list2.get(2));
//		String sqlString="Select * from xxx where 1=1, text = *编号 , name = *名称 , type = *类型,id=*id";
//		
//		String[] split = sqlString.split("where 1=1,");
//		
//		System.out.println("split"+split.toString());
//		String[] split2 = split[1].split(",");
//		
//		ArrayList<String> list=new ArrayList<String>();
//		
//		for(String string:split2) {
//			
//			String[] split3 = string.split("=");
//			if(split3[1].contains("*")) {
//				System.out.println(split3[1]);
//				list.add(split3[1]);
//			}
//			
//		}
//		
//		for(String lString:list) {
//			sqlString = sqlString.replace(lString, "?");
//		}
//		System.out.println("sql === "+sqlString);
//		
//		JDialog dialog=new JDialog();
//		
//		dialog.setPreferredSize(new Dimension(600, 400));
//		List<String> nameList=new ArrayList<String>();
//		
//		
//		
//		DefaultMutableTreeNode childNode = new DefaultMutableTreeNode("资源库");
////		DefaultMutableTreeNode childNode = new DefaultMutableTreeNode("油漆");
//		addNode(childNode,"油漆");
//		addNode(childNode,"刀具");
//		addNode(childNode,"量具");
//		addNode(childNode,"工具");
////		childNode.add(childNode);.add("油漆");
////		childNode.add("刀具");
////		childNode.add("量具");
////		childNode.add("工具");
//		
//		
//		
//		DefaultTreeModel treeModel = new DefaultTreeModel(childNode);
//		
//		JTree leftTree = new JTree();
//		leftTree.setPreferredSize(new Dimension(150, 250));
////		leftTree.setBackground(bgColor);
//		leftTree.setName("tree");
//		
//		leftTree.setModel(treeModel);
////		leftTree.setCellRenderer(new CheckBoxTreeCellRenderer());
//		leftTree.setExpandsSelectedPaths(true);
//		leftTree.setScrollsOnExpand(true);
//		
//		leftTree.addMouseListener(new MouseAdapter() {
//			@Override
//			public void mouseClicked(MouseEvent event) {
//				Object selectObj = leftTree.getLastSelectedPathComponent();
//				if (selectObj instanceof DefaultMutableTreeNode) {
//					Object userObj = ((DefaultMutableTreeNode) selectObj).getUserObject();
//					
//					System.out.println(userObj);
//				}
//				
//			}
//		});
//		JPanel totalPanel = new JPanel();
//		totalPanel.setLayout(new BorderLayout());
//		
//		JPanel designPanel = new JPanel();
//		designPanel.setLayout(new BorderLayout());
////		designPanel.add(leftTree, BorderLayout.WEST);
//		designPanel.setPreferredSize(new Dimension(600, 400));
//		totalPanel.add(designPanel,BorderLayout.CENTER);
//		totalPanel.add(leftTree, BorderLayout.WEST);
//		dialog.add(totalPanel);
////		dialog.setContentPane(designPanel);
//////		designPanel.pack();
//		JPanel southJPanel=new JPanel(); 
//		
//		JButton obButton = new JButton("确定");
//		JButton closeBtn = new JButton("取消");
//		southJPanel.add(obButton);
//		southJPanel.add(new JButton("取消"));
//		designPanel.add(southJPanel,BorderLayout.SOUTH);
//		obButton.addActionListener(new ActionListener() {
//			
//			@Override
//			public void actionPerformed(ActionEvent e) {
//				// TODO Auto-generated method stub
////				dispose();
//			}
//		});
//		closeBtn.addActionListener(new ActionListener() {
//			
//			@Override
//			public void actionPerformed(ActionEvent e) {
//				// TODO Auto-generated method stub
////				dispose();
//			}
//		});
//		
//		JPanel searchJPanel=new JPanel(); 
//		searchJPanel.setPreferredSize(new Dimension(600, 50));
//		JLabel lb_Weight = new JLabel("编号");
//		lb_Weight.setFont(new Font("微软雅黑", Font.PLAIN, 12));
//		lb_Weight.setHorizontalAlignment(SwingConstants.LEFT);
//		lb_Weight.setBounds(10, 10, 60, 20);
//		searchJPanel.add(lb_Weight);
//
////		searchJPanel.setLayout(new VerticalLayout()); 
//		JTextField	h8_Weight_text = new JTextField();
//		h8_Weight_text.setBounds(80, 10, 80, 20);
//		h8_Weight_text.setColumns(8);
//		searchJPanel.add(h8_Weight_text);
//		
//		JLabel lb_Weight1 = new JLabel("编号");
//		lb_Weight1.setFont(new Font("微软雅黑", Font.PLAIN, 12));
//		lb_Weight1.setHorizontalAlignment(SwingConstants.LEFT);
//		lb_Weight1.setBounds(10, 10, 60, 20);
//		searchJPanel.add(lb_Weight1);
//
////		searchJPanel.setLayout(new VerticalLayout()); 
//		JTextField	h8_Weight_text2 = new JTextField();
//		h8_Weight_text2.setBounds(80, 10, 80, 20);
//		h8_Weight_text2.setColumns(8);
//		searchJPanel.add(h8_Weight_text2);
//		JTable mainTable = null;
//		String[] columnNames = new String[] { "序号", "名称", "规格", "备注"};
//		designPanel.add(searchJPanel,BorderLayout.NORTH);
//		mainTable = getjTable(mainTable, null, columnNames, null);
////		mainTable.addA
//		DefaultTableModel model =(DefaultTableModel) mainTable.getModel();
//		model.addRow(new String[] {"1","2","3","4"});
//		model.addRow(new String[] {"","","",""});
//		mainTable.addKeyListener(new KeyListener() {
//			
//			@Override
//			public void keyTyped(KeyEvent e) {
//				// TODO Auto-generated method stub
//				
//			}
//			
//			@Override
//			public void keyReleased(KeyEvent e) {
//				// TODO Auto-generated method stub
//				
//			}
//			
//			@Override
//			public void keyPressed(KeyEvent e) {
//				// TODO Auto-generated method stub
//				if (e.getKeyCode() == KeyEvent.VK_V) { // Copy              
//	                System.out.println("here");
//	                
//	                Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
////	                model.get
//	        		Transferable contents = clipboard.getContents(null);
//	        		try {
//	        			
//	        			String obj = (String)  contents.getTransferData(DataFlavor.stringFlavor);
//	        			String[] split4 = obj.split("\n");
//	        			for(String string:split4) {
//	        				System.out.println(string.contains(" "));
//	        				System.out.println(string.contains(""));
//	        				System.out.println(string.contains("	"));
//	        				String[] split3 = string.split("	");
//	        				model.addRow(split3);
//	        			}
//	        			
////	        			
//	        			
//	        			
//	        			System.out.println(obj.toString().replaceAll("	", "111"));
//	        		} catch (UnsupportedFlavorException e111) {
//	        			// TODO Auto-generated catch block
//	        			e111.printStackTrace();
//	        		} catch (IOException e11) {
//	        			// TODO Auto-generated catch block
//	        			e11.printStackTrace();
//	        		}
//	            }
//			}
//		});
//		
//		designPanel.add(new JScrollPane(mainTable), BorderLayout.CENTER);
//		
//		dialog.pack();
//		dialog. validate();
////		designPanel.centerToScreen();
//		dialog.setVisible(true);
//		showDialog();
	}
	
	public static DefaultTableModel getTableModel(DefaultTableModel dtm, Object[] titleNames, Object[][] values) {
		DefaultTableModel tableModel = null;
		if (dtm == null) {
			tableModel = new DefaultTableModel(values, titleNames) {
				@Override
				public boolean isCellEditable(int row, int column) {
					return false;
				}
			};
		}

		return tableModel;
	}
	
	
	
	
	public static JTable getjTable(JTable partsTable, DefaultTableModel dtm, Object[] titleNames, Object[][] values) {
		int simpleLen = 100;
		int totleLen = 1000;
		if (partsTable == null) {
			partsTable = new JTable(getTableModel(dtm, titleNames, values));
			partsTable.setRowHeight(20);
			RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(partsTable.getModel());
			partsTable.setRowSorter(sorter);
			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 static void addNode(DefaultMutableTreeNode childNode, String string) {
		// TODO Auto-generated method stub
	DefaultMutableTreeNode node1 = new DefaultMutableTreeNode(string);
	childNode.add(node1);
}
	//	 public static void showDialog() {
//		    pack();
//		    validate();
//		    centerToScreen();
//		    setVisible(true);
//		  }
	public static File saveExcelChooser(String defaultFile,String item_id) {
		File dir = null;
		JFileChooser chooser = new JFileChooser();
		chooser.setAcceptAllFileFilterUsed(false);
//		File currentDir = FileSystemView.getFileSystemView().getDefaultDirectory();
		File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
		chooser.setCurrentDirectory(desktopDir);
		chooser.setSelectedFile(new File(defaultFile));
		String saveType[] = { "xlsx" };
		chooser.setFileFilter(new FileNameExtensionFilter("Excel工作簿", saveType));
		int returnVal = chooser.showSaveDialog(new Frame());
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			
			dir = chooser.getSelectedFile();
			String path = dir.getPath();
			String substring = path.substring(path.lastIndexOf("\\"));
			substring=item_id+substring;
			path=dir.getParent()+File.separator+substring.replace("\\", "_");
			System.out.println(path);
			if(!path.toLowerCase().endsWith(".xlsx")) {
				path += ".xlsx";
				dir = new File(path);
			}
			if(dir.exists())
				dir.delete();
//			System.out.println("saveExcelChooser1:" + dir.getPath());
		}
		return dir;
	}
	public static List<UserList> doPost(Map<String, String> itemCheckMap,TCSession session) {
		HashMap<String, String> preferenceHashMap = TCPreferenceUitl.getPreferenceHashMap(session, TCPreferenceService.TC_preference_site, erpPreference);
		String url = preferenceHashMap.get("url");
		String token = preferenceHashMap.get("token");
		JSONObject itemCheckJson = JSONObject.fromObject(itemCheckMap);
		String svr="TcERPUserMap";
		try {
			System.out.println("开始发送请求");
			String args = itemCheckJson.toString();
			System.out.println(args);
			token = URLEncoder.encode(token,"UTF-8");
			svr = URLEncoder.encode(svr,"UTF-8");
			args = URLEncoder.encode(args,"UTF-8");
			String param = "usr="+token+"&svr="+svr+"&args="+args;
			
			System.out.println("url=============="+url);
			System.out.println("param==========="+args + "svr"+svr);
			String response = HttpUtil.doPost(url,param);
			JSONObject jsonObject = JSONObject.fromObject(response);
			
			System.out.println("json格式==============="+jsonObject);
			
			if(jsonObject.has("cont")) {
				JSONObject jsonObject2 = jsonObject.getJSONObject("cont");
				
				if(jsonObject2.has("TC_ERP_USER")) {
					JSONArray jsonObject3 = jsonObject2.getJSONArray("TC_ERP_USER");
					List<UserList> list = JSONArray.toList(jsonObject3,UserList.class);
					if (list.size()==0) {
						MessageBox.post("“此TC账号未关联ERP账号，请联系管理员处理”","提示",MessageBox.INFORMATION);
					}
					return list;
				}
			}
			
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return null;
	}
	
	public static boolean isEmpty(String str) {
		return str == null || "".equals(str.trim());
	}
	public static String getText(TCSession session, String str) throws Exception {
		if (isEmpty(str)) {
			return str;
		} else {
			String res = session.getTextService().getTextValue(str);
			return !isEmpty(res) ? res : str;
		}
	}
	public static int getLen(Object[] arr) {
		return arr == null ? 0 : arr.length;
	}
	
	public static TCComponent[] query(TCSession session, String queryName, String[] keys, String[] vals)
			throws Exception {
		System.out.println("Query: " + queryName);
		System.out.println("keys = " + Arrays.toString(keys));
		System.out.println("vals = " + Arrays.toString(vals));
		TCComponentQueryType queryType = (TCComponentQueryType) session.getTypeComponent("ImanQuery");
		TCComponentQuery query = (TCComponentQuery) queryType.find(queryName);
		if (query == null) {
			System.out.println("null"+queryName);
		} else {
			query.clearCache();
			query.refresh();
			return query.execute(keys, vals);
		}
		return null;
	}
	
	public static TCComponentItemRevision getItemRevision(TCSession session, String itemId,String itemRevId) throws Exception {
		System.out.println("Search Revision: " + itemId+itemRevId);
		if (isEmpty(itemId) || isEmpty(itemRevId)) {
			return null;
		} else {
			String queryName = "Item Revision...";
			String[] keys = new String[]{getText(session, "ItemID"),getText(session, "Revision")};
			String[] vals = new String[]{itemId,itemRevId};
			TCComponent[] res = query(session, queryName, keys, vals);
			int len = getLen(res);
			if (len == 0) {
				return null;
			} else if (len > 1) {
				System.out.println("找到了多个rev");
			} else {
				return (TCComponentItemRevision) res[0];
			}
		}
		return null;
	}
	
	public static void InsertData(String itemId,String taskType,String taskNumber,String userName,String item_rev,TCSession session) {
		PreparedStatement stmt = null;
		Connection con =null;
		String sql = "insert into  connor_ERP_record (ItemId,TaskType,TaskNumber,ImpDate,UserName,Rev_Id) values(?,?,?,to_date(?,'yyyy-fmmm-dd hh24:mi'),?,?)";//
		try {
			con = ConnectionFun(session);
			stmt = con.prepareStatement(sql);
			stmt.setString(1, itemId);
			stmt.setString(2, taskType);
			stmt.setString(3, taskNumber);
//			Date javaDate = null;
//			try {
//				javaDate = df.parse(impDate);
//			} catch (ParseException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			java.sql.Date sqlDate = new java.sql.Date(javaDate.getTime());
			stmt.setString(4, df.format(new Date()));
			stmt.setString(5, userName);
			stmt.setString(6, item_rev);
			stmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				stmt.close();
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	public static Connection ConnectionFun(TCSession session) throws SQLException {
		String[] stringArray = session.getPreferenceService().getStringValues("connor_oracle_connection");
		
		String url = "jdbc:oracle:thin:@" + stringArray[0];//
		
		String oracleUser = stringArray[1];//
		
		String password = stringArray[2];//
		
		Connection conn = null;//

		try {
			System.out.println(url);
			System.out.println(oracleUser);
			System.out.println(password);
			Class.forName("oracle.jdbc.driver.OracleDriver");
			System.out.println("驱动加载成功");
		} catch (ClassNotFoundException e) {
			System.out.println("驱动加载失败");
		}

		conn = DriverManager.getConnection(url, oracleUser, password);

		System.out.println("数据库连接成功");
		return conn;

	}
}
