package com.connor.erp.ProcessImport.ProcessAddTransferToERP;

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.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

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

import com.connor.erp.BomAddTransferToERP.BomAdd;
import com.connor.erp.BomChgTransferToERP.DBUtils;
import com.connor.erp.processresource.EquipmentAcquiredFromERP.TCPreferenceUitl;
import com.connor.erp.toolkit.HttpUtil;
import com.google.gson.Gson;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import com.sun.org.apache.xml.internal.serializer.ElemDesc;
import com.teamcenter.rac.aif.AbstractAIFDialog;
import com.teamcenter.rac.aif.AbstractAIFOperation;
import com.teamcenter.rac.aif.AbstractAIFUIApplication;
import com.teamcenter.rac.kernel.TCComponentForm;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
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 ProcessAddTransferToERPOperation extends AbstractAIFOperation{
	private final String CONNOR_TC_TO_ERP_PART_TIME = "connor_tc_to_erp_part_time";
	private String msgString;
	private AbstractAIFUIApplication app;
	private TCSession session;
	private	List<RootAddEnty> entryMap=new ArrayList<RootAddEnty>();
	private	Map bomMap=new HashMap();
	private String user_id;
	private AbstractAIFDialog dialog;
	private String erpPreference = "connor_tc_to_erp_url";
	private	PreparedStatement stmt;
	private	Connection connectionFun;
	private	ResultSet r ;
	private ResourceBundle resource = ResourceBundle.getBundle("tcUser_erpUser");
	public ProcessAddTransferToERPOperation(AbstractAIFUIApplication app,TCSession session,List<RootAddEnty> entryMap,Map bomMap,AbstractAIFDialog dialog) {
		this.app=app;
		this.session=session;
		this.entryMap=entryMap;
		this.bomMap=bomMap;
		this.dialog=dialog;
	}
	@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 e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
 					   MessageBox.post("导入超时！", "", MessageBox.INFORMATION);
 					   return;
 				   }catch(Exception e) {
 					   	
 					  MessageBox.post("导入失败！", "", MessageBox.INFORMATION);
 					   e.printStackTrace();
 				   }
 				   if (flag) {
 					   dia.setVisible(false);
 					   MessageBox.post("导入成功! 如需查询导入状态，请在“ERP集成”—“ERP任务导入记录”中查找", "发送到ERP成功", 2);
// 					   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 e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
 					   MessageBox.post("导入失败！", "", MessageBox.INFORMATION);
 				   }
 			   };
 		   },new BigDecimal(timeout));
 		   new Thread(daemon).start();
 	   }else {
 		   MessageBox.post("请联系管理员配置"+CONNOR_TC_TO_ERP_PART_TIME+"首选项","",MessageBox.INFORMATION);
 	   }
		
		
 	   	
 	   	
		
		
	}
	
	protected boolean importItemToERP()throws InterruptedException, Exception {
		// TODO Auto-generated method stub
		List<String> taskNums=new ArrayList<String>();
		String sql = "select ImpResult from connor_ERP_record where TaskNumber=?";
		
		
		Map<String, List<String>> map=new HashMap<String, List<String>>();
		for (RootAddEnty bAdd : entryMap) {
		      List<RootAddEnty> entryMap2 = new ArrayList<>();
		      entryMap2.add(bAdd);
		      bomMap.put("ROUTE", entryMap2);
		      String doPost = doPost1((Map)bomMap, "ROUTEAdd");
		      if (!this.msgString.equals("succ")) {
		        MessageBox.post(app.getDesktop().getShell(), this.msgString, "导入出现错误", 1);
		        continue;
		      } 
		      DBUtils.InsertData(bAdd.getAssembly_item(),"工艺路线", doPost, user_id, bAdd.getVersion(), this.session);
		      
		      List<String> itemMap=new ArrayList<String>();
				itemMap.add(bAdd.getAssembly_item());
				itemMap.add(bAdd.getVersion());
				map.put(doPost,itemMap);
		      
		      
//		      Object obj[] = new Object[1];
//				obj[0] = 1;
//				TCUserService service = session.getUserService();
//				service.call("openByPass", obj);
//		      TCComponentItemRevision itemRevision = DBUtils.getItemRevision(session,bAdd.getAssembly_item(),bAdd.getVersion());
//		      TCComponentForm form = (TCComponentForm) itemRevision.getRelatedComponent("IMAN_master_form_rev");
//		      form.setLogicalProperty("nhl8_ERPimpSucc", true);
//		      service.call("closeByPass", obj);
		      taskNums.add(doPost);
		    } 
		
		boolean allSucc=false;
		
		connectionFun = DBUtils.ConnectionFun(session);
		 while (!allSucc) {
      	   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);
	   			   String itemid="";
	   			   if(list.get(0).contains("GY")) {
	   				   itemid=list.get(0);
	   			   }else {
	   				   itemid=list.get(0)+"GY";
	   			   }
	   			   TCComponentItemRevision itemRevision = DBUtils.getItemRevision(session,itemid,list.get(1));
	   			   TCComponentForm form = (TCComponentForm) itemRevision.getRelatedComponent("IMAN_master_form_rev");
	   			   form.setLogicalProperty("nhl8_ERPimpSucc", 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) {
      		   allSucc=true;
      		   System.out.println("所有任务都已完成");
      	   }
	      	 
	      	 Thread.sleep(1000);
		}
		 if(r!=null) {
			 r.close();
		 }
		 if(stmt!=null) {
			 stmt.close();
		 }
		 if(connectionFun!=null) {
			 connectionFun.close();
		 }
		return true;
	}

	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();
	           }
	       }

	   }
	   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();

			}
		}
	   private String doPost1(Map<String, List> itemCheckMap, String svr) {
			// TODO Auto-generated method stub
			HashMap<String, String> preferenceHashMap = TCPreferenceUitl.getPreferenceHashMap(session, TCPreferenceService.TC_preference_site, erpPreference);
			String url = preferenceHashMap.get("url");
			String token = preferenceHashMap.get("token");
			String jsonString=new Gson().toJson(itemCheckMap);
			JSONObject itemCheckJson = JSONObject.fromObject(jsonString);
			String sid = null;
			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);
				String response = HttpUtil.doPost(url, param);  //.doGet(url+"?"+param)

				JSONObject jsonObject = JSONObject.fromObject(response);
				System.out.println("json格式==============="+jsonObject);
				msgString = jsonObject.getString("msg");
				if(jsonObject.has("cont")) {
					JSONObject jsonObject2 = jsonObject.getJSONObject("cont");
					sid = jsonObject2.getString("sid");
				}
				
				
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			return sid;
		}

}
