/*************************************************************************************************
 * 프로그램명 : UserGroupList.java 프로그램설명 : 사용자 그룹지정 리스트 작성자 : 작성일 : 변경일 :
 **************************************************************************************************/
package kr.co.kihyun.beans.user;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
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.UserPart;
import kr.co.kihyun.beans.entity.UserUser;

import kr.co.kihyun.db.DBManager;

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

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

	private ResultSet rs = null;
	private int count = 0;
	private List<String> partIDList = new ArrayList<String>();
	private List<String> nameList = new ArrayList<String>();
	private List<String> userIDList = new ArrayList<String>();
	private List<Date> regdateList = new ArrayList<Date>();
	private List<String> descList = new ArrayList<String>();

	/******** 기관 목록을 배열에 입력 ********/
	public void executeQuery(String userID, int sysAuth) {
		executeQuery(userID, "", "", sysAuth);
	}

	public void executeQuery(String userID, String findOption, String findWord, int sysAuth) {
		StringBuilder sql = new StringBuilder(500);
		ArrayList<Object> paramList = new ArrayList<Object>();
		try {
			sql.append(getSelectClause()).append(getFromClause()).append(getWhereClause(sysAuth));
			sql.append(getSearchCondition(findOption, findWord, paramList));
//System.out.println(sql);
//			LOG.debug(sql.toString(), paramList.toArray());
			rs = execQuery(sql, userID);
			if (rs == null) {
				return;
			}

			while (rs.next()) {
				partIDList.add(rs.getString(1));
				nameList.add(rs.getString(2));
				userIDList.add(rs.getString(3));
				regdateList.add(rs.getDate(4));
				descList.add(rs.getString(5));
			}
			count = partIDList.size();

		} catch (SQLException sqlEx) {
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
					try {
		                if (rs != null)
		                    rs.close();
		            } catch (SQLException ex) {
		                //31.오류 상황 대응 부재_CWE-390 Add by YOUNGJUN,CHO
		                ex.printStackTrace();
		                //++++++++++++++++++++++++++++++++++++++++++++++++
		            }
                    try {
                        if (con != null)
                            con.close();
                    } catch (SQLException ex) {
                        //31.오류 상황 대응 부재_CWE-390 Add by YOUNGJUN,CHO
                        ex.printStackTrace();
                        //++++++++++++++++++++++++++++++++++++++++++++++++
                    }
                    try {
                        if (pstmt != null)
                        	pstmt.close();
                    } catch (SQLException ex) {
                        //31.오류 상황 대응 부재_CWE-390 Add by YOUNGJUN,CHO
                        ex.printStackTrace();
                        //++++++++++++++++++++++++++++++++++++++++++++++++
                    }

		}
	}

	private static String getSelectClause() {
		return "select up.id, up.name, up.user_id, up.reg_date, up.des ";
	}

	private static String getFromClause() {
		return new StringBuilder(100).append(" from ")
				.append(MoumiEntity.getTableName(MUser.class)).append(" us, ")
				.append(MoumiEntity.getTableName(MDept.class)).append(" dt, ")
				.append(MoumiEntity.getTableName(UserPart.class)).append(" up left join ")
				.append(MoumiEntity.getTableName(UserUser.class)).append(" uu on (uu.part_id = up.id)").toString();
	}

	private String getWhereClause(int sysAuth) {

            StringBuilder sql = new StringBuilder(450)
				.append(" where dt.ORGAN is not null and us.id=? and us.dept_id=dt.id ")
				.append("and (up.user_id=us.id or up.user_id in ")
				.append("(select id from ")
				.append(MoumiEntity.getTableName(MUser.class))
				.append(" where sys_auth=9)");




		if (sysAuth != 2) {
			sql.append(" or up.user_id in (select id from ")
					.append(MoumiEntity.getTableName(MUser.class))
					.append(" where sys_auth=2)");
		}
		//sql.append(")");//.append(" group by up.id, up.name, up.user_id, up.reg_date, up.des");
		sql.append(")").append(" order by up.name");    //그룹쪽 이름정렬

		return sql.toString();
	}

	private String getSearchCondition(String findOption, String findWord, ArrayList<Object> paramList)
			throws ParseException {
		String sql = " ";
		if ("docID".equals(findOption)) {
			sql = " and up.id like ?";
			paramList.add("%" + findWord + "%");
		} else if ("docName".equals(findOption)) {
			sql = " and up.name like ?";
			paramList.add("%" + findWord + "%");
		} else if ("regDate".equals(findOption)) {
			Date date = new SimpleDateFormat("yy-MM-dd").parse(findWord);
			sql = " and reg_date=?";
			paramList.add(date);
		}
		return sql;
	}

	public int groupCount(String groupID) {
		StringBuilder sql = new StringBuilder(70);
		try {
			sql.append("select count(*) from ")
					.append(MoumiEntity.getTableName(UserUser.class)).append(" where part_id=?");
			rs = execQuery(sql, groupID);

			if (rs != null) {
				for (int i = 0; rs.next(); i++) {
					count = rs.getInt(1);
				}
			}

			close(rs);
			pstmt.close();

			sql = new StringBuilder(70)
					.append("select count(*) from ")
					.append(MoumiEntity.getTableName(UserDept.class)).append(" where part_id=?");

			rs = execQuery(sql, groupID);
			if (rs != null) {
				for (int i = 0; rs.next(); i++) {
					count += rs.getInt(1);
				}
			}
			close(rs);
			pstmt.close();
			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 {
					 try {
		                 if (rs != null)
		                     rs.close();
		             } catch (SQLException ex) {
		                 //31.오류 상황 대응 부재_CWE-390 Add by YOUNGJUN,CHO
		                 ex.printStackTrace();
		                 //++++++++++++++++++++++++++++++++++++++++++++++++
		             }
                    try {
                        if (con != null)
                            con.close();
                    } catch (SQLException ex) {
                        //31.오류 상황 대응 부재_CWE-390 Add by YOUNGJUN,CHO
                        ex.printStackTrace();
                        //++++++++++++++++++++++++++++++++++++++++++++++++
                    }
                    try {
                        if (pstmt != null)
                        	pstmt.close();
                    } catch (SQLException ex) {
                        //31.오류 상황 대응 부재_CWE-390 Add by YOUNGJUN,CHO
                        ex.printStackTrace();
                        //++++++++++++++++++++++++++++++++++++++++++++++++
                    }

		}
	}

	public int getVaild(String groupID, String userID) {
		StringBuilder sql = new StringBuilder(80);
		int valid = 0;
		try {
			sql.append("select valid from ")
					.append(MoumiEntity.getTableName(UserUser.class)).append(" where part_id=? and id=?");
			rs = execQuery(sql, groupID, userID);
			if (rs.next()) {
				valid = rs.getInt(1);
			}
			return valid;
		} 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 boolean getUserUserEffectiveness(String groupID) {
		StringBuilder sql = new StringBuilder(120);
		boolean validCheck = false;
		try {
			sql.append("select case when valid = 'Y' and valid <> '0' then 1 else 0 end valid from ")
					.append(MoumiEntity.getTableName(UserUser.class)).append(" where part_id=?");
			rs = execQuery(sql, groupID);

			if (rs != null) {
				rs.last();
				count = rs.getRow();
				rs.beforeFirst();
			} else {
				return false;
			}

			boolean[] validList = new boolean[count];
			for (int i = 0; rs.next(); i++) {
				validList[i] = rs.getBoolean(1);
				if (!validList[i]) {
					validCheck = false;
					break;
				}
			}

			return validCheck;
		} 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 {
					 try {
		                 if (rs != null)
		                     rs.close();
		             } catch (SQLException ex) {
		                 //31.오류 상황 대응 부재_CWE-390 Add by YOUNGJUN,CHO
		                 ex.printStackTrace();
		                 //++++++++++++++++++++++++++++++++++++++++++++++++
		             }
                    try {
                        if (con != null)
                            con.close();
                    } catch (SQLException ex) {
                        //31.오류 상황 대응 부재_CWE-390 Add by YOUNGJUN,CHO
                        ex.printStackTrace();
                        //++++++++++++++++++++++++++++++++++++++++++++++++
                    }
                    try {
                        if (pstmt != null)
                        	pstmt.close();
                    } catch (SQLException ex) {
                        //31.오류 상황 대응 부재_CWE-390 Add by YOUNGJUN,CHO
                        ex.printStackTrace();
                        //++++++++++++++++++++++++++++++++++++++++++++++++
                    }

		}
	}

	public int getCount() {
		return count;
	}

	public String[] getPartIDList() {
		return partIDList.toArray(new String[partIDList.size()]);
	}

	public String[] getNameList() {
		return nameList.toArray(new String[nameList.size()]);
	}

	public String[] getUserIDList() {
		return userIDList.toArray(new String[userIDList.size()]);
	}

	public Date[] getRegdateList() {
		return regdateList.toArray(new Date[regdateList.size()]);
	}

	public String[] getDescList() {
		return descList.toArray(new String[descList.size()]);
	}
}
