package com.engine.htsc.htxw.util;

import weaver.conn.RecordSet;

public class HtXwPageUtil {

    //获取分页sql
    public static String getPaginationSql(String sql, String orderby, int pageNo, int pageSize) {
        String execSql = "";

        RecordSet rs = new RecordSet();
        String dbType = rs.getDBType();
        int firstResult = 0;
        int endResult = 0;
        // 返回分页sql
        if("oracle".equals(dbType)){  // rownum
            firstResult = pageNo * pageSize + 1;
            endResult = (pageNo - 1) * pageSize;
            execSql = " select tabUN2.* from ( select tableUN.*,rownum as r from ( " + sql
                    + orderby +") tableUN " + ") tabUN2 where tabUN2.r < " + firstResult + " and tabUN2.r > " + endResult;
        }else if("mysql".equals(dbType)){  // limit
            firstResult =  (pageNo-1) * pageSize;
            endResult =  pageSize;
            if(pageNo == 1){
                execSql = " select * from (" + sql  + " ) tableUN " + orderby + " limit " + endResult;
            }else{
                execSql = "select * from ( select * from (" + sql +
                        " ) tableUN " + orderby + " ) tabUN2 " +  " limit " + firstResult + "," + endResult;
            }
        }else {  // 使用 ROW_NUMBER OVER()分页
            firstResult = (pageNo -1) * pageSize + 1;
            endResult = pageNo * pageSize;
            execSql = " select * from ( select * ,ROW_NUMBER() OVER ("+ orderby + ") as rowid from ( " + sql+
                    " )tableUN ) tableUN2 where rowid between " + firstResult + " and " + endResult;
        }

        return execSql;
    }

    /**
     * 取得分页统计记录数的SQL
     * @param sql;
     * @return String sql分页统计记录数语句
     */
    public static String getPaginationCountSql(String sql) {

        String paginationCountSql = " select count(1) my_count from ( " + sql  + " ) tableA ";

        return paginationCountSql;
    }


}
