package com.connor.erp.toolkit;
 
// import com.connor.erp.BomAddTransferToERP.BomAddImportXMLReader;
 import com.connor.erp.BomChgTransferToERP.BomChgImportXMLReader;
 import com.connor.erp.BomImport.BomTransferCommand;
 import com.connor.erp.ItemAddTransferSendToERP.SendToERPCommand;
 import com.connor.erp.ItemImport.ItemImportXMLReader;
 import com.connor.erp.ProcessImport.ValidateFailDialog;
import com.connor.erp.processresource.EquipmentAcquiredFromERP.TCPreferenceUitl;
import com.connor.erpintegration.entity.BomCheckResult;
import com.connor.erpintegration.entity.CheckResult;
// import com.connor.tcerp.conn.PlmErpIntegration;
 import com.teamcenter.rac.aif.AbstractAIFCommand;
 import com.teamcenter.rac.aif.AbstractAIFUIApplication;
 import com.teamcenter.rac.aif.kernel.AIFComponentContext;
 import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
 import com.teamcenter.rac.kernel.TCComponent;
 import com.teamcenter.rac.kernel.TCComponentBOMLine;
 import com.teamcenter.rac.kernel.TCComponentBOMViewRevision;
 import com.teamcenter.rac.kernel.TCComponentBOMWindow;
 import com.teamcenter.rac.kernel.TCComponentBOMWindowType;
 import com.teamcenter.rac.kernel.TCComponentContextList;
 import com.teamcenter.rac.kernel.TCComponentForm;
 import com.teamcenter.rac.kernel.TCComponentItemRevision;
 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.TCProperty;
 import com.teamcenter.rac.kernel.TCSession;
 import com.teamcenter.rac.kernel.TCTextService;
 import com.teamcenter.rac.kernel.TCUserService;
 import com.teamcenter.rac.util.MessageBox;

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

import java.io.File;
 import java.io.IOException;
 import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.Date;
 import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
import java.util.ResourceBundle;

