 package com.connor.erp.ProcessImport;
 
 import com.connor.erp.processresource.EquipmentAcquiredFromERP.TCPreferenceUitl;
import com.connor.erp.toolkit.AimType;
 import com.connor.erp.toolkit.FileType;
import com.connor.erp.toolkit.HttpUtil;
 import com.connor.erp.toolkit.ReadResultXMLStr;
 import com.connor.erp.toolkit.ResultInfo;
 import com.connor.erp.toolkit.UtilApi;
import com.connor.erpintegration.entity.RouteCheckResult;
// import com.connor.tcerp.conn.PlmErpIntegration;
 import com.teamcenter.rac.aif.AbstractAIFUIApplication;
 import com.teamcenter.rac.kernel.TCComponent;
 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.JSONArray;
import net.sf.json.JSONObject;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
import java.util.ResourceBundle;

import javax.swing.SwingUtilities;
 
 public class ProcessImportApi {
	 
	   private static String erpPreference = "connor_tc_to_erp_url";
	   
	   private static ResourceBundle resource = ResourceBundle.getBundle("tcUser_erpUser");
	 
   public static boolean getTaskRouteAddResult(AbstractAIFUIApplication application, TCSession session, FileType fileType, String title, ProcessImportHandler handler, String dialogType) {
///*  46 */     ResultInfo addResultInfo = getRouteAddResult(application, session, FileType.route);
///*  47 */     if (addResultInfo == null) {
				if (dialogType.equals("task")) {
/*  53 */         handler.postDialogForTask(false);
/*  54 */       } else if (dialogType.equals("route")) {
/*  55 */         handler.postDialogForRoute(false);
   				} 
/*  57 */       return true;
//			}
/*  48 */       
///*  50 */     String result = addResultInfo.getResult();
///*  51 */     if (result.equals("新增工艺路线没有发现任务号！") || result.equals("新增工艺路线任务导入成功！")) {
///*  52 */       if (dialogType.equals("task")) {
///*  53 */         handler.postDialogForTask(false);
///*  54 */       } else if (dialogType.equals("route")) {
///*  55 */         handler.postDialogForRoute(false);
//       } 
///*  57 */       return true;
//     } 
///*  59 */     SwingUtilities.invokeLater((Runnable)new ValidateFailDialog(result, title, addResultInfo.getDetail(), handler, dialogType));
///*  60 */     return false;
   }
   
   public static boolean getTaskRouteChgResult(AbstractAIFUIApplication application, TCSession session, FileType fileType, String title, ProcessImportHandler handler, String dialogType) {
///*  67 */     ResultInfo chgResultInfo = getRouteChgResult(application, session, FileType.route);
///*  68 */     if (chgResultInfo == null) {
				if (dialogType.equals("task")) {
/*  74 */         handler.postDialogForTask(false);
/*  75 */       } else if (dialogType.equals("route")) {
/*  76 */         handler.postDialogForRoute(false);
				} 
/*  78 */       return true;
//			}
///*  71 */     String result = chgResultInfo.getResult();
///*  72 */     if (result.equals("变更工艺路线没有发现任务号！") || result.equals("变更工艺路线任务导入成功！")) {
///*  73 */       if (dialogType.equals("task")) {
///*  74 */         handler.postDialogForTask(false);
///*  75 */       } else if (dialogType.equals("route")) {
///*  76 */         handler.postDialogForRoute(false);
//       } 
///*  78 */       return true;
//     } 
///*  80 */     SwingUtilities.invokeLater((Runnable)new ValidateFailDialog(chgResultInfo.getResult(), title, chgResultInfo.getDetail(), handler, dialogType));
///*  81 */     return false;
   }
   
//   public static void getTaskRouteResult(AbstractAIFUIApplication application, TCSession session, FileType fileType, String title) {
///*  89 */     ResultInfo addResultInfo = getRouteAddResult(application, session, FileType.route);
///*  90 */     ResultInfo chgResultInfo = getRouteChgResult(application, session, FileType.route);
///*  91 */     if (addResultInfo != null && chgResultInfo != null) {
///*  92 */       String RouteInfo = "";
///*  93 */       String addResult = addResultInfo.getResult();
///*  94 */       String chgResult = chgResultInfo.getResult();
///*  95 */       if (addResult.equals("新增工艺路线没有发现任务号！") && chgResult.equals("变更工艺路线没有发现任务号！")) {
///*  96 */         MessageBox.post(application.getDesktop().getShell(), "新增和变更工艺路线没有发现任务号！", "信息", 2);
//         return;
//       } 
///*  99 */       if (addResult.equals("新增工艺路线任务导入成功！") && chgResult.equals("变更工艺路线任务导入成功！")) {
///* 100 */         RouteInfo = "新增/变更工艺路线均导入成功！";
//       } else {
///* 102 */         RouteInfo = String.valueOf(addResult) + "<br>" + chgResult;
//       } 
///* 104 */       String detailInfo = String.valueOf(addResultInfo.getDetail()) + chgResultInfo.getDetail();
///* 105 */       SwingUtilities.invokeLater((Runnable)new ValidateFailDialog(RouteInfo, title, detailInfo));
//     } 
//   }
//   private ResourceBundle resource = ResourceBundle.getBundle("tcUser_erpUser");
   public static ResultInfo getRouteAddResult(AbstractAIFUIApplication application, TCSession session, FileType fileType) {
	   System.out.println("getRouteAddResult");
/* 111 */     String user_id = "";
     try {
/* 113 */       user_id = session.getUser().getProperty("user_id");
/* 114 */     } catch (TCException ex) {
/* 115 */       ex.printStackTrace();
     } 
///* 117 */     String tempPath = System.getProperty("java.io.tmpdir") + File.separator;
///* 118 */     String xmlName = tempPath + user_id + "_" + UtilApi.getCurrentTime();
///* 119 */     String xmlFilePath = xmlName + "_result.xml";
///* 121 */     String addResult = UtilApi.getErrorInfoFromCode(PlmErpIntegration.getTaskResult(user_id, fileType.toString(), AimType.add.toString(), xmlFilePath, session));
///* 121 */     String addResult = "";
///* 122 */     if (addResult.equals("")) {
///* 123 */       MessageBox.post(application.getDesktop().getShell(), "获取上次导入结果导入超时，请联系管理员！", "超时", 1);
///* 124 */       return null;
//     } 
/* 126 */     StringBuffer addDetailInfo = new StringBuffer("新增工艺路线<br>");
/* 127 */     String routeAddInfo = "";
				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","ROUTEADD");
				Map<String, Object> plmImpResultMap = doGet(lastImpMap, "PLMImpResult", session);
///* 128 */     if (!addResult.equals("成功")) {
///* 129 */       MessageBox.post(application.getDesktop().getShell(), addResult, "调用erp函数出现错误", 1);
///* 130 */       return null;
//     } 
///* 132 */     File xmlFile = new File(xmlFilePath);
///* 133 */     if (xmlFile.exists()) {
/* 134 */       Map<String, Object> map = new HashMap<String, Object>();
/* 135 */       boolean isResultFile = ReadResultXMLStr.loadElements(plmImpResultMap, map);
///* 135 */       boolean isResultFile = true;
/* 136 */       if (isResultFile) {
/* 137 */         String taskSN = "";
/* 138 */         if (map.get("taskSN") != null && !map.get("taskSN").equals("")) {
/* 139 */           taskSN = map.get("taskSN").toString();
         } else {
/* 141 */           ResultInfo resultInfo = new ResultInfo("新增工艺路线没有发现任务号！", "");
/* 142 */           return resultInfo;
         } 
/* 144 */         addDetailInfo.append("任务号：").append(taskSN).append("<br>");
/* 145 */         int currentStep = Integer.parseInt(map.get("currentStep").toString());
/* 146 */         if (currentStep == 3) {
/* 148 */           TCComponent[] forms = UtilApi.query(session, "origin_searchMEProcessRevForm", new String[] { "nhl8_ERPTaskNum" }, new String[] { taskSN });
if(forms!=null&&forms.length>0) {
/* 149 */           String taskResult = map.get("taskResult").toString();
/* 150 */           if (taskResult.equals("0")) {
/* 151 */             routeAddInfo = "上次导入任务正在执行或排队，请稍候提交…";
/* 152 */           } else if (taskResult.equals("1") || taskResult.equals("2")) {
/* 153 */             int formNum = forms.length;
/* 154 */             Object[] obj = new Object[1];
/* 155 */             obj[0] = Integer.valueOf(11);
/* 156 */             TCUserService service = session.getUserService();
///* 157 */             for (int i = 0; i < formNum; i++) {
//               try {
///* 159 */                 service.call("openByPass", obj);
///* 160 */                 forms[i].setLogicalProperty("nhl8_ERPimpSucc", true);
///* 161 */                 service.call("closeByPass", obj);
///* 162 */               } catch (TCException e) {
///* 163 */                 e.printStackTrace();
//               } 
//             } 
/* 166 */             routeAddInfo = "新增工艺路线任务导入成功！";
           } else {
/* 170 */             List<String> listWronglineInfo = (List<String>)map.get("wrongLine");
/* 171 */             List<String> listWrongProcessItemId = new ArrayList<String>();
/* 172 */             int listSize = listWronglineInfo.size();
/* 173 */             for (int i = 0; i < listSize; i++) {
/* 174 */               String wronglineInfo = listWronglineInfo.get(i);
/* 175 */               listWrongProcessItemId.add(wronglineInfo.split(" ")[0] + "GY");
/* 176 */               addDetailInfo.append(wronglineInfo).append("<br>");
             } 
/* 178 */             int formNum = forms.length;
/* 179 */             Object[] obj = new Object[1];
/* 180 */             obj[0] = Integer.valueOf(11);
/* 181 */             TCUserService service = session.getUserService();
/* 182 */             for (int j = 0; j < formNum; j++) {
/* 183 */               String form_of_item_id = "";
               try {
/* 185 */                 form_of_item_id = forms[j].getProperty("object_name").split("/")[0];
/* 186 */               } catch (TCException e1) {
/* 187 */                 e1.printStackTrace();
               } 
///* 189 */               if (!listWrongProcessItemId.contains(form_of_item_id))
//                 try {
///* 191 */                   service.call("openByPass", obj);
///* 192 */                   forms[j].setLogicalProperty("nhl8_ERPimpSucc", true);
///* 193 */                   service.call("closeByPass", obj);
///* 194 */                 } catch (TCException e) {
///* 195 */                   e.printStackTrace();
//                 }  
             } 
/* 199 */             if (taskResult.equals("3")) {
/* 200 */               routeAddInfo = "新增工艺路线任务导入错误，请至ERP修改！";
/* 201 */             } 
//						else if (taskResult.equals("4")) {
///* 202 */               routeAddInfo = "新增工艺路线部分数据导入失败，请修正后重新导入！";
///* 203 */             } else if (taskResult.equals("5")) {
///* 204 */               routeAddInfo = "新增工艺路线任务失败，请修正后重新导入！";
///* 205 */             } else if (taskResult.equals("6")) {
///* 206 */               routeAddInfo = "新增工艺路线任务导入失败，请修正！";
//             } 
           } 
}else {
	MessageBox.post("origin_searchItemRevForm查询器未找到表单属性nhl8_ERPTaskNum值为"+taskSN+"的表单","",MessageBox.INFORMATION);
}
         } else {
/* 210 */           routeAddInfo = "上次导入任务正在执行或排队，请稍候提交…";
         } 
       } else {
/* 213 */         String taskSN = map.get("taskSN").toString();
/* 214 */         addDetailInfo.append("任务号：").append(taskSN).append("<br>");
					List<RouteCheckResult> routeCheckResults = new ArrayList<RouteCheckResult>();
					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");
					routeCheckResults = JSONArray.toList(jsonArray,RouteCheckResult.class);
					String errorInfo = ProcessImportReadXMLStr.loadAddElements(routeCheckResults);
///* 215 */         String errorInfo = ProcessImportReadXMLStr.xmlAddElements(session, xmlFile);
///* 215 */         String errorInfo = "";
/* 216 */         addDetailInfo.append(errorInfo).append("<br>");
/* 217 */         routeAddInfo = "新增工艺路线任务导入失败，请修正！";
       } 
//     } else {
///* 220 */       System.out.println(xmlFile + "文件未找到！");
//     } 
/* 223 */     ResultInfo result = new ResultInfo(routeAddInfo, addDetailInfo.toString());
/* 224 */     return result;
   }
   
   public static ResultInfo getRouteChgResult(AbstractAIFUIApplication application, TCSession session, FileType fileType) {
	   System.out.println("getRouteChgResult");
/* 229 */     String user_id = "";
     try {
/* 231 */       user_id = session.getUser().getProperty("user_id");
/* 232 */     } catch (TCException ex) {
/* 233 */       ex.printStackTrace();
     } 
///* 235 */     String tempPath = System.getProperty("java.io.tmpdir") + File.separator;
///* 236 */     String xmlName = tempPath + user_id + "_" + UtilApi.getCurrentTime();
///* 237 */     String xmlFilePath = xmlName + "_result.xml";
///* 239 */     String chgResult = UtilApi.getErrorInfoFromCode(PlmErpIntegration.getTaskResult(user_id, fileType.toString(), AimType.chg.toString(), xmlFilePath, session));
///* 239 */     String chgResult = "";
///* 240 */     if (chgResult.equals("")) {
///* 241 */       MessageBox.post(application.getDesktop().getShell(), "获取上次导入结果导入超时，请联系管理员！", "超时", 1);
///* 242 */       return null;
//     } 
/* 244 */     StringBuffer chgDetailInfo = new StringBuffer("变更工艺路线<br>");
/* 245 */     String routeChgInfo = "";
				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","ROUTECHG");
				Map<String, Object> plmImpResultMap = doGet(lastImpMap, "PLMImpResult", session);
///* 246 */     if (!chgResult.equals("成功")) {
///* 247 */       MessageBox.post(application.getDesktop().getShell(), chgResult, "调用erp函数出现错误", 1);
///* 248 */       return null;
//     } 
///* 250 */     File xmlFile = new File(xmlFilePath);
///* 251 */     if (xmlFile.exists()) {
/* 252 */       Map<String, Object> map = new HashMap<String, Object>();
/* 253 */       boolean isResultFile = ReadResultXMLStr.loadElements(plmImpResultMap, map);
///* 253 */       boolean isResultFile = true;
/* 254 */       if (isResultFile) {
/* 255 */         String taskSN = "";
/* 256 */         if (map.get("taskSN") != null && !map.get("taskSN").equals("")) {
/* 257 */           taskSN = map.get("taskSN").toString();
         } else {
/* 259 */           ResultInfo resultInfo = new ResultInfo("变更工艺路线没有发现任务号！", "");
/* 260 */           return resultInfo;
         } 
/* 262 */         chgDetailInfo.append("任务号：").append(taskSN).append("<br>");
/* 263 */         int currentStep = Integer.parseInt(map.get("currentStep").toString());
/* 264 */         if (currentStep == 3) {
/* 266 */           TCComponent[] forms = UtilApi.query(session, "origin_searchMEProcessRevForm", new String[] { "nhl8_ERPTaskNum" }, new String[] { taskSN });
if(forms!=null&&forms.length>0) {
/* 267 */           String taskResult = map.get("taskResult").toString();
/* 268 */           if (taskResult.equals("0")) {
/* 269 */             routeChgInfo = "上次导入任务正在执行或排队，请稍候提交…";
/* 270 */           } else if (taskResult.equals("1") || taskResult.equals("2")) {
/* 271 */             int formNum = forms.length;
/* 272 */             Object[] obj = new Object[1];
/* 273 */             obj[0] = Integer.valueOf(11);
/* 274 */             TCUserService service = session.getUserService();
/* 275 */             for (int i = 0; i < formNum; i++) {
//               try {
///* 277 */                 service.call("openByPass", obj);
///* 278 */                 forms[i].setLogicalProperty("nhl8_ERPimpSucc", true);
///* 279 */                 service.call("closeByPass", obj);
///* 280 */               } catch (TCException e) {
///* 281 */                 e.printStackTrace();
//               } 
             } 
/* 284 */             routeChgInfo = "变更工艺路线任务导入成功！";
           } else {
/* 288 */             List<String> listWronglineInfo = (List<String>)map.get("wrongLine");
/* 289 */             List<String> listWrongProcessItemId = new ArrayList<String>();
/* 290 */             int listSize = listWronglineInfo.size();
/* 291 */             for (int i = 0; i < listSize; i++) {
/* 292 */               String wronglineInfo = listWronglineInfo.get(i);
/* 293 */               listWrongProcessItemId.add(wronglineInfo.split(" ")[0] + "GY");
/* 294 */               chgDetailInfo.append(wronglineInfo).append("<br>");
             } 
/* 296 */             int formNum = forms.length;
/* 297 */             Object[] obj = new Object[1];
/* 298 */             obj[0] = Integer.valueOf(11);
/* 299 */             TCUserService service = session.getUserService();
/* 300 */             for (int j = 0; j < formNum; j++) {
/* 301 */               String form_of_item_id = "";
               try {
/* 303 */                 form_of_item_id = forms[j].getProperty("object_name").split("/")[0];
/* 304 */               } catch (TCException e1) {
/* 305 */                 e1.printStackTrace();
               } 
///* 307 */               if (!listWrongProcessItemId.contains(form_of_item_id))
//                 try {
///* 309 */                   service.call("openByPass", obj);
///* 310 */                   forms[j].setLogicalProperty("nhl8_ERPimpSucc", true);
///* 311 */                   service.call("closeByPass", obj);
///* 312 */                 } catch (TCException e) {
///* 313 */                   e.printStackTrace();
//                 }  
             } 
           } 
/* 318 */           if (taskResult.equals("3")) {
/* 319 */             routeChgInfo = "变更工艺路线任务导入错误，请至ERP修改！";
/* 320 */           } 
//					else if (taskResult.equals("4")) {
///* 321 */             routeChgInfo = "变更工艺路线部分数据导入失败，请修正后重新导入！";
///* 322 */           } else if (taskResult.equals("5")) {
///* 323 */             routeChgInfo = "变更工艺路线任务失败，请修正后重新导入！";
///* 324 */           } else if (taskResult.equals("6")) {
///* 325 */             routeChgInfo = "变更工艺路线任务导入失败，请修正！";
//           } 
}else {
	MessageBox.post("origin_searchItemRevForm查询器未找到表单属性nhl8_ERPTaskNum值为"+taskSN+"的表单","",MessageBox.INFORMATION);
}
         } else {
/* 328 */           routeChgInfo = "上次导入任务正在执行或排队，请稍候提交…";
         } 
       } else {
/* 331 */         String taskSN = map.get("taskSN").toString();
/* 332 */         chgDetailInfo.append("任务号：").append(taskSN).append("<br>");
					List<RouteCheckResult> routeCheckResults = new ArrayList<RouteCheckResult>();
					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");
					routeCheckResults = JSONArray.toList(jsonArray,RouteCheckResult.class);
					String errorInfo = ProcessImportReadXMLStr.loadAddElements(routeCheckResults);
///* 333 */         String errorInfo = ProcessImportReadXMLStr.xmlChgElements(session, xmlFile);
/* 334 */         chgDetailInfo.append(errorInfo);
/* 335 */         routeChgInfo = "变更工艺路线任务导入失败，请修正！";
       } 
//     } else {
///* 339 */       System.out.println(xmlFile + "文件未找到！");
//     } 
/* 342 */     ResultInfo result = new ResultInfo(routeChgInfo, chgDetailInfo.toString());
/* 343 */     return result;
   }
   
   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);
			   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("位置process");
//				   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;
   }
   
 }

