package com.platform.service;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.platform.entities.GatherOracleInfo;
import com.platform.entities.OracleConnectorParams;
import com.platform.oracle.OracleConnector;
import com.platform.utils.Configs;
import com.platform.utils.FileOperateHelper;

public class OracleExtractHelper {

	private OracleConnector oConnector;

	/**
	 * 判断dblink是否已经存在
	 * 
	 * @param conn
	 * @param linkName
	 *            dblink的名称
	 * @return
	 */
	private boolean hasSameNameDBLink(Connection conn, String linkName) {
		boolean flag = false;
		String sql = "SELECT * FROM ALL_DB_LINKS WHERE DB_LINK=" + linkName;
		ResultSet rSet = oConnector.getSQLExecResultSet(conn, sql);
		try {
			rSet.last();
			if (rSet.getRow() > 0)
				flag = true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return flag;
	}

	/**
	 * 创建dblink
	 * 
<<<<<<< HEAD
<<<<<<< HEAD
	 * @param conn
	 * @param oc
=======
	 * @param conn 汇总库的连接
	 * @param oc 采集库
>>>>>>> 355b6e47a4fa8d058029ec939fe4fefdaa751275
=======
	 * @param conn 汇总库的连接
	 * @param oc 采集库
>>>>>>> web_backend_develope
	 *            dblink连接参数实体
	 */
	public void createDBLink(Connection conn, OracleConnectorParams oc) {
		String linkName = "LinkTo" + oc.getName();
		String sql = "CREATE PUBLIC DATABASE LINK "
				+ linkName
				+ " CONNECT TO "
				+ oc.getUser()
				+ " IDENTIFIED BY "
				+ oc.getPassword()
				+ " USING '(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = "
				+ oc.getIp() + ")(PORT = " + oc.getPort()
				+ ")))(CONNECT_DATA =(SERVICE_NAME =" + oc.getDatabaseName()
				+ ")))';";
		if (null != oc) {
			if (hasSameNameDBLink(conn, linkName)) { // 如果dblink已经存在,先删除dblink，在创建dblink
				String deleteSql = "DROP PUBLIC DATABASE LINK LinkTo"
						+ linkName;
				FileOperateHelper
						.fileWrite(
								Configs.EXTRACT_LOG_LOCALTION + oc.getName(),
								deleteSql);
				if (oConnector.execOracleSQL(conn, deleteSql)) {
					FileOperateHelper.fileWrite(Configs.EXTRACT_LOG_LOCALTION
							+ oc.getName(), sql);
					oConnector.execOracleSQL(conn, sql);
				} else {
					Configs.CONSOLE_LOGGER.error("删除已有的DBLink失败,无法创建新的DBLink!");
					FileOperateHelper.fileWrite(Configs.EXTRACT_LOG_LOCALTION
							+ oc.getName(), "删除已有的DBLink失败,无法创建新的DBLink!");
				}

			} else {
				// 否则，创建dblink
				oConnector.execOracleSQL(conn, sql);
				FileOperateHelper.fileWrite(
						Configs.EXTRACT_LOG_LOCALTION + oc.getName(), sql);
			}
		}
	}

	/**
	 * 创建表空间
	 * 
	 * @param conn 汇总库连接
	 * @param oc 汇总库信息
	 * @return
	 */
	public boolean createTableSpace(Connection conn, GatherOracleInfo oc) {
		String tmpSql = "select TABLESPACE_NAME from dba_tablespaces where TABLESPACE_NAME = '"
				+ Configs.GATHER_TABLESPACE_NAME + "'";
		if (oConnector.execOracleSQL(conn, tmpSql)) {
			return true;
		} else {
			String sql = "create tablespace " + Configs.GATHER_TABLESPACE_NAME
					+ " datafile '" + Configs.GATHER_TABLESPACE_PATH
					+ Configs.GATHER_TABLESPACE_NAME + ".dbf"
					+ "' size 512M autoextend on next 512M maxsize unlimited";
			return oConnector.execOracleSQL(conn, sql);
		}
	}

	/**
	 * 创建用户并授权
	 * 
	 * @param conn 汇总库连接
	 * @param oc  汇总库信息
	 */
	public void createUser(Connection conn, GatherOracleInfo oc) {
		String strTUser = oc.getName() + Configs.TABLE_SUFFIX;
		String sql = "Create user " + strTUser + " default tablespace "
				+ Configs.GATHER_TABLESPACE_NAME + " identified by "
				+ Configs.GATHER_TABLE_PASSWORD;
		String grantSql = "grant connect, resource, dba to " + strTUser;
		oConnector.execOracleSQL(conn, sql);
		oConnector.execOracleSQL(conn, grantSql);
	}

	/**
	 * 执行汇总操作
	 * 
	 * @param conn 汇总库连接
	 * @param oc 采集库
	 */
	public void extractColleDB(Connection conn, OracleConnectorParams oc) {
		String strTUser = oc.getName() + Configs.TABLE_SUFFIX;
		String sql = "SELECT 'create table "
				+ strTUser
				+ ".J'|| substr(t.OWNER||'_'||t.TABLE_NAME,0,29)||' as select * from '||t.OWNER||'.'||t.TABLE_NAME||"
				+ "'@linkTo"
				+ oc.getName()
				+ ";' FROM dba_tables@linkTo"
				+ oc.getName()
				+ " t WHERE t.TABLESPACE_NAME NOT IN ('SYSTEM','SYSAUX')"
				+ " and t.owner||t.table_name not in (select owner||table_name from dba_tables@linkTo"
				+ oc.getName() + " where 'data_type'='CLOB')";
		ResultSet rsSet = oConnector.getSQLExecResultSet(conn, sql);
		try {
			while (rsSet.next()) {
				String resultSql = rsSet.getString(0);
				oConnector.execOracleSQL(conn, resultSql);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