import javax.swing.JTable;
 import javax.swing.SwingUtilities;
 import javax.swing.table.JTableHeader;
 import javax.swing.table.TableColumn;
 import org.jdom.Document;
 import org.jdom.Element;
 import org.jdom.JDOMException;
 import org.jdom.input.SAXBuilder;
 
 public class UtilApi {
   private static final int DEF_DIV_SCALE = 10;
   private static String erpPreference = "connor_tc_to_erp_url";
   private static ResourceBundle resource = ResourceBundle.getBundle("tcUser_erpUser");
   
   public static TCComponent[] query(TCSession session, String query_name, String[] arg1, String[] arg2) {
/*  77 */     TCComponentContextList imancomponentcontextlist = null;
/*  78 */     TCComponent[] component = null;
     try {
/*  80 */       TCComponentQueryType imancomponentquerytype = (TCComponentQueryType)session.getTypeComponent("ImanQuery");
/*  81 */       TCComponentQuery imancomponentquery = (TCComponentQuery)imancomponentquerytype.find(query_name);
/*  82 */       if (imancomponentquery == null) {
/*  83 */         System.out.println("未找到查询构建器" + query_name + "!!");
/*  84 */         return null;
       } 
/*  86 */       TCTextService imantextservice = session.getTextService();
/*  87 */       int keyNum = arg1.length;
/*  88 */       String[] queryAttribute = new String[keyNum];
/*  89 */       for (int i = 0; i < keyNum; i++)
/*  90 */         queryAttribute[i] = imantextservice.getTextValue(arg1[i]); 
/*  93 */       String[] queryValues = new String[keyNum];
/*  94 */       for (int j = 0; j < keyNum; j++)
/*  95 */         queryValues[j] = imantextservice.getTextValue(arg2[j]); 
/*  97 */       imancomponentcontextlist = imancomponentquery.getExecuteResultsList(queryAttribute, queryValues);
/*  98 */       component = imancomponentcontextlist.toTCComponentArray();
/*  99 */     } catch (Exception ex) {
/* 100 */       ex.printStackTrace();
     } 
/* 102 */     return component;
   }
   
   public static TCComponentForm getItemRelationForm(TCComponentItemRevision revision, String relation) throws TCException {
/* 112 */     if (revision != null) {
/* 113 */       AIFComponentContext[] contexts = revision.getChildren(relation);
/* 114 */       if (contexts != null && contexts.length > 0) {
/* 115 */         InterfaceAIFComponent component = contexts[0].getComponent();
/* 116 */         if (component instanceof TCComponentForm) {
/* 117 */           TCComponentForm form = (TCComponentForm)component;
/* 118 */           return form;
         } 
       } 
     } 
/* 122 */     return null;
   }
   
   public static TCComponentBOMLine getNewBOMLine(TCSession session, TCComponentItemRevision itemR, TCComponentBOMViewRevision tcBomView) {
     try {
/* 128 */       TCComponentBOMWindowType bomWinType = (TCComponentBOMWindowType)session.getTypeComponent("BOMWindow");
/* 129 */       TCComponentBOMWindow win = bomWinType.create(null);
/* 130 */       win.lock();
/* 131 */       win.setWindowTopLine(itemR.getItem(), itemR, null, (TCComponent)tcBomView);
/* 132 */       TCComponentBOMLine componentbomline = win.getTopBOMLine();
/* 133 */       return componentbomline;
/* 134 */     } catch (TCException e) {
/* 135 */       e.printStackTrace();
/* 136 */       return null;
     } 
   }
   
   public static String getCurrentTime() {
/* 141 */     return (new SimpleDateFormat("yyyyMMddHHmmssSSS")).format(new Date());
   }
   
   public static String getErrorInfoFromCode(int result) {
/* 145 */     String errorInfo = "";
/* 146 */     switch (result) {
       case 1:
/* 148 */         errorInfo = "本地文件读取错误";
/* 174 */         return errorInfo;
       case 2:
         errorInfo = "初始化TCP错误";
/* 174 */         return errorInfo;
       case 3:
         errorInfo = "发送请求数据错误";
/* 174 */         return errorInfo;
       case 4:
         errorInfo = "服务端获取结果错误";
/* 174 */         return errorInfo;
       case 5:
         errorInfo = "回传文件错误";
/* 174 */         return errorInfo;
       case 6:
         errorInfo = "关闭连接错误";
/* 174 */         return errorInfo;
       case 7:
         errorInfo = "其他错误";
/* 174 */         return errorInfo;
       case 8:
         errorInfo = "成功";
/* 174 */         return errorInfo;
     } 
     errorInfo = "";
/* 174 */     return errorInfo;
   }
   
   public static String getTaskStatus(int result) {
/* 178 */     String status = "";
/* 179 */     switch (result) {
       case 1:
/* 181 */         status = "文件上传完成";
/* 201 */         return status;
       case 2:
         status = "加入任务队列";
/* 201 */         return status;
       case 3:
         status = "开始任务";
/* 201 */         return status;
       case 4:
         status = "开始二次验证文件";
/* 201 */         return status;
       case 5:
         status = "二次验证通过开始API执行导入";
/* 201 */         return status;
       case 6:
         status = "导入过程完成任务结束";
/* 201 */         return status;
     } 
     status = "";
/* 201 */     return status;
   }
   
   public static String getTaskResult(int code) {
/* 205 */     String result = "";
/* 206 */     switch (code) {
       case 1:
/* 208 */         result = "任务成功";
/* 225 */         return result;
       case 2:
         result = "任务成功但有忽略";
/* 225 */         return result;
       case 3:
         result = "任务成功但有需用户注意";
/* 225 */         return result;
       case 4:
         result = "任务成功但子项目有严重错误";
/* 225 */         return result;
       case 5:
         result = "严重错误任务失败";
/* 225 */         return result;
     } 
     result = "";
/* 225 */     return result;
   }
   
   public static String getWrongLevel(int code) {
/* 229 */     String result = "";
/* 230 */     switch (code) {
       case 1:
/* 232 */         result = "可忽略错误";
/* 240 */         return result;
       case 2:
         result = "严重错误";
/* 240 */         return result;
     } 
     result = "";
/* 240 */     return result;
   }
   
   public static String getWrongType(int code) {
/* 244 */     String result = "";
/* 245 */     switch (code) {
       case 1:
/* 247 */         result = "对象不存在错误";
/* 261 */         return result;
       case 2:
         result = "对象已存在错误";
/* 261 */         return result;
       case 3:
         result = "对象属性不正确错误";
/* 261 */         return result;
       case 4:
         result = "其它错误";
/* 261 */         return result;
     } 
     result = "";
/* 261 */     return result;
   }
   
   public static int FitTableColumns(JTable myTable) {
/* 268 */     JTableHeader header = myTable.getTableHeader();
/* 269 */     int rowCount = myTable.getRowCount();
/* 270 */     Enumeration<?> columns = myTable.getColumnModel().getColumns();
/* 271 */     int totalWidth = 15;
/* 272 */     while (columns.hasMoreElements()) {
/* 273 */       TableColumn column = (TableColumn)columns.nextElement();
/* 274 */       int col = header.getColumnModel().getColumnIndex(column.getIdentifier());
/* 275 */       int width = (int)myTable.getTableHeader().getDefaultRenderer().getTableCellRendererComponent(myTable, column.getIdentifier(), false, false, -1, col).getPreferredSize().getWidth();
/* 276 */       for (int row = 0; row < rowCount; row++) {
/* 277 */         int preferedWidth = (int)myTable.getCellRenderer(row, col).getTableCellRendererComponent(myTable, myTable.getValueAt(row, col), false, false, row, col).getPreferredSize().getWidth();
/* 278 */         width = Math.max(width, preferedWidth);
       } 
/* 280 */       header.setResizingColumn(column);
/* 281 */       column.setWidth(width + (myTable.getIntercellSpacing()).width);
/* 282 */       totalWidth = totalWidth + width + (myTable.getIntercellSpacing()).width;
     } 
/* 284 */     return totalWidth;
   }
   
   public static boolean getTaskItemAddResult(AbstractAIFUIApplication application, TCSession session, FileType fileType, String title, Boolean isView, AbstractAIFCommand command, String dialogType) {
///* 290 */     String user_id = "";
//     try {
///* 292 */       user_id = session.getUser().getProperty("user_id");
///* 293 */     } catch (TCException ex) {
///* 294 */       ex.printStackTrace();
//     } 
/////* 296 */     String xmlFilePath = System.getProperty("java.io.tmpdir") + File.separator + user_id + "_" + getCurrentTime() + "_result.xml";
/////* 297 */     String addResult = getErrorInfoFromCode(PlmErpIntegration.getTaskResult(user_id, fileType.toString(), AimType.add.toString(), xmlFilePath, session));
//     Map<String, String> lastImpMap = new HashMap<String, String>();
////     if(resource.containsKey(user_id)) {
////    	 lastImpMap.put("creater", resource.getString(user_id));
////     }else {
////    	 lastImpMap.put("creater", "ZX_COMM");
////	}
//     lastImpMap.put("creater", user_id);
//     lastImpMap.put("type","ITEMADD");
//     			Map<String, Object> plmImpResultMap = doGet(lastImpMap, "PLMImpResult", session);
//     
/////* 298 */     if (addResult.equals("")) {
/////* 299 */       MessageBox.post(application.getDesktop().getShell(), "获取上次导入结果导入超时，请联系管理员！", "超时", 1);
/////* 300 */       return false;
////     } 
///* 302 */     String ItemInfo = "";
///* 303 */     StringBuffer detailInfo = new StringBuffer("新增基础数据<br>");
/////* 304 */     if (!addResult.equals("成功")) {
/////* 305 */       MessageBox.post(application.getDesktop().getShell(), addResult, "调用erp函数出现错误", 1);
/////* 306 */       return false;
////     } 
/////* 308 */     File xmlFile = new File(xmlFilePath);
/////* 309 */     if (xmlFile.exists()) {
///* 310 */       Map<String, Object> map = new HashMap<String, Object>();
///* 311 */       boolean isResultFile = ReadResultXMLStr.loadElements(plmImpResultMap, map);
///* 312 */       if (isResultFile) {
///* 313 */         String taskSN = "";
///* 314 */         if (map.get("taskSN") != null && !map.get("taskSN").equals("")) {
///* 315 */           taskSN = map.get("taskSN").toString();
//         } else {
///* 317 */           if (isView.booleanValue()) {
///* 318 */             MessageBox.post(application.getDesktop().getShell(), "新增基础数据未找到任务号！", "信息", 2);
///* 320 */           } else if (dialogType.equals("task")) {
///* 321 */             ((SendToERPCommand)command).postDialogForTask();
///* 322 */           } else if (dialogType.equals("item")) {
///* 323 */             ((SendToERPCommand)command).postDialogForItem();
///* 324 */           } else if (dialogType.equals("process")) {
///* 325 */             ((SendToERPCommand)command).postDialogForMeProcess();
//           } 
///* 328 */           return true;
//         } 
///* 330 */         detailInfo.append("任务号：").append(taskSN).append("<br>");
///* 331 */         int currentStep = Integer.parseInt(map.get("currentStep").toString());
///* 332 */         if (currentStep == 3) {
///* 334 */           TCComponent[] forms = query(session, "origin_searchItemRevForm", new String[] { "nhl8_ERPTaskNum" }, new String[] { taskSN });
///* 335 */           String taskResult = map.get("taskResult").toString();
//if(forms!=null&&forms.length>0) {
///* 336 */           if (taskResult.equals("0")) {
///* 337 */             ItemInfo = "上次导入任务正在执行或排队，请稍候提交…";
///* 338 */           } else if (taskResult.equals("1") || taskResult.equals("2")) {
///* 339 */             int formNum = forms.length;
///* 340 */             Object[] obj = new Object[1];
///* 341 */             obj[0] = Integer.valueOf(11);
///* 342 */             TCUserService service = session.getUserService();
///* 343 */             for (int i = 0; i < formNum; i++) {
//               try {
///* 345 */                 service.call("openByPass", obj);
///* 346 */                 forms[i].setLogicalProperty("nhl8_ItemimpSucc", true);
///* 347 */                 service.call("closeByPass", obj);
///* 348 */               } catch (TCException e) {
///* 349 */                 e.printStackTrace();
//               } 
//             } 
///* 352 */             ItemInfo = "新增基础数据导入成功！";
//           } else {
///* 354 */             List<String> listWronglineInfo = (List<String>)map.get("wrongLine");
///* 355 */             List<String> listWrongProcessItemId = new ArrayList<String>();
///* 356 */             if (listWronglineInfo != null) {
///* 357 */               int listSize = listWronglineInfo.size();
///* 358 */               for (int j = 0; j < listSize; j++) {
///* 359 */                 String wronglineInfo = listWronglineInfo.get(j);
///* 360 */                 listWrongProcessItemId.add((new StringBuffer(wronglineInfo.split(" ")[0])).toString());
///* 361 */                 detailInfo.append(wronglineInfo).append("<br>");
//               } 
//             } 
///* 365 */             int formNum = forms.length;
///* 366 */             Object[] obj = new Object[1];
///* 367 */             obj[0] = Integer.valueOf(11);
///* 368 */             TCUserService service = session.getUserService();
///* 369 */             for (int i = 0; i < formNum; i++) {
///* 370 */               String form_of_item_id = "";
//               try {
///* 372 */                 form_of_item_id = forms[i].getProperty("object_name").split("/")[0];
///* 373 */               } catch (TCException e1) {
///* 374 */                 e1.printStackTrace();
//               } 
///* 376 */               if (!listWrongProcessItemId.contains(form_of_item_id))
//                 try {
///* 378 */                   service.call("openByPass", obj);
///* 379 */                   forms[i].setLogicalProperty("nhl8_ItemimpSucc", true);
///* 380 */                   service.call("closeByPass", obj);
///* 381 */                 } catch (TCException e) {
///* 382 */                   e.printStackTrace();
//                 }  
//             } 
///* 386 */             if (taskResult.equals("3")) {
///* 387 */               ItemInfo = "新增基础数据任务错误";
///* 388 */             }
////						else if (taskResult.equals("4")) {
/////* 389 */               ItemInfo = "新增基础数据部分数据导入失败，请修正后重新导入！";
/////* 390 */             } else if (taskResult.equals("5")) {
/////* 391 */               ItemInfo = "新增基础数据任务失败，请修正后重新导入！";
/////* 392 */             } else if (taskResult.equals("6")) {
/////* 393 */               ItemInfo = "新增基础数据任务导入失败，请修正！";
////             } 
//           } 
//}else {
//	MessageBox.post("origin_searchItemRevForm查询器未找到表单属性nhl8_ERPTaskNum值为"+taskSN+"的表单","",MessageBox.INFORMATION);
//}
//         } else {
///* 397 */           ItemInfo = "上次导入任务正在执行或排队，请稍候提交…";
//         } 
//       } else {
///* 400 */         String taskSN = (String) map.get("taskSN");
///* 401 */         detailInfo.append("任务号：").append(taskSN).append("<br>");
///* 402 */         TCComponent[] forms = query(session, "origin_searchItemRevForm", new String[] { "nhl8_ERPTaskNum" }, new String[] { taskSN });
//if(forms!=null&&forms.length>0) {
///* 403 */         int formNum = forms.length;
///* 404 */         Map<String, String> idmap = new HashMap<String, String>();
///* 405 */         Map<String, TCComponentForm> idToFormmap = new HashMap<String, TCComponentForm>();
///* 406 */         String[] formProNames = { "nhl8_ProdrOrg", "nhl8_SpareOrg", "nhl8_UnprodrOrg" };
///* 407 */         for (int i = 0; i < formNum; i++) {
///* 408 */           TCComponentForm form = (TCComponentForm)forms[i];
///* 409 */           AIFComponentContext[] referenceComs = null;
//           try {
///* 411 */             referenceComs = form.whereReferenced();
///* 412 */           } catch (TCException e) {
///* 413 */             e.printStackTrace();
//           } 
///* 415 */           int referenceNum = referenceComs.length;
///* 416 */           String itemId = "";
///* 417 */           for (int j = 0; j < referenceNum; j++) {
///* 418 */             if (referenceComs[j].getComponent() instanceof TCComponentItemRevision) {
//               try {
///* 420 */                 itemId = referenceComs[j].getComponent().getProperty("item_id");
///* 421 */               } catch (Exception e) {
///* 422 */                 e.printStackTrace();
//               } 
//               break;
//             } 
//           } 
///* 427 */           idToFormmap.put(itemId, form);
///* 429 */           TCProperty[] formProperties = null;
//           try {
///* 431 */             formProperties = form.getTCProperties(formProNames);
///* 432 */             idmap.put(itemId, String.valueOf(formProperties[0].getLogicalValue()) + "-" + formProperties[1].getLogicalValue() + "-" + formProperties[2].getLogicalValue());
///* 433 */           } catch (TCException e) {
///* 434 */             e.printStackTrace();
//           } 
//         } 
///* 437 */         List<String> orgExistRightItems = new ArrayList<String>();
///* 438 */         List<String> orgExistWrongItems = new ArrayList<String>();
///* 439 */         List<String> Info = new ArrayList<String>();
//				  List<CheckResult> checkResults = new ArrayList<CheckResult>();
//				  Map<String, String> requestMap = new HashMap<String, String>();
//				  requestMap.put("sid", taskSN);
//				  requestMap.put("needParameter", "false");
//				  Map<String, Object> responseMap = doGet(requestMap, "result", session);
//				  JSONObject responseMapJSON = JSONObject.fromObject(responseMap);
//				  JSONArray jsonArray = responseMapJSON.getJSONArray("checkResult");
//				  checkResults = JSONArray.toList(jsonArray,CheckResult.class);
//				  
///* 440 */         ItemImportXMLReader.loadElements(checkResults, Info, orgExistRightItems, orgExistWrongItems, idmap);
///* 441 */         String errorInfo = Info.get(0);
///* 443 */         if (errorInfo.equals("")) {
///* 444 */           int orgExistRightItemNum = orgExistRightItems.size();
///* 445 */           if (orgExistRightItemNum > 0) {
///* 446 */             if (orgExistRightItemNum == formNum) {
///* 447 */               ItemInfo = "成功：所要导入数据在ERP均已经存在，无需导入！";
//             } else {
///* 449 */               Object[] obj = new Object[1];
///* 450 */               obj[0] = Integer.valueOf(11);
///* 451 */               TCUserService service = session.getUserService();
///* 452 */               for (int k = 0; k < orgExistRightItemNum; k++) {
//                 try {
///* 454 */                   service.call("openByPass", obj);
///* 455 */                   ((TCComponentForm)idToFormmap.get(orgExistRightItems.get(k))).setLogicalProperty("nhl8_ItemimpSucc", true);
///* 456 */                   service.call("closeByPass", obj);
///* 457 */                 } catch (TCException e) {
///* 458 */                   e.printStackTrace();
//                 } 
//               } 
///* 461 */               ItemInfo = "成功但有忽略";
//             } 
//           } else {
///* 464 */             ItemInfo = "验证成功";
///* 465 */             return true;
//           } 
//         } else {
///* 468 */           detailInfo.append(errorInfo).append("<br>");
///* 469 */           int orgExistWrongItemNum = orgExistWrongItems.size();
///* 470 */           if (orgExistWrongItemNum > 0) {
///* 471 */             if (orgExistWrongItemNum == formNum) {
///* 472 */               ItemInfo = "成功但有忽略";
//             } else {
///* 474 */               ItemInfo = "成功但有忽略";
///* 475 */               Object[] obj = new Object[1];
///* 476 */               obj[0] = Integer.valueOf(11);
///* 477 */               TCUserService service = session.getUserService();
///* 478 */               for (int k = 0; k < orgExistWrongItemNum; k++) {
//                 try {
///* 480 */                   service.call("openByPass", obj);
///* 481 */                   ((TCComponentForm)idToFormmap.get(orgExistWrongItems.get(k))).setLogicalProperty("nhl8_ItemimpSucc", true);
///* 482 */                   service.call("closeByPass", obj);
///* 483 */                 } catch (TCException e) {
///* 484 */                   e.printStackTrace();
//                 } 
//               } 
//             } 
//           } else {
///* 489 */             ItemInfo = "新增基础物料任务导入失败，请修正！";
//           } 
//         } 
//       }else {
//    		MessageBox.post("origin_searchItemRevForm查询器未找到表单属性nhl8_ERPTaskNum值为"+taskSN+"的表单","",MessageBox.INFORMATION);
//	}
//       } 
////     } else {
/////* 494 */       System.out.println(String.valueOf(xmlFilePath) + "文件不存在！");
////     } 
///* 497 */     System.out.println("401 ItemInfo=" + ItemInfo);
///* 498 */     if (!ItemInfo.contains("成功")) {
///* 499 */       SwingUtilities.invokeLater((Runnable)new ValidateFailDialog(ItemInfo.toString(), title, detailInfo.toString(), command, dialogType));
///* 500 */       return false;
//     } if (isView.booleanValue()) {
//	   /* 503 */       SwingUtilities.invokeLater((Runnable)new ValidateFailDialog(ItemInfo.toString(), title, detailInfo.toString()));
//   /* 505 */     } else 
/* 502 */     if (dialogType.equals("task")) {
/* 506 */       ((SendToERPCommand)command).postDialogForTask();
/* 507 */     } else if (dialogType.equals("item")) {
/* 508 */       ((SendToERPCommand)command).postDialogForItem();
/* 509 */     } else if (dialogType.equals("process")) {
/* 510 */       ((SendToERPCommand)command).postDialogForMeProcess();
     } 
/* 513 */     return true;
   }
   
   public static Map<String, Object> doGet(Map<String, String> map, String svr, 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(map);
//	   List<CheckResult> checkResults =null;
	   Map<String, Object> resultMap = new HashMap<String, Object>();
	   try {
		   System.out.println("开始发送请求");
		   String args = itemCheckJson.toString();
		   if(svr.equals("PLMImpResult")) {
			   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.doGet(url+"?"+param);
			   System.out.println("请求结果================"+response);
			   
			   JSONObject jsonObject = JSONObject.fromObject(response);
			   if(jsonObject==null || response==null) {
				   return null;
			   }
			   System.out.println("json格式==============="+jsonObject);
			   
			   JSONObject jsonObject2 = jsonObject.getJSONObject("cont");
			   System.out.println("cont==============="+jsonObject2);
			   
			   String last_task_sid = jsonObject2.getString("last_task_sid");
			   if(last_task_sid.contains("NOTEXIST")) {
				   System.out.println("位置utilapi");
//				   MessageBox.post("不存在上一次导入结果","",MessageBox.INFORMATION);
				   return null;
			   }else {
				   resultMap = (Map<String, Object>)JSONObject.toBean(jsonObject2,Map.class);
			   }
		   }else if(svr.equals("result")){
			   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.doGet(url+"?"+param);
			   System.out.println("请求结果================"+response);
			   
			   JSONObject jsonObject = JSONObject.fromObject(response);
			   System.out.println("json格式==============="+jsonObject);
			   JSONObject jsonObject2 = jsonObject.getJSONObject("cont");
			   System.out.println("cont==============="+jsonObject2);
			   JSONObject jsonObject3 = jsonObject2.getJSONObject("output");
			   
			   resultMap = (Map<String, Object>)JSONObject.toBean(jsonObject3,Map.class);
		   }
		   
//		   JSONArray checkResult = jsonObject2.getJSONArray("checkResult");
//		   canAllImport = jsonObject2.getBoolean("canAllImport");
//		   checkResults = JSONArray.toList(checkResult,CheckResult.class);
		   
	   } catch (Exception e1) {
		   // TODO Auto-generated catch block
		   e1.printStackTrace();
	   }
	   return resultMap;
   }
   
   public static boolean getTaskBomAddResult(AbstractAIFUIApplication application, TCSession session, FileType fileType, String title) {
/* 519 */     ResultInfo addResultInfo = getBomaddResult(application, session, FileType.bom);
/* 520 */     if (addResultInfo == null)
/* 521 */       return false; 
/* 523 */     String result = addResultInfo.getResult();
/* 524 */     if (result.equals("新增BOM没有发现任务号！"))
/* 525 */       return true; 
/* 526 */     if (!result.equals("新增BOM任务导入成功！")) {
/* 527 */       SwingUtilities.invokeLater((Runnable)new ValidateFailDialog(result, title, addResultInfo.getDetail()));
/* 528 */       return false;
     } 
/* 531 */     return true;
   }
   
   public static boolean getTaskBomAddResult(AbstractAIFUIApplication application, TCSession session, FileType fileType, String title, AbstractAIFCommand command, String dialogType, AimType aimType) {
///* 536 */     ResultInfo addResultInfo = getBomaddResult(application, session, FileType.bom);
///* 537 */     if (addResultInfo == null) {
	
				if (dialogType.equals("task")) {
		/* 543 */         ((BomTransferCommand)command).postDialogForTask(aimType);
		/* 544 */       } else if (dialogType.equals("bom")) {
		/* 545 */         ((BomTransferCommand)command).postDialogForBom(aimType);
		       } 
				return true; 
//			}
///* 538 */      
///* 540 */     String result = addResultInfo.getResult();
///* 541 */     if (result.equals("新增BOM没有发现任务号！") || result.equals("新增BOM任务导入成功！")) {
///* 542 */       if (dialogType.equals("task")) {
///* 543 */         ((BomTransferCommand)command).postDialogForTask(aimType);
///* 544 */       } else if (dialogType.equals("bom")) {
///* 545 */         ((BomTransferCommand)command).postDialogForBom(aimType);
//       } 
///* 547 */       return true;
//     } 
///* 549 */     SwingUtilities.invokeLater((Runnable)new ValidateFailDialog(result, title, addResultInfo.getDetail(), command, dialogType, aimType));
///* 550 */     return false;
   }
   
   public static boolean getTaskBomChgResult(AbstractAIFUIApplication application, TCSession session, FileType fileType, String title) {
/* 557 */     ResultInfo chgResultInfo = getBomchgResult(application, session, FileType.bom);
/* 558 */     if (chgResultInfo == null)
/* 559 */       return false; 
/* 561 */     String result = chgResultInfo.getResult();
/* 562 */     if (result.equals("变更BOM没有发现任务号！"))
/* 563 */       return true; 
/* 564 */     if (!result.equals("变更BOM任务导入成功！")) {
/* 565 */       SwingUtilities.invokeLater((Runnable)new ValidateFailDialog(chgResultInfo.getResult(), title, chgResultInfo.getDetail()));
/* 566 */       return false;
     } 
/* 569 */     return true;
   }
   
   public static boolean getTaskBomChgResult(AbstractAIFUIApplication application, TCSession session, FileType fileType, String title, AbstractAIFCommand command, String dialogType, AimType aimType) {
///* 573 */     ResultInfo chgResultInfo = getBomchgResult(application, session, FileType.bom);
///* 574 */     if (chgResultInfo == null) {
//					if (dialogType.equals("task")) {
///* 580 */         ((BomTransferCommand)command).postDialogForTask(aimType);
///* 581 */       } else if (dialogType.equals("bom")) {
///* 582 */         ((BomTransferCommand)command).postDialogForBom(aimType);
//       } 
///* 584 */       return true;
//				}
/* 577 */     String result = "变更BOM没有发现任务号！";
/* 578 */     if (result.equals("变更BOM没有发现任务号！") || result.equals("变更BOM任务导入成功！")) {
/* 579 */       if (dialogType.equals("task")) {
/* 580 */         ((BomTransferCommand)command).postDialogForTask(aimType);
/* 581 */       } else if (dialogType.equals("bom")) {
/* 582 */         ((BomTransferCommand)command).postDialogForBom(aimType);
       } 
/* 584 */       return true;
     } 
///* 586 */     SwingUtilities.invokeLater((Runnable)new ValidateFailDialog(chgResultInfo.getResult(), title, chgResultInfo.getDetail(), command, dialogType, aimType));
/* 587 */     return false;
   }
   
//   public static void getTaskBomResult(AbstractAIFUIApplication application, TCSession session, FileType fileType, String title) {
///* 595 */     ResultInfo addResultInfo = getBomaddResult(application, session, FileType.bom);
///* 596 */     ResultInfo chgResultInfo = getBomchgResult(application, session, FileType.bom);
///* 597 */     if (addResultInfo != null && chgResultInfo != null) {
///* 598 */       String BomInfo = "";
///* 599 */       String addResult = addResultInfo.getResult();
///* 600 */       String chgResult = chgResultInfo.getResult();
///* 601 */       if (addResult.equals("新增BOM没有发现任务号！") && chgResult.equals("变更BOM没有发现任务号！")) {
///* 602 */         MessageBox.post(application.getDesktop().getShell(), "新增和更改BOM没有发现任务号！", "信息", 2);
//         return;
//       } 
///* 605 */       if (addResult.equals("新增BOM任务导入成功！") && chgResult.equals("变更BOM任务导入成功！")) {
///* 606 */         BomInfo = "新增/变更BOM均导入成功！";
//       } else {
///* 608 */         BomInfo = String.valueOf(addResult) + "<br>" + chgResult;
//       } 
///* 610 */       String detailInfo = String.valueOf(addResultInfo.getDetail()) + chgResultInfo.getDetail();
///* 611 */       SwingUtilities.invokeLater((Runnable)new ValidateFailDialog(BomInfo, title, detailInfo));
//     } 
//   }
   
   public static ResultInfo getBomaddResult(AbstractAIFUIApplication application, TCSession session, FileType fileType) {
/* 618 */     String user_id = "";
     try {
       user_id = session.getUser().getProperty("user_id");
    } catch (TCException ex) {
       ex.printStackTrace();
     } 
///* 624 */     String xmlFilePath = System.getProperty("java.io.tmpdir") + File.separator + user_id + "_" + getCurrentTime() + "_result.xml";
/* 625 */     String BomaddInfo = "";
///* 627 */     String addResult = getErrorInfoFromCode(PlmErpIntegration.getTaskResult(user_id, fileType.toString(), AimType.add.toString(), xmlFilePath, session));
///* 627 */     String addResult = "";
///* 628 */     if (addResult.equals("")) {
///* 629 */       MessageBox.post(application.getDesktop().getShell(), "获取上次导入结果导入超时，请联系管理员！", "超时", 1);
///* 630 */       return null;
//     } 
/* 632 */     StringBuffer addDetailInfo = new StringBuffer("新增BOM<br>");
Map<String, String> lastImpMap = new HashMap<String, String>();
//if(resource.containsKey(user_id)) {
//	 lastImpMap.put("creater", resource.getString(user_id));
//}else {
//	 lastImpMap.put("creater", "ZX_COMM");
//}
lastImpMap.put("creater", user_id);
lastImpMap.put("type","BOMADD");
			Map<String, Object> plmImpResultMap = doGet(lastImpMap, "PLMImpResult", session);
///* 633 */     if (!addResult.equals("成功")) {
///* 634 */       MessageBox.post(application.getDesktop().getShell(), addResult, "调用erp函数出现错误", 1);
///* 635 */       return null;
//     } 
///* 637 */     File xmlFile = new File(xmlFilePath);
///* 638 */     if (xmlFile.exists()) {
			if(plmImpResultMap==null) {
				return null;
			}
/* 639 */       Map<String, Object> map = new HashMap<String, Object>();
/* 640 */       boolean isResultFile = ReadResultXMLStr.loadElements(plmImpResultMap, map);
///* 640 */       boolean isResultFile = true;
/* 641 */       if (isResultFile) {
/* 642 */         String taskSN = "";
/* 643 */         if (map.get("taskSN") != null && !map.get("taskSN").equals("")) {
/* 644 */           taskSN = map.get("taskSN").toString();
         } else {
/* 646 */           ResultInfo resultInfo = new ResultInfo("新增BOM没有发现任务号！", "");
/* 647 */           return resultInfo;
         } 
/* 649 */         addDetailInfo.append("任务号：").append(taskSN).append("<br>");
/* 650 */         int currentStep = Integer.parseInt(map.get("currentStep").toString());
/* 651 */         if (currentStep == 3) {
/* 653 */           TCComponent[] forms = query(session, "origin_searchItemRevForm", new String[] { "nhl8_ERPTaskNum" }, new String[] { taskSN });
if(forms!=null&&forms.length>0) {
/* 654 */           String taskResult = map.get("taskResult").toString();
/* 655 */           if (taskResult.equals("0")) {
/* 656 */             BomaddInfo = "上次导入任务正在执行或排队，请稍候提交…";
/* 657 */           } else if (taskResult.equals("1") || taskResult.equals("2")) {
/* 658 */             int formNum = forms.length;
/* 659 */             Object[] obj = new Object[1];
/* 660 */             obj[0] = Integer.valueOf(11);
/* 661 */             TCUserService service = session.getUserService();
/* 662 */             for (int i = 0; i < formNum; i++) {
               try {
/* 664 */                 service.call("openByPass", obj);
/* 665 */                 forms[i].setLogicalProperty("nhl8_BOMimpSucc", true);
/* 666 */                 service.call("closeByPass", obj);
/* 667 */               } catch (TCException e) {
/* 668 */                 e.printStackTrace();
               } 
             } 
/* 671 */             BomaddInfo = "新增BOM任务导入成功！";
           } else {
/* 673 */             List<String> listWronglineInfo = (List<String>)map.get("wrongLine");
/* 674 */             List<String> listWrongProcessItemId = new ArrayList<String>();
/* 675 */             int listSize = listWronglineInfo.size();
/* 676 */             for (int i = 0; i < listSize; i++) {
/* 677 */               String wronglineInfo = listWronglineInfo.get(i);
/* 678 */               listWrongProcessItemId.add((new StringBuffer(wronglineInfo.split(" ")[0])).toString());
/* 679 */               addDetailInfo.append(wronglineInfo).append("<br>");
             } 
/* 681 */             int formNum = forms.length;
/* 682 */             Object[] obj = new Object[1];
/* 683 */             obj[0] = Integer.valueOf(11);
/* 684 */             TCUserService service = session.getUserService();
/* 685 */             for (int j = 0; j < formNum; j++) {
/* 686 */               String form_of_item_id = "";
               try {
/* 688 */                 form_of_item_id = forms[j].getProperty("object_name").split("/")[0];
/* 689 */               } catch (TCException e1) {
/* 690 */                 e1.printStackTrace();
               } 
/* 692 */               if (!listWrongProcessItemId.contains(form_of_item_id))
                 try {
/* 694 */                   service.call("openByPass", obj);
/* 695 */                   forms[j].setLogicalProperty("nhl8_BOMimpSucc", true);
/* 696 */                   service.call("closeByPass", obj);
/* 697 */                 } catch (TCException e) {
/* 698 */                   e.printStackTrace();
                 }  
             } 
/* 702 */             if (taskResult.equals("3")) {
/* 703 */               BomaddInfo = "新增BOM任务错误";
/* 704 */             } 
//else if (taskResult.equals("4")) {
///* 705 */               BomaddInfo = "新增BOM部分数据导入失败，请修正后重新导入！";
///* 706 */             } else if (taskResult.equals("5")) {
///* 707 */               BomaddInfo = "新增BOM任务失败，请修正后重新导入！";
///* 708 */             } else if (taskResult.equals("6")) {
///* 709 */               BomaddInfo = "新增BOM任务导入失败，请修正！";
//             } 
           } 
}else {
	MessageBox.post("origin_searchItemRevForm查询器未找到表单属性nhl8_ERPTaskNum值为"+taskSN+"的表单","",MessageBox.INFORMATION);
}
         } else {
/* 713 */           BomaddInfo = "上次导入任务正在执行或排队，请稍候提交…";
         } 
       } else {
/* 716 */         String taskSN = (String) map.get("taskSN");
/* 717 */         addDetailInfo.append("任务号：").append(taskSN).append("<br>");
/* 719 */         StringBuffer errorInfo = new StringBuffer("");
					List<BomCheckResult> checkResults = new ArrayList<BomCheckResult>();
					Map<String, String> requestMap = new HashMap<String, String>();
					requestMap.put("sid", taskSN);
					requestMap.put("needParameter", "false");
					Map<String, Object> responseMap = doGet(requestMap, "result", session);
					JSONObject responseMapJSON = JSONObject.fromObject(responseMap);
					JSONArray jsonArray = responseMapJSON.getJSONArray("checkResult");
					checkResults = JSONArray.toList(jsonArray,BomCheckResult.class);
//					BomAddImportXMLReader.loadElements(checkResults, errorInfo);
/* 721 */         addDetailInfo.append(errorInfo.toString()).append("<br>");
/* 722 */         BomaddInfo = "新增BOM任务导入失败，请修正！";
       } 
//     } else {
///* 725 */       System.out.println(String.valueOf(xmlFilePath) + "文件不存在！");
//     } 
/* 728 */     ResultInfo result = new ResultInfo(BomaddInfo, addDetailInfo.toString());
/* 729 */     return result;
   }
   
   public static ResultInfo getBomchgResult(AbstractAIFUIApplication application, TCSession session, FileType fileType) {
/* 735 */     String user_id = "";
     try {
/* 737 */       user_id = session.getUser().getProperty("user_id");
/* 738 */     } catch (TCException ex) {
/* 739 */       ex.printStackTrace();
     } 
///* 741 */     String xmlFilePath = System.getProperty("java.io.tmpdir") + File.separator + user_id + "_" + getCurrentTime() + "_result.xml";
/* 743 */     String BomchgInfo = "";
///* 745 */     String chgResult = getErrorInfoFromCode(PlmErpIntegration.getTaskResult(user_id, fileType.toString(), AimType.chg.toString(), xmlFilePath, session));
///* 745 */     String chgResult = "";
///* 746 */     if (chgResult.equals("")) {
///* 747 */       MessageBox.post(application.getDesktop().getShell(), "获取上次导入结果导入超时，请联系管理员！", "超时", 1);
///* 748 */       return null;
//     } 
/* 750 */     StringBuffer chgDetailInfo = new StringBuffer("变更BOM<br>");
///* 751 */     if (!chgResult.equals("成功")) {
///* 752 */       MessageBox.post(application.getDesktop().getShell(), chgResult, "调用erp函数出现错误", 1);
///* 753 */       return null;
//     } 
				Map<String, String> lastImpMap = new HashMap<String, String>();
//			     if(resource.containsKey(user_id)) {
//			    	 lastImpMap.put("creater", resource.getString(user_id));
//			     }else {
//			    	 lastImpMap.put("creater", "ZX_COMM");
//				}
				lastImpMap.put("creater", user_id);
				lastImpMap.put("type","BOMCHG");
				Map<String, Object> plmImpResultMap = doGet(lastImpMap, "PLMImpResult", session);
///* 755 */     File xmlFile = new File(xmlFilePath);
///* 756 */     if (xmlFile.exists()) {
/* 757 */       Map<String, Object> map = new HashMap<String, Object>();
/* 758 */       boolean isResultFile = ReadResultXMLStr.loadElements(plmImpResultMap, map);
///* 758 */       boolean isResultFile = true;
/* 759 */       if (isResultFile) {
/* 760 */         String taskSN = "";
/* 761 */         if (map.get("taskSN") != null && !map.get("taskSN").equals("")) {
/* 762 */           taskSN = map.get("taskSN").toString();
         } else {
/* 764 */           ResultInfo resultInfo = new ResultInfo("变更BOM没有发现任务号！", "");
/* 765 */           return resultInfo;
         } 
/* 767 */         chgDetailInfo.append("任务号：").append(taskSN).append("<br>");
/* 768 */         int currentStep = Integer.parseInt(map.get("currentStep").toString());
/* 769 */         if (currentStep == 3) {
/* 771 */           TCComponent[] forms = query(session, "origin_searchItemRevForm", new String[] { "nhl8_ERPTaskNum" }, new String[] { taskSN });
/* 772 */           String taskResult = map.get("taskResult").toString();
if(forms!=null&&forms.length>0) {
/* 773 */           if (taskResult.equals("0")) {
/* 774 */             BomchgInfo = "上次导入任务正在执行或排队，请稍候提交…";
/* 775 */           } else if (taskResult.equals("1") || taskResult.equals("2")) {
/* 776 */             int formNum = forms.length;
/* 777 */             Object[] obj = new Object[1];
/* 778 */             obj[0] = Integer.valueOf(11);
/* 779 */             TCUserService service = session.getUserService();
/* 780 */             for (int i = 0; i < formNum; i++) {
               try {
/* 782 */                 service.call("openByPass", obj);
/* 783 */                 forms[i].setLogicalProperty("nhl8_BOMimpSucc", true);
/* 784 */                 service.call("closeByPass", obj);
/* 785 */               } catch (TCException e) {
/* 786 */                 e.printStackTrace();
               } 
             } 
/* 789 */             BomchgInfo = "变更BOM任务导入成功！";
           } else {
/* 791 */             List<String> listWronglineInfo = (List<String>)map.get("wrongLine");
/* 792 */             List<String> listWrongProcessItemId = new ArrayList<String>();
/* 793 */             int listSize = listWronglineInfo.size();
/* 794 */             for (int i = 0; i < listSize; i++) {
/* 795 */               String wronglineInfo = listWronglineInfo.get(i);
/* 796 */               listWrongProcessItemId.add((new StringBuffer(wronglineInfo.split(" ")[0])).toString());
/* 797 */               chgDetailInfo.append(wronglineInfo).append("<br>");
             } 
/* 799 */             int formNum = forms.length;
/* 800 */             Object[] obj = new Object[1];
/* 801 */             obj[0] = Integer.valueOf(11);
/* 802 */             TCUserService service = session.getUserService();
/* 803 */             for (int j = 0; j < formNum; j++) {
/* 804 */               String form_of_item_id = "";
               try {
/* 806 */                 form_of_item_id = forms[j].getProperty("object_name").split("/")[0];
/* 807 */               } catch (TCException e1) {
/* 808 */                 e1.printStackTrace();
               } 
/* 811 */               if (!listWrongProcessItemId.contains(form_of_item_id))
                 try {
/* 813 */                   service.call("openByPass", obj);
/* 814 */                   forms[j].setLogicalProperty("nhl8_BOMimpSucc", true);
/* 815 */                   service.call("closeByPass", obj);
/* 816 */                 } catch (TCException e) {
/* 817 */                   e.printStackTrace();
                 }  
             } 
/* 821 */             if (taskResult.equals("3")) {
/* 822 */               BomchgInfo = "变更BOM任务导入错误，请至ERP修改！";
/* 823 */             } 
//						else if (taskResult.equals("4")) {
///* 824 */               BomchgInfo = "变更BOM部分数据导入失败，请修正后重新导入！";
///* 825 */             } else if (taskResult.equals("5")) {
///* 826 */               BomchgInfo = "变更BOM任务失败，请修正后重新导入！";
///* 827 */             } else if (taskResult.equals("6")) {
///* 828 */               BomchgInfo = "变更BOM任务导入失败，请修正！";
//             } 
           } 
}else {
	MessageBox.post("origin_searchItemRevForm查询器未找到表单属性nhl8_ERPTaskNum值为"+taskSN+"的表单","",MessageBox.INFORMATION);
}
         } else {
/* 832 */           BomchgInfo = "上次导入任务正在执行或排队，请稍候提交…";
         } 
       } else {
/* 835 */         String taskSN = map.get("taskSN").toString();
/* 836 */         chgDetailInfo.append("任务号：").append(taskSN).append("<br>");
					List<BomCheckResult> checkResults = new ArrayList<BomCheckResult>();
					Map<String, String> requestMap = new HashMap<String, String>();
					requestMap.put("sid", taskSN);
					requestMap.put("needParameter", "false");
					Map<String, Object> responseMap = doGet(requestMap, "result", session);
					JSONObject responseMapJSON = JSONObject.fromObject(responseMap);
					JSONArray jsonArray = responseMapJSON.getJSONArray("checkResult");
					checkResults = JSONArray.toList(jsonArray,BomCheckResult.class);
					String errorInfo = BomChgImportXMLReader.loadElements(checkResults);
/* 838 */         chgDetailInfo.append(errorInfo).append("<br>");
/* 840 */         BomchgInfo = "变更BOM任务导入失败，请修正！";
       } 
//     } else {
///* 844 */       System.out.println(String.valueOf(xmlFilePath) + "文件不存在！");
//     } 
/* 847 */     ResultInfo result = new ResultInfo(BomchgInfo, chgDetailInfo.toString());
/* 848 */     return result;
   }
   
   public static String getTaskSN(File xmlFile) {
/* 853 */     SAXBuilder sb = new SAXBuilder();
/* 854 */     String taskSN = null;
     try {
/* 857 */       Document doc = sb.build(xmlFile);
/* 859 */       Element root = doc.getRootElement();
/* 861 */       taskSN = root.getAttribute("taskSN").getValue();
/* 863 */     } catch (JDOMException e) {
/* 864 */       e.printStackTrace();
/* 865 */     } catch (IOException e) {
/* 866 */       e.printStackTrace();
     } 
/* 868 */     return taskSN;
   }
   
   public static String subZeroAndDot(String s) {
/* 877 */     if (s.indexOf(".") > 0) {
/* 878 */       s = s.replaceAll("0+?$", "");
/* 879 */       s = s.replaceAll("[.]$", "");
     } 
/* 881 */     return s;
   }
   
   public static double div(double v1, double v2) {
/* 892 */     return div(v1, v2, 10);
   }
   
   public static double div(double v1, double v2, int scale) {
/* 904 */     if (scale < 0)
/* 905 */       throw new IllegalArgumentException(
/* 906 */           "The scale must be a positive integer or zero"); 
/* 908 */     BigDecimal b1 = new BigDecimal(Double.toString(v1));
/* 909 */     BigDecimal b2 = new BigDecimal(Double.toString(v2));
/* 910 */     return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
   }
   
   public static double add(double v1, double v2) {
/* 920 */     BigDecimal b1 = new BigDecimal(Double.toString(v1));
/* 921 */     BigDecimal b2 = new BigDecimal(Double.toString(v2));
/* 922 */     return b1.add(b2).doubleValue();
   }
 }

