/***********************************************************************************
 * @@ Program Name : PartList.java Description : 부서를 포함하고있는 기관의 정보 목록 Author : 강원중 Create Date : 2004-10-22 History :
 * @@
 ***********************************************************************************/

package kr.co.kihyun.beans.user;

import java.sql.ResultSet;
import java.sql.SQLException;
import kr.co.kihyun.beans.entity.MDept;
import kr.co.kihyun.beans.entity.MUser;
import kr.co.kihyun.beans.entity.MoumiEntity;

import kr.co.kihyun.beans.entity.SysAuth;
import kr.co.kihyun.beans.entity.TotDoc;
import kr.co.kihyun.beans.entity.TotReport;
import kr.co.kihyun.beans.entity.TotReportProcess;
import kr.co.kihyun.beans.entity.TotReportType;
import kr.co.kihyun.db.DBManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PartList extends DBManager {
	private static final Logger LOG = LoggerFactory.getLogger(PartList.class);

	private ResultSet rs = null;

	private int count = 0;
	private String[] idList = null;
	private String[] nameList = null;
	private String[] upperDeptList = null;
	private String[] organList = null;
	private boolean[] selTypeList = null;

	/******** 카테고리 전체 리스트 ********/
	public void executeQuery() {
		StringBuilder sql = new StringBuilder(250);
		try {
			sql.append("select id, name, upper_dept, organ, ")
					.append("case when sel_type = 'Y' and sel_type <> '0' then 1 else 0 end sel_type, priority from ")
					.append(MoumiEntity.getTableName(MDept.class))
					.append(" where ORGAN is not null and upper_dept is null and sys_auth < 3 order by id");
//System.out.println("PartList test1"+sql);
			rs = execQuery(sql);
			if (rs != null) {
				rs.last();
				count = rs.getRow();
				rs.beforeFirst();
			} else {
				return;
			}

			idList = new String[count];
			nameList = new String[count];
			upperDeptList = new String[count];
			organList = new String[count];
			selTypeList = new boolean[count];

			for (int i = 0; rs.next(); i++) {
				idList[i] = rs.getString(1);
				nameList[i] = rs.getString(2);
				upperDeptList[i] = rs.getString(3);
				organList[i] = rs.getString(4);
				selTypeList[i] = rs.getBoolean(5);
			}
		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nMySQL Error Code - {}\nmessage - {}\nsql - {}",
					new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}

	/******** 카테고리 전체 리스트 ********/
	public void executeQuery(String partID) {
		StringBuilder sql = new StringBuilder(250);
		try {
			sql.append("select id, name, upper_dept, organ, ")
					.append("case when sel_type = 'Y' and sel_type <> '0' then 1 else 0 end sel_type, priority from ")
					.append(MoumiEntity.getTableName(MDept.class))
					.append(" where ORGAN is not null and id=?");
			if (kr.co.kihyun.moumi.MoumiConfig.is2StepDirect()) {
				sql.append(" or (upper_dept=? and id=organ)");
			} else {
				sql.append(" or upper_dept=?");
			}
			sql.append(" order by id");
//System.out.println("PartList test2"+sql);
			rs = execQuery(sql, partID, partID);
			if (rs != null) {
				rs.last();
				count = rs.getRow();
				rs.beforeFirst();
			} else {
				return;
			}

			idList = new String[count];
			nameList = new String[count];
			upperDeptList = new String[count];
			organList = new String[count];
			selTypeList = new boolean[count];

			for (int i = 0; rs.next(); i++) {
				idList[i] = rs.getString(1);
				nameList[i] = rs.getString(2);
				upperDeptList[i] = rs.getString(3);
				organList[i] = rs.getString(4);
				selTypeList[i] = rs.getBoolean(5);
			}
		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nMySQL Error Code - {}\nmessage - {}\nsql - {}",
					new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}

	/******** 선택된 문서에대한 보고 기관 리스트 ********/
	public void executeQuery(Long docID, String selectType) {
		// TODO: selectType에 따라 다른 쿼리 실행하기...
		StringBuilder sql = new StringBuilder(500);
		try {
			sql.append("select distinct pt.id, pt.name, pt.upper_dept, ")
					.append("case when pt.sel_type = 'Y' and pt.sel_type <> '0' then 1 else 0 end sel_type, ")
					.append("pt.priority ")
					.append("from ").append(MoumiEntity.getTableName(MDept.class)).append(" pt, ")
					.append(MoumiEntity.getTableName(MDept.class)).append(" dt, ")
					.append(MoumiEntity.getTableName(MUser.class)).append(" us, ")
					.append(MoumiEntity.getTableName(TotDoc.class)).append(" dc, ")
					.append(MoumiEntity.getTableName(TotReport.class)).append(" rt ")
					.append("where dc.id=? and (dc.del_type='0' or dc.del_type='N') and dc.id=rt.doc_id ")
					.append("and rt.prss>=? and (rt.del_type='0' or rt.del_type='N') and rt.type=? ")
					.append("and rt.data is not null and rt.user_id=us.id and rt.dept_id=dt.id and dt.organ=pt.id ")
					.append("order by pt.priority");
//System.out.println("PartList test3"+sql);
			rs = execQuery(sql, docID, TotReportProcess.COMP.ordinal(), TotReportType.REPORT.ordinal());
			if (rs != null) {
				rs.last();
				count = rs.getRow();
				rs.beforeFirst();
			} else {
				return;
			}

			idList = new String[count];
			nameList = new String[count];
			upperDeptList = new String[count];
			selTypeList = new boolean[count];

			for (int i = 0; rs.next(); i++) {
				idList[i] = rs.getString(1);
				nameList[i] = rs.getString(2);
				upperDeptList[i] = rs.getString(3);
				selTypeList[i] = rs.getBoolean(4);
			}
		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nMySQL Error Code - {}\nmessage - {}\nsql - {}",
					new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}

	/******** 카테고리 전체 리스트 ********/
	public void getTop() {
		StringBuilder sql = new StringBuilder(250);
		try {
			sql.append("select id, name, upper_dept, organ, ")
					.append("case when sel_type = 'Y' and sel_type <> '0' then 1 else 0 end sel_type, priority ")
					.append("from ").append(MoumiEntity.getTableName(MDept.class))
					.append(" where ORGAN is not null and upper_dept is null and sys_auth in (?, ?, ?) order by priority, id");

			rs = execQuery(sql, SysAuth.REPOPER.ordinal(), SysAuth.SUB_TOTPER.ordinal(), SysAuth.TOTPER.ordinal());
			if (rs != null) {
				rs.last();
				count = rs.getRow();
				rs.beforeFirst();
			} else {
				return;
			}

			idList = new String[count];
			nameList = new String[count];
			upperDeptList = new String[count];
			organList = new String[count];
			selTypeList = new boolean[count];
//System.out.println("PartList test4"+sql);
			rs = execQuery(sql);

			for (int i = 0; rs.next(); i++) {
				idList[i] = rs.getString(1);
				nameList[i] = rs.getString(2);
				upperDeptList[i] = rs.getString(3);
				organList[i] = rs.getString(4);
				selTypeList[i] = rs.getBoolean(5);
			}
		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nMySQL Error Code - {}\nmessage - {}\nsql - {}",
					new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}

	public String[] getIDList() {
            //24.Public 메소드로부터 반환된 Private배열_CWE-495 : Update by KWON,HAN
	    //	return idList;
                
            String[] ret = null;
            if( this.idList != null) {
                ret = new String[idList.length];
                for (int i=0; i<idList.length; i++) {
                    ret[i] = this.idList[i];
                }
            }
            return ret;                
            //====================================================================              
	}

	public String[] getNameList() {
	    //	return nameList;
                
            String[] ret = null;
            if( this.nameList != null) {
                ret = new String[nameList.length];
                for (int i=0; i<nameList.length; i++) {
                    ret[i] = this.nameList[i];
                }
            }
            return ret;                 
	}

	public String[] getUpperDeptList() {
	    //	return upperDeptList;
                
            String[] ret = null;
            if( this.upperDeptList != null) {
                ret = new String[upperDeptList.length];
                for (int i=0; i<upperDeptList.length; i++) {
                    ret[i] = this.upperDeptList[i];
                }
            }
            return ret;                  
	}

	public String[] getOrganList() {
	    //	return organList;
                
            String[] ret = null;
            if( this.organList != null) {
                ret = new String[organList.length];
                for (int i=0; i<organList.length; i++) {
                    ret[i] = this.organList[i];
                }
            }
            return ret;                  
	}

	public boolean[] getSelTypeList() {
	    //	return selTypeList;
                
            boolean[] ret = null;
            if( this.selTypeList != null) {
                ret = new boolean[selTypeList.length];
                for (int i=0; i<selTypeList.length; i++) {
                    ret[i] = this.selTypeList[i];
                }
            }
            return ret;                 
	}

	public int getCount() {
		return count;
	}
}
