package com.connor.bhdz.pdm.drawingToCapp;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DecimalFormat;
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.Vector;

//import com.connor.dfl.plm.dfl027.ChangeOwnerbean;
//import com.connor.dfl.plm.dfl038.ChangeBean;
//import com.connor.dfl.plm.forms.ChangeOrderBean;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;

public class DataBaseControl {

	/** ************************数据库类调用:声明部分*********************************** */
	/**
	 * kelsen声明部分 ....
	 */
	Connection conn;

	ResultSet rs;

	PreparedStatement pstmt;

	Statement stmt;

	String  strSQLQuery;

	public String str_Information = "";

	private String strDriver = "oracle.jdbc.driver.OracleDriver";
	private String strUrl = "";
	private String strUserName = "";
	private String strPassword = "";

	/**
	 * 构造器
	 */
	public DataBaseControl(String strDriver, String strUrl, String strUserName,
			String strPassword) {
		// this.strDriver ="oracle.jdbc.driver.OracleDriver";//驱动
		// this.strUrl = "jdbc:oracle:thin:@127.0.0.1:1521:tc";//连接路径
		// this.strUserName = "infodba";//数据库用户
		// this.strPassword = "infodba";//数据库密码


		this.strDriver = strDriver; // "oracle.jdbc.driver.OracleDriver";//驱动
		this.strUrl = strUrl; // "jdbc:oracle:thin:@127.0.0.1:1521:tceng";//连接路径
		this.strUserName = strUserName; // "infodba";//数据库用户
		this.strPassword = strPassword; // "infodba";//数据库密码

		// 加载驱动
		try {
			Class.forName(strDriver);// 通过反射加载驱动到内存
		} catch (ClassNotFoundException cnfe) {
			cnfe.printStackTrace();
		}
		// try {
		// Class.forName("org.objectweb.rmijdbc.Driver").newInstance();
		// } catch (InstantiationException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// } catch (IllegalAccessException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// } catch (ClassNotFoundException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
	}

	/**
	 * 构造器
	 */
	public DataBaseControl(TCSession session) {

		String[] stringArray = session.getPreferenceService().getStringArray(4,
				"DFL2_SQL_Connect");
		if (stringArray != null && stringArray.length == 3) {
			strUrl = "jdbc:oracle:thin:@" + stringArray[0];
			strUserName = stringArray[1];
			strPassword = stringArray[2];
		} else {
			MessageBox.post("未配置DFL2_SQL_Connect首选项，无法获得连接信息!", "错误",
					MessageBox.ERROR);
		}

		// 加载驱动
		try {
			Class.forName(strDriver);// 通过反射加载驱动到内存
		} catch (ClassNotFoundException cnfe) {
			cnfe.printStackTrace();
		}

	}
	/**
	 * 构造器
	 */
	public DataBaseControl(TCSession session,String connect) {

		String[] stringArray = session.getPreferenceService().getStringArray(4,
				connect);
		if (stringArray != null && stringArray.length == 3) {
			strUrl = "jdbc:oracle:thin:@" + stringArray[0];
			strUserName = stringArray[1];
			strPassword = stringArray[2];
		} else {
			MessageBox.post("未配置"+connect+"首选项，无法获得连接信息!", "错误",
					MessageBox.ERROR);
		}

		// 加载驱动
		try {
			Class.forName(strDriver);// 通过反射加载驱动到内存
		} catch (ClassNotFoundException cnfe) {
			cnfe.printStackTrace();
		}

	}

	/**
	 * 表更新
	 * 
	 * @param strSQLQuery
	 */
	public void dbModify(String strSQLQuery) {

		openDataBase();

		try {
			stmt = conn.createStatement();
			stmt.executeUpdate(strSQLQuery);
		} catch (SQLException sqle2) {
			sqle2.printStackTrace();
		}

		closeDataBase();
	}

