/***********************************************************************************
 * @@ Program Name : HttpDeptList.java Description : 기관에속한 부서들의 목록 Author : 강원중 Create Date : 2003-12-16 History :
 * @@
 ***********************************************************************************/

package kr.co.kihyun.beans.user;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
//import java.util.ArrayList;
import java.util.List;
//import javax.jdo.JDOObjectNotFoundException;
//import javax.jdo.PersistenceManager;
//import javax.jdo.Transaction;
//
//import javax.servlet.ServletException;
//import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import kr.co.kihyun.beans.entity.MDept;
//import kr.co.kihyun.beans.entity.MUser;
//import kr.co.kihyun.beans.entity.UserPart;
//import kr.co.kihyun.beans.entity.util.MPersistenceManager;
//import kr.co.kihyun.beans.entity.util.PMF;
import kr.co.kihyun.beans.totsys.report.Report;
import kr.co.kihyun.db.DBManager;

//import kr.co.kihyun.lang.Encoder;
//import kr.co.kihyun.moumi.MoumiConfig;
import kr.co.kihyun.lang.MString;
//import kr.co.kihyun.text.html.ServletUtil;

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

public class HttpApproveInsert extends DBManager {

    private  List<String> recogid;
    private ResultSet rs = null;
   	private static final Logger LOG = LoggerFactory.getLogger(Report.class);

   	private String[] ID = null;
   	private String[] RECOG = null;
   	private String[] RECOG_NUM = null;
   	private String[] RECOG_USER_ID = null;
   	private String[] REPORT_ID = null;
   	private String[] RECOGFLAG = null;
    private String[] MAXID = null;

