/**
 * ***********************************************************************************************
 * 프로그램명 : ReportView.java 프로그램설명 : 집계자가 올린 프로젝트
 * 리스트 작성자 : 강원중 작성일 : 2004.01.27
 * 변경자 : jskim
 * 변경일 : 2015.02.04
 *************************************************************************************************
 */
package kr.co.kihyun.beans.totsys.report;

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

import kr.co.kihyun.db.DBManager;
import kr.co.kihyun.db.FixMeJDOException;
import kr.co.kihyun.lang.MString;

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

public class ReportView extends DBManager {

    private static final Logger LOG = LoggerFactory.getLogger(ReportView.class);

    private ResultSet rs = null;

    private String deptID = null;
    private String deptName = "";
    private String regDate = "";
    private String userID = "";
    private String userName = "";
    private int appro;
    private int rowCount;
    private String data = "";
    private String totData = "";
    private int recog;
    private String downDocID = "";
    private String note = "";
    private String repDocID = "";

    @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, String deptID, String userID) {
        executeQuery(docID, deptID, userID, "");
    }

 /**
 * 제출자료의 ID를 조회하여 동일부서의 동일사용자가 제출한 데이타를 구분하여 처리하도록 개선
 * 2015.02.04 jskim
**/
    public void executeQuery(Long reportID, Long docID, String deptID, String userID) {
        executeQuery(reportID, docID, deptID, userID, "");
    }

    public void executeQuery(Long docID, String deptID, String userID, String selectType) {
        StringBuilder sql = new StringBuilder(500);
        ArrayList<Object> paramList = new ArrayList<Object>();
        this.deptID = deptID;
        this.userID = userID;

        try {
            sql.append("select dp.name, us.id, sp_cm_dec_fu(us.name), rt.reg_date, rt.data, rt.tot_data, ")
                    .append("rt.recog, rt.appro, rt.note, rt.down_doc_id, rt.rep_doc_id");
            if ("modify".equals(selectType)) {
                sql.append(" from ").append(MoumiEntity.getTableName(TotReport.class)).append(" rt, ")
                        .append(MoumiEntity.getTableName(TotDoc.class)).append(" dc, ")
                        .append(MoumiEntity.getTableName(MUser.class)).append(" us, ")
                        .append(MoumiEntity.getTableName(MDept.class)).append(" dp, ")
                        .append(MoumiEntity.getTableName(Emul.class)).append(" em ")
                        .append("where rt.user_id=us.id and rt.user_id=em.user_id and rt.dept_id=dp.id ")
                        .append("and rt.dept_id=? and dc.id=? and rt.doc_id=dc.id and rt.type=? ")
                        .append("and dc.end_date >= ? and (rt.del_type='0' or rt.del_type='N') ")
                        .append("and (rt.doc_type=0 or (rt.doc_type=1 and rt.user_id=?))");
                paramList.add(deptID);
                paramList.add(docID);
                paramList.add(TotReportType.REPORT.ordinal());
                paramList.add(new Date());
                paramList.add(userID);
            } else {
                sql.append(" from ").append(MoumiEntity.getTableName(TotReport.class)).append(" rt, ")
                        .append(MoumiEntity.getTableName(MUser.class)).append(" us, ")
                        .append(MoumiEntity.getTableName(MDept.class)).append(" dp, ")
                        .append(MoumiEntity.getTableName(Emul.class)).append(" em ")
                        .append("where rt.user_id=us.id and rt.user_id=em.user_id and rt.dept_id=dp.id ")
                        .append("and rt.dept_id=? and rt.doc_id=? and rt.type=? ")
                        .append("and (rt.del_type='0' or rt.del_type='N') ")
                        .append("and (rt.doc_type=0 or (rt.doc_type=1 and rt.user_id=?))");
                paramList.add(deptID);
                paramList.add(docID);
                paramList.add(TotReportType.REPORT.ordinal());
                paramList.add(userID);
            }

//            System.out.println("sql======>" + sql.toString());
//            System.out.println("dept_id=========>" + deptID);
//            System.out.println("doc_id=========>" + docID);
//            System.out.println("type=========>" + TotReportType.REPORT.ordinal());
//            System.out.println("user_id=========>" + userID);

            rs = execQuery(sql.toString(), paramList.toArray());
            for (int i = 0; rs.next(); i++) {
                deptName = rs.getString(1);
                userID = rs.getString(2);
                userName = rs.getString(3);
                regDate = rs.getString(4);
                data = MString.checkNull(rs.getString(5));
                totData = MString.checkNull(rs.getString(6));
                recog = rs.getInt(7);
                appro = rs.getInt(8);
                note = MString.checkNull(rs.getString(9));
                downDocID = rs.getString(10);
                repDocID = rs.getString(11);
            }
        } 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();
        }
    }


