package com.dev.swms.server.service.sequence.pojo;

import java.math.BigInteger;
import java.sql.CallableStatement;
import java.sql.Date;
import java.sql.SQLException;

import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.SessionFactoryUtils;

import com.dev.swms.server.service.sequence.SwmsSequenceDao;

public class HibernateSwmsSequenceDao extends HibernateDaoSupport implements
		SwmsSequenceDao {
    
	public Long getSequenceBySP(final String keyName) {
		String DB = "";
		try {
			DB = SessionFactoryUtils.getDataSource(this.getHibernateTemplate().getSessionFactory()).getConnection().getMetaData().getDatabaseProductName();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		if (StringUtils.equalsIgnoreCase(DB, "MYSQL")) {
			//MYSQL存储过程调用方式
			return (Long) this.getHibernateTemplate().execute(new HibernateCallback() {
				public Object doInHibernate(Session session) throws HibernateException, SQLException {
					Query query = session.createSQLQuery("SELECT GENSEQ(\""+keyName+"\")");
					BigInteger result = (BigInteger) query.uniqueResult();
					return result.longValue();
				}
			});
		} else {
			//非MYSQL数据库存储过程调用方式
			return (Long) this.getHibernateTemplate().execute(new HibernateCallback() {
			    public Object doInHibernate(Session session) throws HibernateException, SQLException {
				    // 需要执行的存储过程
				    String procedure = "{call GENSEQ(?,?)}";
				    CallableStatement callableStatement = session.connection().prepareCall(procedure);
				    // 设置输入参数
				    callableStatement.setString(1, keyName);
				    // 注册输出参数
				    callableStatement.registerOutParameter(2, java.sql.Types.BIGINT);
				    callableStatement.execute();
				    // 取回输出参数
				    Long result = callableStatement.getLong(2);
				    callableStatement.close();
				    return result;
			    }
			});	
		}
	}

	public void computeStorageDailyByProcedure(final String computeDate) {
		this.getHibernateTemplate().execute(new HibernateCallback() {
		    public Object doInHibernate(Session session) throws HibernateException, SQLException {
			    // 需要执行的存储过程
			    String procedure = "{call PRO_CREATE_STORAGEDAILY(?)}";
			    CallableStatement callableStatement = session.connection().prepareCall(procedure);
			    // 设置输入参数
			    callableStatement.setDate(1, Date.valueOf(computeDate));
			    // 注册输出参数
			    callableStatement.execute();
			    // 取回输出参数
//			    Long result = callableStatement.getLong(2);
			    callableStatement.close();
			    
			    return null;
		    }
		});	
	}
}
