package com.connor.erp.processresource.EquipmentAcquiredFromERP;

import com.connor.erp.toolkit.HttpUtil;
import com.connor.erp.toolkit.UtilApi;
import com.connor.erpintegration.entity.DepResEntity;
//import com.origin.tcerp.conn.PlmErpIntegration;
import com.teamcenter.rac.aif.AbstractAIFCommand;
import com.teamcenter.rac.aif.AbstractAIFUIApplication;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentFolder;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCPreferenceService;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;

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

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

//import javax.activation.MailcapCommandMap;

public class EquipmentAcquiredFromERPCommand extends AbstractAIFCommand {
	private TCSession session;

	private AbstractAIFUIApplication application;

	private TCComponentFolder targetFolder;
	public String erpPreference = "connor_tc_to_erp_url";
	private String svr = "DepRes";

	public EquipmentAcquiredFromERPCommand(TCSession pSession, AbstractAIFUIApplication app,
			TCComponentFolder ptargetFolder) {
		this.session = pSession;
		this.application = app;
		this.targetFolder = ptargetFolder;
		callERPDll();
	}

	@SuppressWarnings("deprecation")
	private void callERPDll(){
		TCComponent[] components;
		Vector<String> vecNo = new Vector<String>();
		try {
			components = session.search("零组件 ID", new String[] { "零组件 ID" },
					new String[] { "NHLM*" });
			int componentLen = components.length;
			for (int i = 0; i < componentLen; i++) {
				try {
					String item_id = components[i].getProperty("item_id");
					vecNo.add(item_id.substring(4));
				} catch (TCException e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		String user_id = "";
		try {
			user_id = this.session.getUser().getProperty("user_id");
		} catch (TCException e) {
			e.printStackTrace();
		}
		List<DepResEntity> depResList = doGet();
//    String xmlFilePath = System.getProperty("java.io.tmpdir") + File.separator + user_id + "_" + UtilApi.getCurrentTime() + "_query_device.xml";
//    String result = UtilApi.getErrorInfoFromCode(PlmErpIntegration.getAllDeviceInfo(xmlFilePath));
//    if (!result.equals("成功")) {
//      MessageBox.post(this.application.getDesktop().getShell(), result, "验证出现错误", 1);
//      return;
//    } 
//    ReadXMLStr doc = new ReadXMLStr();
//    File xmlFile = new File(xmlFilePath);
		Vector<String> vecCanImp = new Vector<String>();
		if (depResList!=null&&depResList.size()>0) {
			for(DepResEntity t:depResList) {
				if(!vecNo.contains(t.getDEPARTMENT_CODE()))
				vecCanImp.add(t.getDEPARTMENT_CODE()+","+t.getDESCRIPTION());
			}
//  	if (xmlFile.exists()) {
//      List<String> infoList = doc.xmlElements(xmlFile, "ERPFramework|SegmentInfo");
//      int listSize = infoList.size();
//      for (int j = 0; j < listSize; j++) {
//        String[] str = ((String)infoList.get(j)).split("%#%");
//        String resource_code = str[1].split("=")[1];
//        if (!vecNo.contains(resource_code))
//          vecCanImp.add(String.valueOf(resource_code) + "," + str[2].split("=")[1]); 
//      } 
		} else {
			MessageBox.post("ERP中未找到设备","警告",MessageBox.WARNING);
//      MessageBox.post(this.application.getDesktop().getShell(), String.valueOf(xmlFilePath) + "文件未找到！！", "警告", 4);
			return;
		}
		if (vecCanImp.size() == 0) {
			MessageBox.post(this.application.getDesktop().getShell(), "未找到可以导入PLM系统的设备！！", "警告", 4);
			return;
		}
		setRunnable((Runnable) new EquipmentAcquiredFromERPDialog(this.session, this.targetFolder, vecCanImp));
	}

	private List<DepResEntity> doGet() {
		HashMap<String, String> preferenceHashMap = TCPreferenceUitl.getPreferenceHashMap(session, TCPreferenceService.TC_preference_site, erpPreference);
		String url = preferenceHashMap.get("url");
		String token = preferenceHashMap.get("token");
		List<DepResEntity> depResList = null;
		try {
			System.out.println("开始发送请求");
			String 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==========="+param);
			String response = HttpUtil.doGet(url+"?"+param);
			System.out.println("请求结果================"+response);
			
			JSONObject jsonObject = JSONObject.fromObject(response);
			System.out.println("json格式==============="+jsonObject);
//			Map<String, Class> classMap = new HashMap<String, Class>();
//			classMap.put("DepRes", DepResEntity.class);
//			classMap.put("cont", DepResListClass.class);
			JSONObject jsonObject2 = jsonObject.getJSONObject("cont");
			System.out.println("cont==============="+jsonObject2);
			JSONArray jsonArray = jsonObject2.getJSONArray("DepRes");
//			for(int i=0;i<jsonArray.size();i++) {
//				System.out.println("code=================="+jsonArray.getJSONObject(i).getString("DEPARTMENT_CODE"));
//				System.out.println("description==========="+jsonArray.getJSONObject(i).getString("DESCRIPTION"));
//			}
//			DepResTemp depResTemp = (DepResTemp) JSONObject.toBean(jsonObject2,DepResTemp.class,classMap);
//			depResList = depResTemp.getDepRes();
			
			
			depResList = JSONArray.toList(jsonArray, DepResEntity.class);
//			Map<String, String> map2 = (Map<String,String>)jsonObject2.toBean(jsonObject2, Map.class);
//			String depRes = map2.get("DepRes");
//			List<DepRes> depResList = JSONArray.fromObject(depRes);
//			System.out.println("位置7");
//			for(DepResEntity dep:depResList) {
//				System.out.println("DEPARTMENT_CODE============"+dep.getDEPARTMENT_CODE());
//				System.out.println("DEPARTMENT_ID============"+dep.getDEPARTMENT_ID());
//				System.out.println("DESCRIPTION============"+dep.getDESCRIPTION());
//			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return depResList;
	}
}