/**
 * 제출자료의 ID를 조회하여 동일부서의 동일사용자가 제출한 데이타를 구분하여 처리하도록 개선
 * 2015.02.04 jskim
**/
    public void executeQuery(Long reportID, Long docID, String deptID, String userID, String selectType) {
        StringBuilder sql = new StringBuilder(500);
        ArrayList<Object> paramList = new ArrayList<Object>();
        this.deptID = deptID;
        this.userID = userID;

        try {
            sql.append("select dp.name, us.id, sp_cm_dec_fu(us.name), rt.reg_date, rt.data, rt.tot_data, ")
                    .append("rt.recog, rt.appro, rt.note, rt.down_doc_id, rt.rep_doc_id");
            if ("modify".equals(selectType)) {
                sql.append(" from ").append(MoumiEntity.getTableName(TotReport.class)).append(" rt, ")
                        .append(MoumiEntity.getTableName(TotDoc.class)).append(" dc, ")
                        .append(MoumiEntity.getTableName(MUser.class)).append(" us, ")
                        .append(MoumiEntity.getTableName(MDept.class)).append(" dp, ")
                        .append(MoumiEntity.getTableName(Emul.class)).append(" em ")
                        .append("where rt.user_id=us.id and rt.user_id=em.user_id and rt.dept_id=dp.id ")
                        //.append("and rt.dept_id=?")
                        .append(" and dc.id=? and rt.doc_id=dc.id and rt.id=? and rt.type=? ")
                        .append("and dc.end_date >= ? and (rt.del_type='0' or rt.del_type='N') ");
                        //.append("and (rt.doc_type=0 or (rt.doc_type=1 and rt.user_id=?))");
                //paramList.add(deptID);
                paramList.add(docID);
                paramList.add(reportID);
                paramList.add(TotReportType.REPORT.ordinal());
                paramList.add(new Date());
                //paramList.add(userID);
            } else {
                sql.append(" from ").append(MoumiEntity.getTableName(TotReport.class)).append(" rt, ")
                        .append(MoumiEntity.getTableName(MUser.class)).append(" us, ")
                        .append(MoumiEntity.getTableName(MDept.class)).append(" dp, ")
                        .append(MoumiEntity.getTableName(Emul.class)).append(" em ")
                        .append("where rt.user_id=us.id and rt.user_id=em.user_id and rt.dept_id=dp.id ")
                        //.append("and rt.dept_id=?")
                        .append(" and dc.id=? and rt.doc_id=dc.id and rt.id=? and rt.type=? ")
                        .append("and (rt.del_type='0' or rt.del_type='N') ");
                        //.append("and (rt.doc_type=0 or (rt.doc_type=1 and rt.user_id=?))");
                //paramList.add(deptID);
                paramList.add(docID);
                paramList.add(reportID);
                paramList.add(TotReportType.REPORT.ordinal());
                //paramList.add(userID);

            }

            /*System.out.println("reportadd sql======>" + sql.toString());
            System.out.println("reportadd dept_id=========>" + deptID);
            System.out.println("reportadd doc_id=========>" + docID);
            System.out.println("reportadd type=========>" + TotReportType.REPORT.ordinal());
            System.out.println("reportadd user_id=========>" + userID);
            System.out.println("paramList:");
            for (Object object : paramList) {
				System.out.println(object);
			}*/

            rs = execQuery(sql.toString(), paramList.toArray());
            for (int i = 0; rs.next(); i++) {
                deptName = rs.getString(1);
                userID = rs.getString(2);
                userName = rs.getString(3);
                regDate = rs.getString(4);
                data = MString.checkNull(rs.getString(5));
                totData = MString.checkNull(rs.getString(6));
                recog = rs.getInt(7);
                appro = rs.getInt(8);
                note = MString.checkNull(rs.getString(9));
                downDocID = rs.getString(10);
                repDocID = rs.getString(11);
            }
        } 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();
        }
    }

    /**
     * ****** 보고자료의 각 Field값 얻는 Method *******
     */
    public String getDeptID() {
        return deptID;
    }

    public String getDeptName() {
        return deptName;
    }

    public String getRegDate() {
        return regDate;
    }

    public String getUserID() {
        return userID;
    }

    public String getUserName() {
        return userName;
    }

    public int getRowCount() {
        return rowCount;
    }

    public String getData() {
        return data;
    }
    public String setData(String data) {
        return this.data=data;
    }
    public String getTotData() {
        return totData;
    }

    public int getRecog() {
        return recog;
    }

    public int getAppro() {
        return appro;
    }

    public String getDownDocID() {
        return downDocID;
    }

    public String getNote() {
        return note;
    }

    public String getRepDocID() {
        return repDocID;
    }
}
