package com.connor.erp.searchImpResult;

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.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import com.connor.erp.processresource.EquipmentAcquiredFromERP.TCPreferenceUitl;
import com.connor.erp.toolkit.HttpUtil;
import com.connor.erpintegration.entity.ERPResultEntity;
import com.teamcenter.rac.aif.AbstractAIFOperation;
import com.teamcenter.rac.aif.AbstractAIFUIApplication;
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;

public class SearchImpResultOperation extends AbstractAIFOperation{
	private AbstractAIFUIApplication application;
	private TCSession session;
	private JTable table;
	private String user;
	private String fromDate;
	private String toDate;
	private String taskType;
	private String impResult;
	private SimpleDateFormat df = new SimpleDateFormat("yyyy-M-dd HH:mm");
	private static String erpPreference = "connor_tc_to_erp_url";
	
	public SearchImpResultOperation() {
		super();
	}
	
	public SearchImpResultOperation(AbstractAIFUIApplication application,TCSession session,JTable table,String user,String from,String to,String taskType,String impResult) {
		this.application = application;
		this.session = session;
		this.table = table;
		this.user = user;
		this.fromDate = from;
		this.toDate = to;
		this.taskType = taskType;
		this.impResult = impResult;
//		try {
//			this.fromDate = df.parse(from);
//			this.toDate = df.parse(to);
//		} catch (ParseException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
	}
	
	@Override
	public void executeOperation() throws Exception {
		// TODO Auto-generated method stub
		List<ERPResultEntity> list = getData();
		if(list.size()<1) {
			MessageBox.post("未查到相关任务记录","",MessageBox.INFORMATION);
			table.setModel(new DefaultTableModel());
			return;
		}
		String [][] data = new String[list.size()][9];
		for(int i =0;i<list.size();i++) {
			System.out.println("当前执行第"+i+"条记录");
			String impResult2 = list.get(i).getImpResult();
			if(impResult2!=null&&impResult2.trim().length()>0&&!"正在执行".equals(impResult2)) {
				System.out.println("导入结果不为空或正在执行");
				data[i][0] = i+"";
				data[i][1] = list.get(i).getItemId();
				data[i][2] = list.get(i).getTaskType();
				data[i][3] = list.get(i).getTaskNumber();
				
				data[i][4] = list.get(i).getImpDate();
				data[i][5] = list.get(i).getUserName();
				data[i][6] = list.get(i).getImpResult();
				data[i][7] = list.get(i).getErrorInfo();
				data[i][8] = list.get(i).getVersion();
			}else {
				System.out.println("导入结果为空或正在执行");
				String taskNumber = list.get(i).getTaskNumber();
				Map<String, String> requestMap = new HashMap<String, String>();
				requestMap.put("sid", taskNumber);
				requestMap.put("needParameter", "false");
				String[] result = doGet(requestMap, "result");
				String taskNumber2 = list.get(i).getTaskNumber();
				updateResult(result, taskNumber2);
				data[i][0] = i+"";
				data[i][1] = list.get(i).getItemId();
				data[i][2] = list.get(i).getTaskType();
				data[i][3] = list.get(i).getTaskNumber();
				data[i][4] = list.get(i).getImpDate();
				data[i][5] = list.get(i).getUserName();
				if(result!=null&&result.length>0&&result[0]!=null&&result[0].length()>0) {
					data[i][6] = result[0];
				}else {
					data[i][6] = "正在执行";
				}
				if(result!=null&&result.length>1) {
					System.out.println("errorinfo==========="+result[1]);
					data[i][7] = result[1];
				}else {
					data[i][7] = "";
				}
				data[i][8] = list.get(i).getVersion();
			}
		}
		String[] property = new String[] { "序号", "导入对象", "任务类型 ", "任务号", "导入时间", "导入人", "导入结果","错误信息","对象版本"};
		table.setModel(new DefaultTableModel(data,property));
	}
	
