/*************************************************************************************************
 * 프로그램명 : ReportList.java 프로그램설명 : 집계자가 올린 프로젝트 리스트 작성자 : 강원중 작성일 : 2004.06.07 변경일 : 2003.11.30
 **************************************************************************************************/

package kr.co.kihyun.beans.totsys.report;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
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.TotDoc;
import kr.co.kihyun.beans.entity.TotReport;
import kr.co.kihyun.beans.entity.TotReportProcess;

import kr.co.kihyun.db.DBManager;
import kr.co.kihyun.db.FixMeJDOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

	private ResultSet rs = null;

	private int count = 0;
	private List<String> partIDList;
	private List<String> partNameList;
	private List<String> deptIDList;
	private List<String> deptNameList;
	private List<String> userIDList;
	private List<Date> regDateList;
	private List<String> upperNameList;
	private List<String> prssList;
	private List<Integer> typeList;
	private List<Long> downDocIDList;
	private List<String> noteList;
	private List<Integer> docTypeList;
	private List<String> recogList;
        private List<String> ogranNameList;

	@Override
	protected void setStatment(String sql, Object... params) throws SQLException, FixMeJDOException {
		if (con == null || con.isClosed()) {
			con = getConnection();
		}
		pstmt = con.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);

		for (int i = 0; params != null && i < params.length; i++) {
			if (params[i] instanceof java.util.Date) {
				java.util.Date param = (java.util.Date) params[i];
				pstmt.setDate(i + 1, new java.sql.Date(param.getTime()));
			} else if (params[i] instanceof Boolean) {
				pstmt.setBoolean(i + 1, (Boolean) params[i]);
			} else {
				pstmt.setObject(i + 1, params[i]);
			}
		}
	}

	/******** 보고자료 목록을 배열에 입력 ********/
	public void executeQuery(Long docID, int prss) {
		executeQuery(docID, prss, "", "", -1);
	}

	public void executeQuery(Long docID, int prss, String findOption, String findWord, int recog) {
		executeQuery(docID, prss, findOption, findWord, TotReportProcess.CANCEL.ordinal(), recog);
	}

	private void executeQuery(Long docID, int prss, String findOption, String findWord, int type, int recog) {
		if (prss == TotReportProcess.COMP.ordinal()) { // 보고기관이고 보고한 기관
			listByPrss(docID, findOption, findWord, new int[] { prss }, type, recog);
		} else if (prss == TotReportProcess.NOT_REPORT.ordinal()) { // 보고기관이지만 보고는 하지 않은 기관
			listByPrss(docID, findOption, findWord, new int[] { TotReportProcess.ACCEPT.ordinal(),
			TotReportProcess.REASSIGN.ordinal(), TotReportProcess.ASSIGN.ordinal(), TotReportProcess.RETURN.ordinal(),
			TotReportProcess.TEMP.ordinal(), TotReportProcess.APPROVE.ordinal() }, type, recog);
		} else if (prss == TotReportProcess.TEMP.ordinal()) { // 임시저장상태 문서만 검색
			listByPrss(docID, findOption, findWord, new int[] { TotReportProcess.TEMP.ordinal(),
			TotReportProcess.APPROVE.ordinal() }, type, recog);
		} else if (prss == TotReportProcess.ACCEPT.ordinal()) { // 접수상태 문서만 검색
			listByPrss(docID, findOption, findWord, new int[] { prss }, type, recog);
		} else if (prss == TotReportProcess.RETURN.ordinal()) { // 재입력(재보고)상태 문서만 검색
			listByPrss(docID, findOption, findWord, new int[] { prss }, type, recog);
		} else if (prss == TotReportProcess.NOT.ordinal()) { // 재입력(재보고)상태 문서만 검색
			listByPrss(docID, findOption, findWord, new int[] { prss }, type, recog);
		} else { // 보고기관 전체
			listByPrss(docID, findOption, findWord, null, type, recog);
		}
	}

	public void listByPrss(Long docID, String findOption, String findWord, int[] prss, int type, int recog) {
		LOG.debug("prss - {}", Arrays.toString(prss).replace('[', ' ').replace(']', ' '));
		StringBuilder sql = new StringBuilder(500);
		ArrayList<Object> paramList = new ArrayList<Object>();

		try {
			sql.append("select dt.organ, (select name from ").append(MoumiEntity.getTableName(MDept.class))
					.append(" where organ is not null and id=dt.organ and id=dt.id) partName, dt.id, dt.name, ")
					.append("(select name from ").append(MoumiEntity.getTableName(MDept.class))
					.append(" where organ is not null and id=dt.upper_dept) upper_name, ")
					.append("rt.user_id, rt.reg_date, rt.prss, rt.down_doc_id, ")
					.append("rt.type, rt.doc_type, rt.note, rt.recog   \n")

                                        //2014.09.19 Add by KWON,HAN : 부서ID와 기관코드ID와 같고 상위부서ID가 존재하는 경우에 상위부서ID의 기관코드명을 조회한다.
                                        .append(", ( SELECT name FROM ").append(MoumiEntity.getTableName(MDept.class))
                                        .append("     where id = ( CASE WHEN dt.id = dt.organ AND dt.upper_dept IS NOT NULL ")
                                        .append("                       THEN ( SELECT organ FROM ").append(MoumiEntity.getTableName(MDept.class))
                                        .append("                               where id = dt.upper_dept )    ")
                                        .append("                       ELSE dt.organ END )    ")
                                        .append("  ) AS organDeptName    ")

					.append("from ").append(MoumiEntity.getTableName(TotReport.class))
					.append(" rt, ").append(MoumiEntity.getTableName(TotDoc.class)).append(" dc, ")
					.append(MoumiEntity.getTableName(MDept.class)).append(" dt");

			if ("userName".equals(findOption)) {
				sql.append(", ").append(MoumiEntity.getTableName(MUser.class)).append(" us");
			}
			sql.append(" where dt.ORGAN is not null and rt.dept_id=dt.id and rt.doc_id=dc.id and rt.doc_id=? and (rt.del_type='0' or rt.del_type='N') ");
			paramList.add(docID);

			if (recog != -1) {
				sql.append(" and rt.recog=?");
				paramList.add(recog);
			}

			if (prss != null && prss.length > 0) {
				sql.append(" and rt.prss in (").append(Arrays.toString(prss).replace('[', ' ').replace(']', ' ')).append(")");
			}

			if ("userName".equals(findOption)) {
				sql.append(" and rt.user_id=us.id");
			}
			if ("deptID".equals(findOption)) {
				sql.append(" and rt.dept_id=?");
				paramList.add(findWord);
			} else if ("deptName".equals(findOption)) {
				sql.append(" and dt.name like '%?%'");
				paramList.add(findWord);
			} else if ("partName".equals(findOption)) {
				sql.append(" and pt.name like '%?%'");
				paramList.add(findWord);
			} else if ("regDate".equals(findOption)) {
				sql.append(" and rt.reg_date='?'");
				paramList.add(findWord);
			} else if ("userName".equals(findOption)) {
				sql.append(" and us.name = sp_cm_enc_fu(?) ");
				paramList.add(findWord);
			}

			sql.append(" order by dt.priority, dt.upper_dept, dt.name");

            rs = execQuery(sql.toString(), paramList.toArray());

            partIDList = new ArrayList<String>();
			partNameList = new ArrayList<String>();
			deptIDList = new ArrayList<String>();
			deptNameList = new ArrayList<String>();
			userIDList = new ArrayList<String>();
			regDateList = new ArrayList<Date>();
			upperNameList = new ArrayList<String>();
			prssList = new ArrayList<String>();
			typeList = new ArrayList<Integer>();
			downDocIDList = new ArrayList<Long>();
			noteList = new ArrayList<String>();
			docTypeList = new ArrayList<Integer>();
			recogList = new ArrayList<String>();
            ogranNameList = new ArrayList<String>();

            while(rs.next()){
				partIDList.add(rs.getString(1));
				partNameList.add(rs.getString(2));
				deptIDList.add(rs.getString(3));
				deptNameList.add(rs.getString(4));
				upperNameList.add(rs.getString(5));
				userIDList.add(rs.getString(6));
				regDateList.add(rs.getDate(7));
				prssList.add(rs.getString(8));
				downDocIDList.add(rs.getLong(9));
				typeList.add(rs.getInt(10));
				docTypeList.add(rs.getInt(11));
				if (rs.getClob(12) == null)
					noteList.add("");
				else
					noteList.add(rs.getClob(12).toString());
				recogList.add(rs.getString(13));
                ogranNameList.add(rs.getString(14));
            }
			count = partIDList.size();




		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nMySQL Error Code - {}\nmessage - {}\nsql - {}",
					new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage(), sql.toString() });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}

	public int getCount() {
		return count;
	}

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

	public String[] getPartNameList() {
		return partNameList.toArray(new String[partNameList.size()]);
	}

	public String[] getDeptIDList() {
		return deptIDList.toArray(new String[deptIDList.size()]);
	}

	public String[] getDeptNameList() {
		return deptNameList.toArray(new String[deptNameList.size()]);
	}

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

	public Date[] getRegDateList() {
		return regDateList.toArray(new Date[regDateList.size()]);
	}

	public String[] getNoteList() {
		return noteList.toArray(new String[noteList.size()]);
	}

	public String[] getPrssList() {
		return prssList.toArray(new String[prssList.size()]);
	}

	public Integer[] getTypeList() {
		return typeList.toArray(new Integer[typeList.size()]);
	}

	public Long[] getDownDocIDList() {
		return downDocIDList.toArray(new Long[downDocIDList.size()]);
	}

	public Integer[] getDocTypeList() {
		return docTypeList.toArray(new Integer[docTypeList.size()]);
	}

	public String[] getUpperNameList() {
		return upperNameList.toArray(new String[upperNameList.size()]);
	}

	public String[] getRecogList() {
		return recogList.toArray(new String[recogList.size()]);
	}

        public String[] getOrganNameOfUpperDept() {
		return ogranNameList.toArray(new String[ogranNameList.size()]);
	}
}