	/**
	 * 表查询
	 * 
	 * @param strSQLQuery
	 * @return
	 */
	public ResultSet dbQuery(String strSQLQuery) {
		ResultSet rs_result = null;
		if (conn == null)
			openDataBase();
		try {
			stmt = conn.createStatement();
			rs_result = stmt.executeQuery(strSQLQuery);

		} catch (SQLException sqle2) {
			sqle2.printStackTrace();
		}
		return rs_result;
	}

	/**
	 * 表查询2
	 * 
	 * @param strSQLQuery
	 * @return
	 */
	public ResultSet dbQuery2(String strSQLQuery, Object[] strs) {
		ResultSet rs_result = null;
		if (conn == null)
			openDataBase();
		try {
			// stmt = conn.createStatement();
			PreparedStatement ps = conn.prepareStatement(strSQLQuery);
			for (int i = 0; i < strs.length; i++) {
				ps.setObject(i + 1, strs[i]);
			}
			rs_result = ps.executeQuery();

		} catch (SQLException sqle2) {
			sqle2.printStackTrace();
		}
		return rs_result;
	}
	/**
	 * 表查询3
	 * 
	 * @param strSQLQuery
	 * @return
	 */
	public ResultSet dbQuery3(String strSQLQuery) {
		ResultSet rs_result = null;
		if (conn == null)
			openDataBase();
		try {
			stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
			rs_result = stmt.executeQuery(strSQLQuery);

		} catch (SQLException sqle2) {
			sqle2.printStackTrace();
		}
		return rs_result;
	}


	/**
	 * 表更新2
	 * 
	 * @param strSQLQuery
	 */
	public void dbModify2(String strSQLQuery, Object[] strs) {

		openDataBase();

		try {
			// stmt = conn.createStatement();
			PreparedStatement ps = conn.prepareStatement(strSQLQuery);
			for (int i = 0; i < strs.length; i++) {
				ps.setObject(i + 1, strs[i]);
			}
			ps.executeUpdate();
		} catch (SQLException sqle2) {
			sqle2.printStackTrace();
		}

		closeDataBase();
	}

	/**
	 * 开启链接
	 * 
	 */
	public void openDataBase() {
		try {
			// this.strUrl="jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.1.29)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=tcprod)))";
			if (conn == null || conn.isClosed())
				conn = DriverManager.getConnection(strUrl, strUserName,
						strPassword);
		} catch (SQLException sqle) {
			sqle.printStackTrace();
			MessageBox.post("数据库连接错误" + sqle.getMessage(), "错误", 1);
		}
	}

