/***********************************************************************************
 * @@ Program Name : Dept.java Description : 부서 관련정보 Author : 강원중 Create Date : 2004.10.13 History :
 * @@
 ***********************************************************************************/

package kr.co.kihyun.beans.user;

import java.sql.ResultSet;
import java.sql.SQLException;
import kr.co.kihyun.beans.entity.Emul;
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.UserDept;
import kr.co.kihyun.beans.entity.UserUser;

import kr.co.kihyun.db.DBManager;
import kr.co.kihyun.moumi.MoumiConfig;

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

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

	public static String[] gradeName = { "유치원", "초등학교", "중학교", "고등학교", "기타기관" };

	private ResultSet rs = null;

	/******** 부서이름 가져오기 ********/
	public String getName(String id) {
		StringBuilder sql = new StringBuilder(50);

		String name = "";
		try {
			sql.append("select name from ").append(MoumiEntity.getTableName(MDept.class)).append(" where id=?");
            //System.out.println("Dept test1:::::"+sql);
			rs = execQuery(sql.toString(), id);

			if (rs.next()) {
				name = rs.getString(1);
			}
			return name;
		} 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 getPartID(String id) {
		StringBuilder sql = new StringBuilder(50);

		String partID = null;
		try {
			sql.append("select organ from ").append(MoumiEntity.getTableName(MDept.class)).append(" where id=?");
            //System.out.println("Dept test2:::::"+sql);
			rs = execQuery(sql, id);

			if (rs.next()) {
				partID = rs.getString(1);
			}
			return partID;
		} 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 getInsertPartID(String id) {
		StringBuilder sql = new StringBuilder(50).append("select upper_dept from ")
				.append(MoumiEntity.getTableName(MDept.class)).append(" where id=?");

         //System.out.println("Dept test3::::"+sql);
		String upperID = id;

		while (upperID != null) {
			try {
				rs = execQuery(sql, upperID);
				upperID = rs.next() ? rs.getString(1) : null;
				LOG.debug("getInsertPartID - {} ", id);
			} 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();
			}
		}

		return id;
	}

	public String getPartName(String id) {
		StringBuilder sql = new StringBuilder(100);
		String partName = "";

		try {
			sql.append("select udt.name from ")
                           .append(MoumiEntity.getTableName(MDept.class)).append(" dt, ")
		           .append(MoumiEntity.getTableName(MDept.class)).append(" udt where dt.id=? and udt.id=dt.organ");
			rs = execQuery(sql, id);

			if (rs.next()) {
				partName = rs.getString(1);
			}
                        
			return partName;
		} catch (SQLException sqlEx) {
			LOG.error("Could not get name of MDept@" + id);
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}
        
        /*
         * 2014.09.18 Add by KWON,HAN : 
         * - 부서ID와 기관코드ID와 같고 상위부서ID가 존재하는 경우에 상위부서ID의 기관코드명을 조회한다.
         *   즉, 강릉교육청-지역교육청-강릉교육청 ==> 강원도교육청-지역교육청-강릉교육청 으로 표시되도록 변경함. 
         */
	public String getOrganNameOfUpperDept(String id) {
		StringBuilder sql = new StringBuilder(100);
		String partName = "";

		try {
			sql.append("select udt.name from ")
                           .append(MoumiEntity.getTableName(MDept.class)).append(" dt, ")
		         //.append(MoumiEntity.getTableName(MDept.class)).append(" udt where dt.id=? and udt.id=dt.organ");
                           .append(MoumiEntity.getTableName(MDept.class)).append(" udt where dt.id=? and udt.id=( CASE WHEN dt.id = dt.organ AND dt.upper_dept IS NOT NULL THEN ( SELECT organ FROM ")
                           .append(MoumiEntity.getTableName(MDept.class)).append(" where id = dt.upper_dept ) ELSE dt.organ END )") ;
			rs = execQuery(sql, id);

//System.out.println("Dept.getOrganNameOfUpperDept:::::::::::::::");                        
//System.out.println("sql = "+sql);
//System.out.println("id = "+id);
//System.out.println("::::::::::::::::::::::::::::::::::::::::::");

			if (rs.next()) {
				partName = rs.getString(1);
			}
                        
			return partName;
		} catch (SQLException sqlEx) {
			LOG.error("Could not get name of MDept@" + id);
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}        

	public String getUpperDeptName(String id) {
		StringBuilder sql = new StringBuilder(100);
		String upperDeptName = "";
		try {
			sql.append("select udt.name from ").append(MoumiEntity.getTableName(MDept.class)).append(" dt, ")
					.append(MoumiEntity.getTableName(MDept.class)).append(" udt ")
					.append("where dt.id=? and udt.id=dt.upper_dept");
			rs = execQuery(sql, id);

            //System.out.println("Dept test5::::"+sql);

			if (rs.next()) {
				upperDeptName = rs.getString(1);
			}
			return upperDeptName;
		} 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 int getCount(String partID) {
		StringBuilder sql = new StringBuilder(90);
		int count = 0;
		try {
			sql.append("select count(id) from ").append(MoumiEntity.getTableName(MDept.class))
					.append(" where organ=? and sys_auth < ?");

         //System.out.println("Dept test6::::"+sql);

			rs = execQuery(sql, partID, MoumiConfig.SUB_TOTADM);
			if (rs.next()) {
				count = rs.getInt(1);
			}
			return count;
		} 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[] getMultiUserList(String id) {
		StringBuilder sql = new StringBuilder(150);
		int count = 0;
		String[] userList = null;
		try {
			sql.append("select em.user_id from ").append(MoumiEntity.getTableName(Emul.class)).append(" em, ")
					.append(MoumiEntity.getTableName(MUser.class)).append(" us ")
					.append("where em.dept_id=? and us.id=em.user_id and (us.del_type='0' or us.del_type='N')");

            //System.out.println("Dept test7:::::"+sql);

			rs = execQuery(sql, id);
			if (rs != null) {
				rs.last();
				count = rs.getRow();
				rs.beforeFirst();
			} else {
				return null;
			}

			userList = new String[count];

			for (int i = 0; rs.next(); i++) {
				userList[i] = rs.getString(1) + "/" + id;
			}
			return userList;
		} 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 getConverDeptIDs(String deptIDs, String deptTypes) {
		StringBuilder sql = new StringBuilder(60);
		try {
			String[] deptIDList = deptIDs.split(",");
			String[] deptTypeList = deptTypes.split(",");
			StringBuilder returnDeptIDs = new StringBuilder(250);

			for (int i = 0; i < deptIDList.length; i++) {
				if (deptTypeList[i].equals("group")) {
					if (i == 0) {
						sql.append("select id from ").append(MoumiEntity.getTableName(UserDept.class))
								.append(" where part_id=?");

                        //System.out.println("Dept test8:::::"+sql);
						rs = execQuery(sql, deptIDList[i]);

						for (int j = 0; rs.next(); j++) {
							if (returnDeptIDs.length() == 0)
								returnDeptIDs.append(rs.getString(1));
							else
								returnDeptIDs.append(",").append(rs.getString(1));
						}

						close(rs);
						execClose();

						sql.append("select id, dept_id from ").append(MoumiEntity.getTableName(UserUser.class))
								.append(" where part_id=?");

                        //System.out.println("Dept test9::::::"+sql);

						rs = execQuery(sql, deptIDList[i]);

						for (int j = 0; rs.next(); j++) {
							if (returnDeptIDs.length() == 0)
								returnDeptIDs.append(rs.getString(1)).append("/").append(rs.getString(2));
							else
								returnDeptIDs.append(",").append(rs.getString(1)).append("/").append(rs.getString(2));
						}

						close(rs);
						execClose();
					} else {
						sql.append("select id from ").append(MoumiEntity.getTableName(UserDept.class))
								.append(" where part_id=?");

                       //System.out.println("Dept test10:::::"+sql);
						rs = execQuery(sql, deptIDList[i]);

						for (int j = 0; rs.next(); j++)
							returnDeptIDs.append(",").append(rs.getString(1));

						close(rs);
						execClose();

						sql.append("select id, dept_id from ").append(MoumiEntity.getTableName(UserUser.class))
								.append(" where part_id=?");

                       //System.out.println("Dept test11::::"+sql);
						rs = execQuery(sql, deptIDList[i]);

						for (int j = 0; rs.next(); j++)
							returnDeptIDs.append(",").append(rs.getString(1)).append("/").append(rs.getString(2));

						close(rs);
						execClose();
					}
				} else {
					if (i == 0)
						returnDeptIDs.append(deptIDList[i]);
					else
						returnDeptIDs.append(",").append(deptIDList[i]);
				}
			}

			return returnDeptIDs.toString();
		} 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();
		}
	}
}
