package com.connor.erp.ItemAddTransferSendToERP;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Label;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ResourceBundle;

import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTable;
import javax.swing.SwingConstants;

import com.connor.erp.BomChgTransferToERP.DBUtils;
import com.connor.erp.BomChgTransferToERP.UserList;
import com.connor.erp.processresource.EquipmentAcquiredFromERP.TCPreferenceUitl;
import com.connor.erp.toolkit.HttpUtil;
//import com.sun.corba.se.impl.encoding.EncapsOutputStream;
import com.teamcenter.rac.aif.AbstractAIFDialog;
import com.teamcenter.rac.aif.AbstractAIFOperation;
import com.teamcenter.rac.aif.AbstractAIFUIApplication;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentForm;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
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 net.sf.json.JSONObject;

public class SendToERPOperation extends AbstractAIFOperation{
	private AbstractAIFUIApplication app;
	private TCSession session;
	private ResourceBundle resource = ResourceBundle.getBundle("tcUser_erpUser");
	private String errInfo = "";
	private JTable table;
	private AbstractAIFDialog dialog;
	private final String CONNOR_ORACLE_CONNECTION = "connor_oracle_connection";
	private final String CONNOR_TC_TO_ERP_PART_TIME = "connor_tc_to_erp_part_time";
	private SimpleDateFormat df = new SimpleDateFormat("yyyy-M-dd HH:mm");
	private String user_id;
	private List<String> item_id = new ArrayList<String>();
	private String itemAddSvr = "ITEMAdd";
	private List<String> Info = new ArrayList<String>();
	private String erpPreference = "connor_tc_to_erp_url";
	private List<TCComponentItemRevision> ItemRevision;
	   
	
	private	PreparedStatement stmt;
	private	Connection connectionFun;
	private	ResultSet r ;
	