    public HttpApproveInsert(Long reportID,String reportType,String idList,String typeList,String docReportID,HttpServletRequest req, HttpServletResponse res) throws SQLException, IOException
	{
        String[] reoogUserDList = null;
        String strReportID = null;
        String recogUserId = null;
        String sql = null;
        String sql2 = null;

       	String usID = HttpSSOLogin.getLoginID(req);
		int sysAuth = HttpSSOLogin.getSysAuth(req);
        recogUserId=MString.checkNull(idList,"null");
        reoogUserDList = recogUserId.split(",");
        strReportID = docReportID;
        String RecogId = null;
        ResultSet rs = null;

        res.setContentType("text/html;charset=UTF-8");
		PrintWriter out = res.getWriter();
		try
		{
            for(int i = 0; i < reoogUserDList.length; i++){
                int tmpRecogNum = i+1;
                int prss = 1;
                //System.out.println("Recog num:::"+tmpRecogNum+"::reportIDList:::"+reoogUserDList[i]+"::reportID:::"+strReportID);

                insertRepoAdm(prss,tmpRecogNum,reoogUserDList[i],strReportID);

                if(tmpRecogNum == 1){
                     UpdatetTotReport(strReportID);
                }

           }

            //v2. 1.HTTP 응답분할 : Update by KWON,HAN
//           res.sendRedirect("/totsys/repoper/mydocbox/tempbox/report_view.jsp?reportID="+ reportID + "&totperInfo=true&reportType=" + reportType + "'&alertState=Y");

            // 수정 : 외부 입력값 필터링
            String filtered_reportType = reportType.replaceAll("\r","").replaceAll("\n","");
            LOG.debug("v2 1.HTTP 응답분할 : HttpApproveInsert.HttpApproveInsert() filtered_reportType={}, Not Test", filtered_reportType);

            //v2. 3.신뢰되지 않는 URL 주소로 자동 접속 연결_CWE-601 : Update by KWON,HAN
//            res.sendRedirect("/totsys/repoper/mydocbox/tempbox/report_view.jsp?reportID="+ reportID + "&totperInfo=true&reportType=" + filtered_reportType + "'&alertState=Y");

            // 다른 페이지 이동하는 URL 리스트를 만듬
            String connURL = "";
            String allowURL[] = { "/totsys/repoper/mydocbox/tempbox/report_view.jsp" };
            connURL = allowURL[0] + "?reportID="+ reportID + "&totperInfo=true&reportType=" + filtered_reportType + "'&alertState=Y";
            LOG.debug("v2 3.신뢰되지 않는 URL 주소로 자동 접속 연결_CWE-601 : HttpApproveInsert.HttpApproveInsert() connURL={} : Not Test", connURL);
            res.sendRedirect(connURL);
            //========================================================================
            //======================================
           return;

		}catch (Exception e){
			e.printStackTrace();
		}
		finally
        {

            try {
                if (pstmt != null)
                    pstmt.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            try {
                if (con != null)
                    con.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            try {
                if (rs != null)
                    rs.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
	}


     public void  insertRepoAdm(int prss,int tmpRecogNum,String reportIDList,String strReportID) throws SQLException
	{
        ResultSet rs = null;
		PrintWriter out=null;
        String recogFlag="Y";
        String acceptFlag="N";

		try
		{
                  //System.out.println("Recog num:::"+tmpRecogNum+"::reportIDList:::"+reportIDList+"::reportID:::"+strReportID);
                  String sql="INSERT INTO MOUMI_REPOADM (ID,DEC_DATE,HISTORY,RECOG,RECOG_NUM,RECOG_USER_ID,REPORT_ID,RECOGFLAG,ACCEPTFLAG,DELTYPE)";
                         sql= sql + "VALUES((SELECT MAX(ID)+1 FROM MOUMI_REPOADM),TO_CHAR(SYSDATE,'yyyy/mm/dd'),'',?,?,?,?,?,?,'N')";

                  execUpdate(sql,prss,tmpRecogNum,reportIDList,strReportID,recogFlag,acceptFlag);

                  //System.out.println("UpdateRepoAdm 실행 SQL::::::"+sql);
                  return;
		}catch (Exception e){
    			e.printStackTrace();
		}
		finally
        {
            try {
                if (pstmt != null)
                	pstmt.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            try {
                if (con != null)
                    con.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            try {
                if (rs != null)
                    rs.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
	}

     public void  UpdatetTotReport(String docReportID) throws SQLException
	{
        String strReportID = null;
        ResultSet rs = null;
		PrintWriter out=null;
		try
		{
            strReportID = docReportID;

                String sql="UPDATE MOUMI_TOT_REPORT SET CURRENT_REPOADM_ID = (SELECT MAX(ID) FROM MOUMI_REPOADM) ,PRSS=5 WHERE ID =?";
                execUpdate(sql,strReportID);

                  //System.out.println("UpdateRepoAdm 실행 SQL::::::"+sql);

                  return;

		}catch (Exception e){
			e.printStackTrace();
		}
		finally
        {
            try {
                if (pstmt != null)
                	pstmt.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            try {
                if (con != null)
                    con.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            try {
                if (rs != null)
                    rs.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
	}


      public void  UpdateTotReportFin(String docReportID) throws SQLException
	{
        String strReportID = null;
        ResultSet rs = null;
		PrintWriter out=null;
		try
		{
            strReportID = docReportID;

                String sql="UPDATE MOUMI_TOT_REPORT SET CURRENT_REPOADM_ID = (SELECT MAX(ID) FROM MOUMI_REPOADM) ,PRSS=6 WHERE ID =?";
                execUpdate(sql,strReportID);

                  //System.out.println("UpdateRepoAdm 실행 SQL::::::"+sql);

                  return;

		}catch (Exception e){
			e.printStackTrace();
		}
		finally
        {
            try {
                if (pstmt != null)
                	pstmt.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            try {
                if (con != null)
                    con.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            try {
                if (rs != null)
                    rs.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
	}


   /******** tmpName 구해오기 ********/
	public void getrecogID(String reportID) {
		StringBuilder sql = new StringBuilder(250);
        int count = 0;

		try {

           sql.append("SELECT ID,RECOG,RECOG_NUM,RECOG_USER_ID,REPORT_ID,RECOGFLAG FROM MOUMI_REPOADM ")
              .append("WHERE REPORT_ID = '"+reportID+"' ORDER BY ID DESC,REPORT_ID ASC;");

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

                ID  = new String[count];
                RECOG  = new String[count];
                RECOG_NUM  = new String[count];
                RECOG_USER_ID  = new String[count];
                REPORT_ID  = new String[count];
                RECOGFLAG  = new String[count];

			for (int i = 0; rs.next(); i++) {
                ID[i] = rs.getString(1);
                RECOG[i] = rs.getString(2);
                RECOG_NUM[i] = rs.getString(3);
                RECOG_USER_ID[i] = rs.getString(4);
                REPORT_ID[i] = rs.getString(5);
                RECOGFLAG[i] = rs.getString(6);
			}

          //System.out.println(sql);

		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nMySQL Error Code - {}\nmessage - {}\nsql - {}",
			new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage()});
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			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();
                    //++++++++++++++++++++++++++++++++++++++++++++++++
                }
            try {
                    if (rs != null)
                        rs.close();
                } catch (SQLException ex) {
                    //31.오류 상황 대응 부재_CWE-390 Add by YOUNGJUN,CHO
                    ex.printStackTrace();
                    //++++++++++++++++++++++++++++++++++++++++++++++++
                }
		}
	}

    public String[] getID() {
            //24.Public 메소드로부터 반환된 Private배열_CWE-495 : Update by KWON,HAN
	    //	return ID;

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

    public String[] getRecog() {
	    //	return RECOG;

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

    public String[] getRecogNum() {
	    //	return RECOG_NUM;

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

    public String[] getRecogUserId() {
	    //	return RECOG_USER_ID;

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

    public String[] getReportId() {
	    //	return REPORT_ID;

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

    public String[] getRecogFlag() {
	    //	return RECOGFLAG;

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

    public String[] getMaxID(){
        //return MAXID;

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

}