	public void updateResult(String[] result,String taskNumber) {
		Connection con = null;
		PreparedStatement stmt = null;
		String sql = null;
		if(result!=null&&result.length>0) {
			try {
				if(result.length>1) {
					sql = "update  connor_ERP_record set ImpResult=?,ErrorInfo=? where TaskNumber=?";//
					con = ConnectionFun();
					stmt = con.prepareStatement(sql);
					stmt.setString(1, result[0]);
					stmt.setString(2, result[1]);
					stmt.setString(3, taskNumber);
					stmt.executeUpdate();
				}else {
					sql = "update  connor_ERP_record set ImpResult=? where TaskNumber=?";//
					con = ConnectionFun();
					stmt = con.prepareStatement(sql);
					stmt.setString(1, result[0]);
					stmt.setString(2, taskNumber);
					stmt.executeUpdate();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				try {
					stmt.close();
					con.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public List<ERPResultEntity> getData() {
		List<ERPResultEntity> list = new ArrayList();

		ResultSet r = null;
		Connection con = null;
		PreparedStatement stmt = null;
		StringBuffer sb = new StringBuffer("select ItemId,TaskType,TaskNumber,to_char(ImpDate,'yyyy-fmmm-dd hh24:mi'),UserName,ImpResult,ErrorInfo,Rev_Id from connor_ERP_record where UserName=? and ImpDate>=to_date(?,'yyyy-fmmm-dd hh24:mi') and ImpDate<=to_date(?,'yyyy-fmmm-dd hh24:mi')");
		if(taskType!=null) {
			sb.append(" and TaskType=?");
		}
		if(impResult!=null) {
			sb.append(" and ImpResult=?");
		}
		sb.append(" order by ImpDate desc");
		String sql = sb.toString();
		try {
			con = ConnectionFun();
			stmt = con.prepareStatement(sql);
			stmt.setString(1, user);
			stmt.setString(2, fromDate);
			stmt.setString(3, toDate);
			if(taskType!=null) {
				stmt.setString(4, taskType);
				if(impResult!=null)stmt.setString(5, impResult);
			}else if(impResult!=null){
				stmt.setString(4, impResult);
			}
			System.out.println("sql===="+sql);
			r = stmt.executeQuery();
			while (r.next()) {
				ERPResultEntity entity = new ERPResultEntity();
//				System.out.println(r.getString(1));
				entity.setItemId(r.getString(1));
				entity.setTaskType(r.getString(2));
				entity.setTaskNumber(r.getString(3));
				entity.setImpDate(r.getString(4));
				entity.setUserName(r.getString(5));
				entity.setImpResult(r.getString(6));
				entity.setErrorInfo(r.getString(7));
				entity.setVersion(r.getString(8));
				list.add(entity);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				r.close();
				stmt.close();
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		return list;
	}
	
	
	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;

	}
	
	   public String[] doGet(Map<String, String> map, 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(map);
//		   List<CheckResult> checkResults =null;
		   Map<String, Object> resultMap = new HashMap<String, Object>();
		   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.doGet(url+"?"+param);
			   System.out.println("请求结果================"+response);
				   
			   JSONObject jsonObject = JSONObject.fromObject(response);
//			   System.out.println("json格式==============="+jsonObject);
			   JSONObject jsonObject2 = jsonObject.getJSONObject("cont");
//			   int status = jsonObject2.getInt("status");
			   String result = jsonObject2.getString("result");
			   String output = jsonObject2.getString("output");
			   
			   System.out.println("result============"+result);
			   System.out.println("output============"+output);
			   if(result.equals("0"))return new String[] {"正在执行"};
			   else if(result.equals("1"))return new String[] {"成功"};
			   else if(result.equals("2"))return new String[] {"警告",output};
			   else if(result.equals("3")) {
				   if(output!=null&&output.length()>=14&&output.substring(0,14).equals("{\"checkResult\"")) {
					   JSONObject json = JSONObject.fromObject(output);
					   JSONArray jsonArray = json.getJSONArray("checkResult");
					   StringBuffer sb = new StringBuffer();
					   for(int i =0;i<jsonArray.size();i++) {
						  JSONObject fromObject = JSONObject.fromObject(jsonArray.get(i));
						  String itemID = fromObject.getString("item");
						  String uom = fromObject.getString("uom");
						  boolean existNiNHL = fromObject.getBoolean("existInNHL");
						  boolean existNiNSC = fromObject.getBoolean("existInNSC");
						  boolean existNiNBJ = fromObject.getBoolean("existInNBJ");
						  boolean existNiNSJ = fromObject.getBoolean("existInNSJ");
						  boolean uomExist = fromObject.getBoolean("uomExist");
						  boolean canImport = fromObject.getBoolean("canImport");
						  if(canImport) continue;
						  else {
							if(existNiNHL)sb.append(itemID+"在主组织中已存在;");
							if(existNiNSC)sb.append(itemID+"在生产组织中已存在;");
							if(existNiNBJ)sb.append(itemID+"在备件组织中已存在;");
							if(existNiNSJ)sb.append(itemID+"在非生产组织中已存在;");
							if(!uomExist)sb.append(itemID+"的单位["+uom+"]不存在;");
						  }
					   }
					   output = sb.toString();
				   }
				   return new String[] {"错误",output};
			   }
				   
//			   System.out.println("cont==============="+jsonObject2);
//			   JSONObject jsonObject3 = jsonObject2.getJSONObject("output");
				   
//			   resultMap = (Map<String, Object>)JSONObject.toBean(jsonObject3,Map.class);
			   
			   
			   
		   } catch (Exception e1) {
			   // TODO Auto-generated catch block
			   e1.printStackTrace();
		   }
		   return null;
	   }
}