	public SendToERPOperation(AbstractAIFUIApplication app, TCSession session, JTable table, AbstractAIFDialog dialog, List<String> item_id, List<String> Info, List<TCComponentItemRevision> ItemRevision) {
		this.app = app;
		this.session = session;
		this.table = table;
		this.dialog = dialog;
		this.item_id = item_id;
		this.Info = Info;
		this.ItemRevision = ItemRevision;
	}
	
	
	@Override
	public void executeOperation() throws Exception {
		// TODO Auto-generated method stub
		user_id = session.getUser().getProperty("user_id");
		String timeout = session.getPreferenceService().getStringValue(CONNOR_TC_TO_ERP_PART_TIME);
 	   if(timeout!=null&&timeout.length()>0) {
 		   System.out.println("超时时间为"+timeout+"秒！");
 		   Daemon daemon = new Daemon(new Thread() {
 			   public void run() {
 				   WaitingDialog dia = new WaitingDialog(app.getDesktop(), "INFOMATION", "正在导入ERP...");
 				   dia.setAlwaysOnTop(true);//设置在窗口最前端
 				   dia.setVisible(true);
 				   boolean flag = false;
 				   try {
 					   flag = importItemToERP();
 					   
 				   }catch (InterruptedException e) {
 					   // TODO Auto-generated catch block
//						e.printStackTrace();
 					  
 					   dia.setVisible(false);
 					   try {
 						  if(r!=null) {
 							 r.close();
 						 }
 						 if(stmt!=null) {
 							 stmt.close();
 						 }
 						 if(connectionFun!=null) {
 							 connectionFun.close();
 						 }
 						} catch (SQLException ee) {
 							// TODO Auto-generated catch block
 							ee.printStackTrace();
 						}
 					  
 					   MessageBox.post("导入超时！", "", MessageBox.INFORMATION);
 					  dialog.dispose();
 					   return;
 				   }catch(Exception e) {
 					   e.printStackTrace();
 					  dialog.dispose();
 				   }
 				   if (flag) {
 					   dia.setVisible(false);
 					   MessageBox.post("导入成功！", "", MessageBox.INFORMATION);
 				   } else {
 					   dia.setVisible(false);
 					   try {
 						  if(r!=null) {
 							 r.close();
 						 }
 						 if(stmt!=null) {
 							 stmt.close();
 						 }
 						 if(connectionFun!=null) {
 							 connectionFun.close();
 						 }
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
 					   
 					   MessageBox.post(errInfo+"导入失败！", "", MessageBox.INFORMATION);
 				   }
 			   };
 		   },new BigDecimal(timeout));
 		   new Thread(daemon).start();
 	   }else {
 		   MessageBox.post("请联系管理员配置"+CONNOR_TC_TO_ERP_PART_TIME+"首选项","",MessageBox.INFORMATION);
 	   }
 	   
 	   	
	}
	
	   private boolean importItemToERP() throws InterruptedException, Exception {
		   
		   Map<String, String> userMap=new HashMap<String, String>();
			userMap.put("TCUser", user_id);
			List<UserList> doPost = DBUtils.doPost(userMap, session);
			UserList userList = doPost.get(0);
		   
		   Map<String, Object> itemAddMap = new HashMap<String, Object>();
		   List<Map<String, Object>> itemAddList = new ArrayList<Map<String,Object>>();
		   Map<String, Boolean> orgMap = new HashMap<String, Boolean>();
//		   Map<String,TCComponentItem> totalItems = new HashMap<String, TCComponentItem>();
//		   Map<String,TCComponentItem> notImportItems = new HashMap<String, TCComponentItem>();
		   
//		   if(resource.containsKey(user_id)) {
//			   itemAddMap.put("creater", resource.getString(user_id));
//		   }else {
		   itemAddMap.put("creater", userList.getERP_USER_CODE());
//		   }
		   
		   
		   int itemCount =  item_id.size();
		   ArrayList<Integer> partTranNums = new ArrayList<Integer>();
		   int Info_i = 0;
//	             List<String> revIds = new ArrayList<String>();
		   for (int i = 0; i < itemCount; i++) {
			   Thread.sleep(1);
			   Map<String, Object> itemAddMap2 = new HashMap<String, Object>();
			   Boolean Nhl8_IfToERP_value = (Boolean) table.getValueAt(i, 0);
			   String nhl8_wlzt_value = (String) table.getValueAt(i, 7);
			   String item_id_value = (String) table.getValueAt(i, 1);
			   String object_name_value = (String) table.getValueAt(i, 2);
			   String nhl8_uom_tag_value = (String) table.getValueAt(i, 3);
			   Boolean isSCZZ = (Boolean) table.getValueAt(i, 4);
			   Boolean isBJZZ = (Boolean) table.getValueAt(i, 5);
			   Boolean isFSCZZ = (Boolean) table.getValueAt(i, 6);
			   Boolean isZZZ = false;
			   String nhl8_templateID_value = (String) table.getValueAt(i, 9);
			   String nhl8_MaxType_value = (String) table.getValueAt(i, 10);
			   String nhl8_MinType_value = (String) table.getValueAt(i, 11);
			   if (Nhl8_IfToERP_value.booleanValue()) {
				   Info_i++;
				   partTranNums.add(Integer.valueOf(i));
				   StringBuffer org_Info = new StringBuffer();
				   if (((String) Info.get(Info_i)).charAt(0) == '1') {
					   org_Info.append('0');
				   } else {
					   org_Info.append('1');
				   } 
				   if(org_Info.toString().equals("0")) {
					   isZZZ = false;
				   }else {
					   isZZZ = true;
				   }
				   
				   orgMap.put("NHL", isZZZ);
				   orgMap.put("NSC", isSCZZ);
				   orgMap.put("NBJ", isBJZZ);
				   orgMap.put("NSJ", isFSCZZ);
				   try {
//						revIds.add(ItemRevision.get(i).getStringProperty("item_revision_id"));
					   itemAddMap2.put("item", item_id_value);
					   itemAddMap2.put("version",ItemRevision.get(i).getStringProperty("item_revision_id"));
					   itemAddMap2.put("description", object_name_value);
					   itemAddMap2.put("uom", nhl8_uom_tag_value);
					   itemAddMap2.put("template_id", nhl8_templateID_value);
					   itemAddMap2.put("primary_category", nhl8_MaxType_value);
					   itemAddMap2.put("secondary_category", nhl8_MinType_value);
					   itemAddMap2.put("org", orgMap);
					   itemAddMap2.put("po_leadtime", null);
					   itemAddMap2.put("minimum_order_quantity", null);
					   itemAddMap2.put("maximum_order_quantity", null);
					   itemAddMap2.put("minimum_packing_quantity", null);
					   itemAddMap2.put("planner_code", null);
					   itemAddList.add(itemAddMap2);
				   } catch (TCException e1) {
					   // TODO Auto-generated catch block
					   e1.printStackTrace();
				   }
			   } 
		   } 
		   Map<String, List<String>> map=new HashMap<String, List<String>>();
		   List<String> taskNums=new ArrayList<String>();
		   for(Map<String,Object> m:itemAddList) {
			   
			   List<Map<String,Object>> tempList = new ArrayList<Map<String,Object>>();
			   tempList.add(m);
			   itemAddMap.put("items", tempList);
			   final StringBuffer task_num = new StringBuffer();
			   task_num.append(doGet(itemAddMap, itemAddSvr));
			   try {
				   Object obj[] = new Object[1];
				   obj[0] = 1;
				   TCUserService service = session.getUserService();
				   service.call("openByPass", obj);
				   String itemId = m.get("item").toString();
				   TCComponent[] item = session.search("零组件 ID", new String[] {"零组件 ID"}, new String[] {itemId});
				   if(item!=null&&item.length>0) {
					   String revId = m.get("version").toString();
					   System.out.println("插入数据库,任务号为："+task_num.toString());
					   InsertData(itemId, "基础物料", task_num.toString(), df.format(new Date()), user_id, revId);
					   taskNums.add(task_num.toString());
					   
					   List<String> itemMap=new ArrayList<String>();
		               itemMap.add(itemId);
		               itemMap.add(revId);
		               map.put(task_num.toString(),itemMap);
					   
					   
////					   totalItems.put(revId,(TCComponentItem) item[0]);
//					   //反写添加成功属性
//					   TCComponentItem ite = (TCComponentItem)item[0];
//					   TCComponentItemRevision rev = ite.getLatestItemRevision();
//					   TCComponentForm form = (TCComponentForm) rev.getRelatedComponent("IMAN_master_form_rev");
//					   System.out.println("反写"+rev+"属性nhl8_ItemimpSucc值为true");
//					   form.setLogicalProperty("nhl8_ItemimpSucc", true);
				   }
				   service.call("closeByPass", obj);
			   } catch (Exception e1) {
				   // TODO Auto-generated catch block
				   e1.printStackTrace();
			   }
			   Thread.sleep(1);
		   }
		   String sql = "select ImpResult from connor_ERP_record where TaskNumber =?";
		   
		   
//		   notImportItems = new HashMap<String, TCComponentItem>(totalItems);
		   boolean isAllSucc = false;
		   //循环检查表单属性
		   connectionFun = DBUtils.ConnectionFun(session);
		   while(!isAllSucc) {
			   for(int i=0;i<taskNums.size();i++) {
				   
	       		   stmt = connectionFun.prepareStatement(sql);
	       		   stmt.setObject(1, taskNums.get(i));
	       		   String impResult="";
	       		   r = stmt.executeQuery();
	       		   while (r.next()) {
	      			   impResult = r.getString(1);
	      			   System.out.println("impResult"+impResult+"sid"+taskNums.get(i)+r.getObject(1));
	       		   }
	       		if(r!=null) {
					 r.close();
				 }
		       	 if(stmt!=null) {
					 stmt.close();
				 }
	      		   if(impResult==null || impResult.equals("")) {
	      			   continue;
	      		   }
	      		   else if(impResult.equals("成功")) {
	      			   System.out.println("已完成："+taskNums.get(i));
	      			   
	      			   List<String> list = map.get(taskNums.get(i));
		   			   Object obj[] = new Object[1];
		   			   obj[0] = 1;
		   			   TCUserService service = session.getUserService();
		   			   service.call("openByPass", obj);
		   			   TCComponentItemRevision itemRevision = DBUtils.getItemRevision(session,list.get(0),list.get(1));
		   			   TCComponentForm form = (TCComponentForm) itemRevision.getRelatedComponent("IMAN_master_form_rev");
		   			   form.setLogicalProperty("nhl8_ItemimpSucc", true);
		   			   System.out.println("回填属性itemid"+list.get(0)+"rev"+list.get(1));
		   			   service.call("closeByPass", obj);
	      			   
	      			   taskNums.remove(i);
	      			   i--;
	      		   }else if(impResult.contains("失败") || impResult.equals("任务id无效")){
	      			   return false;
	      		   }
	       	   }
	       	   if(taskNums.size()==0) {
	       		   isAllSucc=true;
	       		   System.out.println("所有任务都已完成");
	       	   }
		      
			   Thread.sleep(1000);
		   }
		   if(r!=null) {
				 r.close();
			 }
			 if(stmt!=null) {
				 stmt.close();
			 }
			 if(connectionFun!=null) {
				 connectionFun.close();
			 }
		   dialog.dispose();
		   return true;
	   }
	
	   private String doGet(Map<String, Object> itemCheckMap, String svr) {
			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 sid = null;
			try {
				System.out.println("开始发送请求");
				   String args = itemCheckJson.toString();
					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==========="+param);
				   String response = HttpUtil.doPost(url, param); //.doGet(url+"?"+param)
				   System.out.println("请求结果================"+response);
				
				JSONObject jsonObject = JSONObject.fromObject(response);
				System.out.println("json格式==============="+jsonObject);
				if(jsonObject.has("cont")) {
					JSONObject jsonObject2 = jsonObject.getJSONObject("cont");
					System.out.println("cont==============="+jsonObject2);
					
					sid = jsonObject2.getString("sid");
					
				}
				
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			return sid;
		}
	   
	public void InsertData(String itemId,String taskType,String taskNumber,String impDate,String userName,String revID) {
		Connection con = null;
		PreparedStatement stmt = 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();
			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, impDate);
			stmt.setString(5, userName);
			stmt.setString(6, revID);
			stmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				stmt.close();
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	public Connection ConnectionFun() 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;

	}
	
	class WaitingDialog extends com.teamcenter.rac.aif.AbstractAIFDialog {
		private static final long serialVersionUID = 1L;
		public JPanel panel;
		JProgressBar progressBar = null;

		public WaitingDialog(Frame arg0, String title, String message) {
			super(arg0, title);
			this.setModal(false);

			panel = new JPanel(new BorderLayout());

			/*
			 * JLabel label = new JLabel(message); System.out.println("message:"+message);
			 * System.out.println("label:"+label); panel.add(label);
			 */

			progressBar = new JProgressBar(SwingConstants.HORIZONTAL);
			progressBar.setVisible(true);
			progressBar.setIndeterminate(true);

			panel.add(BorderLayout.CENTER, new Label(message));
			panel.add(BorderLayout.SOUTH, progressBar);

			panel.setPreferredSize(new Dimension(350, 60));

			this.getContentPane().add(panel);

			centerToScreen();

			pack();

		}
	}
   
   class Daemon implements Runnable {
       private Thread thread;
       private BigDecimal time;

       public Daemon(Thread r, BigDecimal t) {
           thread = r;
           time = t;
       }

       @Override
       public void run() {
    	   this.thread.start();
           while (true) {
               try {
                   Thread.sleep(time.multiply(new BigDecimal("1000")).longValue());
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
               thread.interrupt();
           }
       }

   }

}