	/**
	 * 关闭数据库链接
	 * 
	 */
	public void closeDataBase() {
		try {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException sqlec) {
					sqlec.printStackTrace();
				}
			}
			if (stmt != null) {
				try {
					stmt.close();
				} catch (SQLException sqlec) {
					sqlec.printStackTrace();
				}
			}
			if (conn != null && !conn.isClosed()) {
				try {
					conn.close();
				} catch (SQLException sqlecon) {
					sqlecon.printStackTrace();
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 将语句传入数据库进行查询 查询得到的结果集的每一条记录封装于一个HashMap,key以表字段名命名
	 * 查询出多条记录代表Vector对象中有多少个HasnMap元素
	 * 
	 * @param strSQLQuery
	 * @return
	 * @author xuk
	 */
	public Vector orgQuery(String strSQLQuery) {
		openDataBase();
		Vector v_result = new Vector();
		try {
			ResultSet rs_get = dbQuery(strSQLQuery);
			// System.out.println("RS_GET:"+rs_get);
			if (rs_get != null) {
				ResultSetMetaData metaData = rs_get.getMetaData();

				int i_ColumnCount = metaData.getColumnCount();
				// System.out.println("i_ColumnCount:"+i_ColumnCount);
				while (rs_get.next()) {
					// System.out.println("【BJZJ2】"+rs_get.getString("BJZJ2"));;
					HashMap<String, String> hm_unit = new HashMap<String, String>();
					for (int i = 1; i <= i_ColumnCount; i++) {
						hm_unit.put(metaData.getColumnName(i),
								rs_get.getString(i));
						// System.out.println("metaData.getColumnName(i):"+metaData.getColumnName(i));
						// System.out.println("rs_get.getString(i):"+rs_get.getString(i));
					}
					v_result.add(hm_unit);
				}
			} else {
				str_Information = "【" + strSQLQuery + "】" + "查询的结果集为空\n";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return v_result;
	}


	public String getTaskIdea(String uid)
			throws Exception {
		openDataBase();
		String query = "select IDEA from PLM_Perform_Task where PUID= ?";
		// 查询该id在数据库中的内容
		ResultSet rs = dbQuery2(query, new Object[] { uid});
		String taskIdea = "";
		if (rs.next()) {
			taskIdea = rs.getString(1);
			System.out.println("taskIdea=" + taskIdea);
		}

		closeDataBase();

		return taskIdea;

	}
	public void setTaskIdea(String uid,String idea)
			throws Exception {
		openDataBase();
		String query = "select IDEA from PLM_Perform_Task where PUID= ?";
		// 查询该id在数据库中的内容
		ResultSet rs = dbQuery2(query, new Object[] { uid});
		if(rs.next()) {
			String upin = "update PLM_Perform_Task set  IDEA= ?  where PUID= ?";
			dbModify2(upin, new Object[] { idea, uid });
		}else {
			String upin = "insert into PLM_Perform_Task(PUID,IDEA) values ( ? , ?  )";
			dbModify2(upin, new Object[] { uid, idea });
		}
		closeDataBase();

	}

	/**
	 * 获得流水码
	 * 
	 * @param type
	 *            流水码类型
	 * @param prefix
	 *            前缀
	 * @param col
	 *            流水码位数 如4位"0000"
	 * @return
	 * @throws Exception
	 */
	public String getNewCode(String type, String prefix, String col)
			throws Exception {
		openDataBase();
		String query = "select PREFIX,LSH from PLM_LSH where PLMTYPE= ? and PREFIX= ?";
		// 查询该id在数据库中的内容
		ResultSet rs = dbQuery2(query, new Object[] { type, prefix });
		String lshstr = col;
		String pre = "";
		String lsh = "";
		if (rs.next()) {
			pre = rs.getString(1);
			lsh = rs.getString(2);
			System.out.println("sspre=" + pre);
			System.out.println("sslsh=" + lsh);
			if ("".equals(lsh)) {
				throw new Exception("流水码为空！");
			}
			int ls = Integer.parseInt(lsh) + 1;// 新的流水码数
			lshstr = ls + "";
			if (col != null) {
				DecimalFormat df = new DecimalFormat(col);
				lshstr = df.format(ls);
			}
			String upin = "update PLM_LSH set  LSH= ?  where PLMTYPE= ? and PREFIX= ? ";
			dbModify2(upin, new Object[] { lshstr, type, prefix });
		} else {
			String upin = "insert into PLM_LSH(PLMTYPE,PREFIX,LSH) values ( ? , ? , ? )";
			dbModify2(upin, new Object[] { type, prefix, lshstr });

		}

		closeDataBase();
		String newId = prefix + lshstr;

		return newId;

	}

	/*
	 * //获取变更单信息 public List<ChangeBean> getChangeMesg(String product,String
	 * time1,String time2) throws SQLException { List<ChangeBean> list = new
	 * ArrayList<ChangeBean>(); if("全部".equals(product)) { product = ""; } String
	 * sql =
	 * "select APPLYNAME,OBJECTCODE,APPLYDATE,PRODUCTNAME,PROJECTMODEL,CLIENTNAME,WAREHOUSECODE,NOTIFYEMERGENCYPROCEDURES,TZGGLX,PRODUCTDEPARTMENT,DUTYDEPARTMENT,DUTYMAN,CHANGETYPE,PRODUCTTYPE,ERRORTYPE,PRICEBOOKING,SALSECLASSIFY,ISNOTPRODUCTLOSS,XMJD,RECEIVECLASSIFY,DRAWINGTO,PROJECTCODE,CHANGEREASON,ACCOUNTSET,case when REASONDETAIL is null then changereason else REASONDETAIL end as REASONDETAIL from  DFL_CHANGEFORM  where PRODUCTDEPARTMENT like '%"
	 * +product+"%'";// SimpleDateFormat df = new
	 * SimpleDateFormat("yyyy-M-d HH:mm"); openDataBase();
	 * System.out.println("sql============"+sql); ResultSet rs = dbQuery(sql);
	 * while(rs.next()){ try { String dateStr = rs.getString(3);
	 * System.out.println("date========"+rs.getString(3)); if(dateStr == null) {
	 * continue; } Date date = df.parse(rs.getString(3)); Date date1 =
	 * df.parse(time1); Date date2 = df.parse(time2); if(date.after(date2) &&
	 * date.before(date1)) { System.out.println("date2========"+rs.getString(3)); }
	 * if(date.after(date1) && date.before(date2)) { ChangeBean bn = new
	 * ChangeBean(); bn.setApplyName(rs.getString(1));
	 * bn.setApplyDate(rs.getString(3)); bn.setProjectCode(rs.getString(22));
	 * bn.setClientNae(rs.getString(6)); bn.setProductName(rs.getString(4));
	 * bn.setProjectModel(rs.getString(5)); bn.setChangeType(rs.getString(13));
	 * bn.setProductType(rs.getString(14)); bn.setErrorType(rs.getString(15));
	 * bn.setDutyDepartment(rs.getString(11)); bn.setDutyMan(rs.getString(12));
	 * bn.setChangeReason(rs.getString(23)); bn.setSalseClassify(rs.getString(17));
	 * bn.setPriceBooking(rs.getString(16));
	 * bn.setIsNotProductLoss(rs.getString(18));
	 * bn.setReceiveClassify(rs.getString(20));
	 * bn.setWarehouseCode(rs.getString(7)); bn.setAccountSet(rs.getString(24));
	 * bn.setNotifyEmergencyProcedures(rs.getString(8));
	 * bn.setDrawingTo(rs.getString(21)); bn.setChangeListCode(rs.getString(2));
	 * bn.setTZChangeType(rs.getString(9));
	 * bn.setSUOSU_ProductDepartment(rs.getString(10));
	 * bn.setProjectState(rs.getString(19)); bn.setReasonDetail(rs.getString(25));
	 * list.add(bn); } } catch (ParseException e) { // TODO Auto-generated catch
	 * block e.printStackTrace(); }
	 * 
	 * } closeDataBase(); return list; }
	 */
	/**
	 * 获得流水码
	 * 
	 * @param type
	 *            流水码类型
	 * @param prefix
	 *            前缀
	 * @param col
	 *            流水码位数 如4位"0000"
	 * @return
	 * @throws Exception
	 */

	/*
	 * public String getNewCode(String type,CodeBean selCodeBean) throws Exception {
	 * String prefix = selCodeBean.getCode(); String col = selCodeBean.getNum();
	 * String min = selCodeBean.getMin(); String max = selCodeBean.getMax();
	 * openDataBase(); String query =
	 * "select PREFIX,LSH from PLM_LSH where PLMTYPE= ? and PREFIX= ?"; //
	 * 查询该id在数据库中的内容 ResultSet rs = dbQuery2(query, new Object[] { type, prefix });
	 * String lshstr = col; String pre = ""; String lsh = ""; if (rs.next()) { pre =
	 * rs.getString(1); lsh = rs.getString(2); System.out.println("sspre=" + pre);
	 * System.out.println("sslsh=" + lsh); if ("".equals(lsh)) { throw new
	 * Exception("流水码为空！"); } int ls = Integer.parseInt(lsh) + 1;// 新的流水码数 int minls
	 * = Integer.parseInt(min); int maxls = Integer.parseInt(max); if (minls>ls) {
	 * ls=minls; } if (ls>maxls) { System.out.println("错误:流水码最已超过最大值"); return
	 * "MAXERR"; } lshstr = ls + ""; if (col != null) { DecimalFormat df = new
	 * DecimalFormat(col); lshstr = df.format(ls); } String upin =
	 * "update PLM_LSH set  LSH= ?  where PLMTYPE= ? and PREFIX= ? ";
	 * dbModify2(upin, new Object[] { lshstr, type, prefix }); } else { if (col !=
	 * null) { int minls = Integer.parseInt(min); DecimalFormat df = new
	 * DecimalFormat(col); lshstr = df.format(minls); } String upin =
	 * "insert into PLM_LSH(PLMTYPE,PREFIX,LSH) values ( ? , ? , ? )";
	 * dbModify2(upin, new Object[] { type, prefix, lshstr }); }
	 * 
	 * closeDataBase(); String newId = prefix + lshstr;
	 * 
	 * return newId;
	 * 
	 * }
	 */
	/**
	 * 获取最大流水码
	 * 
	 */
	/*
	 * public String getMaxCode(String type,CodeBean selCodeBean)throws Exception {
	 * String prefix = selCodeBean.getCode(); String col = selCodeBean.getNum();
	 * String min = selCodeBean.getMin(); String max = selCodeBean.getMax();
	 * 
	 * openDataBase(); //String query =
	 * "select * from (select * from pitem where pitem_id like '"
	 * +prefix+"%' order by pitem_id desc) where rownum<=1"; String query =
	 * "select LSH from PLM_LSH where PREFIX = prefix"; // 查询该id在数据库中的内容 ResultSet
	 * rs = dbQuery(query); String lshstr = col; String lsh = ""; if (rs.next()) {
	 * lsh = rs.getString(0); System.out.println("sslsh=" + lsh); if
	 * ("".equals(lsh)) { throw new Exception("流水码为空！"); } lsh = lsh.substring(6);
	 * int ls = Integer.parseInt(lsh) + 1;// 新的流水码数 lshstr = ls + "";
	 * System.out.println("lshstr=" + lshstr); if (col != null) { DecimalFormat df =
	 * new DecimalFormat(col); lshstr = df.format(ls); } } String upin =
	 * "update PLM_LSH set  LSH= ?  where PLMTYPE= ? and PREFIX= ? ";
	 * dbModify2(upin, new Object[] { lshstr, type, prefix }); closeDataBase();
	 * String newId = prefix + lshstr; return newId; }
	 */

	/**
	 * 更新模具下机数
	 * @param v3
	 * @param v16
	 * @param time
	 * @param user
	 * @throws Exception
	 */
	public void setSqlConn(String v3, String v16, String time, String user)
			throws Exception {
		openDataBase();
		//		WF_MJID   varchar2(200),--编码
		//		WF_YXJ   varchar2(200),--已下机数
		//		WF_DATE   varchar2(200),--上传日期
		//		WF_USER   varchar2(200),--上传人员
		String query = "select WF_MJID from WF_MJ_XJ_T where WF_MJID = ? ";
		// 查询该id在数据库中的内容
		ResultSet rs = dbQuery2(query, new Object[] {v3});
		String wfmjid = "";
		if (rs.next()) {
			System.out.println("更新");
			wfmjid = rs.getString(1);
			System.out.println("wfmjid=" + wfmjid);
			String upup = "UPDATE  WF_MJ_XJ_T set WF_YXJ = ? ,WF_DATE= ?, WF_USER = ? WHERE WF_MJID = ? ";
			dbModify2(upup, new Object[] {v16, time, user ,v3});

		} else {
			System.out.println("插入");
			System.out.println("wfmjid=" + v3);
			String upin = "insert into WF_MJ_XJ_T(WF_MJID,WF_YXJ,WF_DATE,WF_USER) values ( ?,? , ? , ? )";
			dbModify2(upin, new Object[] {v3, v16, time, user});

		}

		closeDataBase();

		return ;

	}

	/**
	 * 获得呆滞库存
	 * 
	 * @param value
	 *           查询条件
	 * @param sql
	 *            查询语句
	 * @return
	 * @throws Exception
	 */
	/*
	 * public List<ChangeOwnerbean> getRecord(String sql) throws Exception {
	 * List<ChangeOwnerbean> list=new ArrayList<>(); openDataBase(); //
	 * 查询该id在数据库中的内容 ResultSet rs = dbQuery(sql); while (rs.next()) {
	 * ChangeOwnerbean bean = new ChangeOwnerbean();
	 * bean.setZhangt(rs.getString(1)); bean.setId(rs.getString(2));
	 * bean.setCustomerName(rs.getString(3)); bean.setSpec(rs.getString(4));
	 * bean.setUnit(rs.getString(5)); bean.setCangk(rs.getString(6));
	 * bean.setCangkName(rs.getString(7)); bean.setNum(rs.getString(8));
	 * bean.setLocation(rs.getString(9)); list.add(bean); } closeDataBase(); return
	 * list; }
	 */
	//	public List<ChangeOwnerbean> getRecord2(String value,String zhangT,String cangK,String sql)
	//			throws Exception {
	//		List<ChangeOwnerbean> list=new ArrayList<>();
	//		openDataBase();
	//		// 查询该id在数据库中的内容
	//		ResultSet rs = dbQuery2(sql, new Object[] {value,zhangT,cangK});
	//		while (rs.next()) {
	//			ChangeOwnerbean  bean = new ChangeOwnerbean();
	//			bean.setId(rs.getString(1));
	//			bean.setCustomerName(rs.getString(2));
	//			bean.setSpec(rs.getString(3));
	//			bean.setZhangt(rs.getString(4));
	//			bean.setCangk(rs.getString(5));
	//			bean.setNum(rs.getString(6));
	//			bean.setUnit(rs.getString(7));
	//			list.add(bean);
	//		}
	//		closeDataBase();
	//		return list;
	//	}

	public String getNum(Object[] values)
			throws Exception {
		openDataBase();
		// 查询该id在数据库中的内容
		String sql = "select NUM from DFL_OLD_ITEM where ITEM_ID= ? and ZHANGTAO= ? and WAREHOUSE= ?";
		String num = "";
		ResultSet rs = dbQuery2(sql, values);
		if (rs.next()) {
			num = rs.getString(1);
		}
		closeDataBase();
		return num;
	}

	public double  getNums(String sql)
			throws Exception {
		openDataBase();
		// 查询该id在数据库中的内容
		double nums = 0;
		ResultSet rs = dbQuery(sql);
		if (rs.next()) {
			nums = rs.getInt(1);
		}
		closeDataBase();
		return nums;
	}
	/**
	 * 单例测试
	 * 
	 * @param args
	 */
	public static void main(String args[]) {
		try {

			String str_DataBaseDriver = "oracle.jdbc.driver.OracleDriver";
			String str_URL = "jdbc:oracle:thin:@localhost:1521:tc12";
			String str_UserName = "infodba";
			String str_Password = "infodba";
			DataBaseControl dbc = new DataBaseControl(str_DataBaseDriver,
					str_URL, str_UserName, str_Password);
			// dbc.openDataBase();
			System.out.println("连接成功");
			// dbc.stmt = dbc.conn.createStatement();
			// String sql = "select * from PLM_LSH";
			// Vector rs_result = dbc.orgQuery(sql);
			// for (int i = 0; i < rs_result.size(); i++) {
			// HashMap<String, String> map = (HashMap<String, String>)
			// rs_result.get(i);
			//
			// for (Map.Entry<String, String> entry: map.entrySet()) {
			// System.out.println(entry.getKey()+"---"+entry.getValue());
			// }
			// }
			String newid = dbc.getNewCode("PLMITEMID", "pz", "0000");
			System.out.println(newid);
			// dbc.closeDataBase();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
