/* 
    ETRI IntraPMS Project
    
    문서를 새로 상신하는 Servlet 	
    
*/

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

import com.etri.groupware.*;
import com.etri.groupware.eda.*;

public class EDASubmitServlet extends HttpServlet{
	GroupwareControllerInterface groupwareController = null;
	EDAControllerInterface edaController = null;
	Properties pro = null;	
		
	public void init( ServletConfig sc ) throws ServletException{
		super.init(sc);
		
		pro = new Properties();
		pro.put("DriverName","weblogic.jdbc.mssqlserver4.Driver");
		pro.put("DBServer","jdbc:weblogic:mssqlserver4:GWDB@Server:1433");
		pro.put("User","sa");
		pro.put("Password","");
		
		pro.put("OrganizationDBManagerClassName","PandaSoftOrganizationDBManager");
		pro.put("BBSDBManagerClassName","PandaSoftBBSDBManager");
		pro.put("EDADBManagerClassName","PandaSoftEDADBManager");
		pro.put("MailDBManagerClassName","PandaSoftMailDBManager");
		
		try{
			groupwareController = GroupwareController.init( pro );
			System.out.println("그룹웨어 컨트롤러 생성을 마쳤습니다.");
			
			edaController = groupwareController.createEDAController();
			System.out.println("전자결재 컨트롤러 생성도 무사히 마쳤습니다.");	
		}
		catch( Exception e){
			System.out.println( e.toString() );
		}
	}

	public void destroy(){
		System.out.println("EDAApprovalServlet Destroy() 호출");
		super.destroy();
		DBConnectionManager.instance.release();
		System.out.println("EDAApprovalServlet Destroy() 완료");
	}

/*----------------------------------------------------------------- */
/**
 [메소드이름]: doGet<br>
 [기능]: 새 문서를 작성하기 위한 폼을 보여준다.<br>
 [파라미터]: HttpServletRequest req,HttpServletResponse res<br>
 [호출자] : 사용자<br>
 */
/*--------------------------------------------------------------- */	
	public void doGet(HttpServletRequest req,HttpServletResponse res)
	 throws ServletException,IOException{
	 
	 	HttpSession session = req.getSession(true);
	 	
		res.setContentType("text/html;charset=edu-kr");
		PrintWriter out = new PrintWriter( new OutputStreamWriter(
		 res.getOutputStream(),"EUC-KR"));
		 
		boolean authentication = false;
		
		String id = req.getParameter("id");
		String name = req.getParameter("name");
		
		if((session.isNew())){
			session.invalidate();
			res.sendRedirect("../Login.html");
		}
		else if(session.getValue("Authentication").equals("true")){
			authentication = true;
			id = (String) session.getValue("Id");
			name = (String) session.getValue("Name");
		}
		else {
			session.invalidate();
			res.sendRedirect("../Login.html");
		}
		
		if(authentication){
			out.println("<html><head><title>결재 문서 작성</title></head>");
			out.println("<SCRIPT LANGUAGE=\"JavaScript\">");
			out.println("<!--" );
			out.println("var AtthNum=0;");
			out.println("var myWin ");
			out.println("function AppendAttachFile(){");
			out.println("	var AtthBox=\"\"; " );
			out.println("	var AtthOk = true;");
			out.println("	if(AtthNum>5){");
			out.println("		alert(\"더이상 파일을 첨수할 수 없습니다.\");");
			out.println("		return;");
			out.println("	}");
			out.println("	if(AtthNum>0){");
			out.println("		var file;AtthBox = \"document.forms[0].ATTH\"+(AtthNum-1);");
			out.println("		AtthBox +=\".value\";file=eval(AtthBox);");
			out.println("		if(file.length<=0) AtthOk = false;");
			out.println("	}");
			out.println("	if(AtthOk==true){" );
			out.println("		var Atth=\"document.all.AtthBox\"+AtthNum;Atth+=\".style.display=\";");
			out.println("		Atth +=\"(document.all.AtthBox\"+AtthNum;Atth+=\".style.display=='none')?'':'none'\";");
			out.println("		eval(Atth);");
			out.println("		AtthNum++;");
			out.println("	}");
			out.println("}");
					
			out.println("function Check_Form(form){");
			out.println("if( form.titleEdit.value ==\"\" ) window.alert(\"제목을 입력하세요\");");
			out.println("else if( form.itemSel.value ==\"\" ) window.alert( \"문서분류항목을 지정하세요.\");");
			out.println("else if( form.pathName1.value == \"1\" )window.alert( \"결재경로를 지정하세요\");");
			out.println("else form.submit();");
			out.println("} ");
	
			
			out.println("function EDALineSelection() {");
			out.println("myWin = window.open ( \"/EDALineSelection.html\" , \"결재선선택\" , \"width=650,height=450,scrollbars=1,copyHistory=1\" )");	
			out.println("}");
		
			out.println("function result( d ) {");
			out.println("var allOfficial = arguments[0] ;");
			out.println("var e1 = document.createElement(\"OPTION\")" );
			out.println("e1.text = allOfficial ;");
			out.println("e1.value = allOfficial ;");
			out.println("e1.selected = true ;");
			out.println("document.form1.pathName1.options.add(e1);");
			out.println("myWin.close();");
			out.println("}");
		
			out.println("//-->");	
				
			out.println("</SCRIPT>"); 
	
			out.println("<body text=\"blue\" link=\"blue\" vlink=\"black\" alink=\"#FF2020\">");
			out.println("<p align=right><img src=\'../image/우측_기안결재.gif\'></p>");
			Calendar current = Calendar.getInstance();
			
			String doGet = req.getParameter("doGet");
			
			out.println("<FORM METHOD = POST name=\"form1\" action=\"/servlet/EDASubmitServlet\"enctype=multipart/form-data>");
			out.println("<p align=\"center\"><font face=\"돋움체\" size=\"5\" color=\"darkblue\"><b>결재 문서 작성</b></font><br>");
			out.println("<img src=\"../image/BBS_line.gif\" width=\"600\" >");
						
			out.println("<div align=\"center\"><table border=\"0\" cellpadding=\"2\" width=\"600\" >");
			out.println("<tr>");
			out.println("<td width=\"200\" align=\"center\" bgcolor=\"C7E4FF\"><p><font size=\"2\">" +
			 "제&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;목</font></td>");
	        	out.println("<td><p><font size=\"2\"><input type=text name=titleEdit size=40></font></td>");
	    		out.println("</tr>");
	    		
	    		out.println("<tr>");
	    		out.println("<td width=\"200\" align=\"center\" bgcolor=\"#C7E4FF\"><p><font size=\"2\">" +
	            	 "<p align=\"center\">문서&nbsp;분류</font></td>");
	            	out.println("<td><p><font size=\"2\"><select name=itemSel>");
	            	out.println("<option value=\"\"></option>");
	            	out.println("<option value=\"교육문서\">교육문서</option>");
	            	out.println("<option value=\"복리후생\">복리후생</option>");
	            	out.println("<option value=\"인사문서\">인사문서</option>");
	            	out.println("<option value=\"일반기안\">일반기안</option>");
	            	out.println("<option value=\"총무문서\">총무문서</option>");
	            	out.println("<option value=\"회계문서\">회계문서</option>");
	            	out.println("</select></font></td>");
	    		out.println("</tr>");    		
	    		    		
	    		out.println("<tr>");
	        	out.println("<td width=\"200\" align=\"center\" bgcolor=\"#C7E4FF\"><p><font size=\"2\">" +
	        	 "작&nbsp;&nbsp;성&nbsp;&nbsp자</font></td>");
	         	out.println("<td><p><font color=\"black\">&nbsp;&nbsp;&nbsp;" + name + "</td>");
	         	out.println("</tr>");
	         	
	         	out.println("<tr>");
	         	out.println("<td width=\"200\" align=\"center\" bgcolor=\"#C7E4FF\"><p><font size=\"2\">"+
	         	 "작성 일자</font></td>");
	         	out.println("<td><p><font color=\"black\">&nbsp;&nbsp;&nbsp"+
	        	 current.get(Calendar.YEAR) + "년" + (current.get(Calendar.MONTH)+1) + 
	        	 "월" + current.get(Calendar.DAY_OF_MONTH) + "일"+ "</td>");
	    		out.println("</tr>");
	        		    		
	   		out.println("<tr>");
	        	out.println("<td width=\"200\" align=\"center\" bgcolor=\"#C7E4FF\"><p><font size=\"2\">"+
	        	 "기안&nbsp;내용</font></td>");
	        	out.println("<td><p><font size=\"2\">"+
	        	 "<textarea name=commSEdit rows=8 cols=60></textarea></font></td>");
	        	out.println("</tr>");
	        	Map course = new HashMap();
			try{
	    			course = edaController.listApprovalCourse ( name + "(" + id + ")" );
	    		}
	    		catch( Exception e){}
	    		String[] courseArray = new String[ course.size() ];
	    		String[] courseView = new String[ course.size() ];
	    		for( int i=0 ; i < courseArray.length ; i++ ){
	    			courseArray[i] = "";
	    			courseView[i] = "";
	    		}
	    		List courseList = new ArrayList();
	    		int count = 0;
	    		for( Iterator i = course.entrySet().iterator(); i.hasNext() ; count++ ){
	    			Map.Entry e = (Map.Entry) i.next(); 
	    			courseList = (List)e.getValue();
	    			ApprovalCourse path = new ApprovalCourse();
	    			for ( int j = 0 ; j < courseList.size() ; j++ ){
	    				path = ( ApprovalCourse ) courseList.get( j );
	    				if( path.gettype() == ApprovalCourse.SUBMITAPPROVAL ){
	    					courseArray[ count ] = courseArray[ count ] + path.getpersonID() + "," + "결재" + ";" ;
	    					StringTokenizer st = new StringTokenizer ( path.getpersonID() , "(" );
	    					courseView[ count ] = courseView[ count ] + "->" + st.nextToken() + "(" + "결재" + ")"; 
	    				}
	    				else if ( path.gettype() == ApprovalCourse.SUBMITINFORM ){
	    					courseArray[ count ] = courseArray[ count ] + path.getpersonID() + "," + "통보" + ";" ;
	    					StringTokenizer st = new StringTokenizer ( path.getpersonID() , "(" );
	    					courseView[ count ] = courseView[ count ] + "->" + st.nextToken() + "(" + "통보" + ")";	    						
	    				}
	    			}
	    		}

	    		String defaultPath ="";
	      		try{
	      			defaultPath = (edaController.loadEDAOption ( name + "(" + id + ")" )).getdefaultPath();
	      		}catch( Exception e){}
	      		
	     		out.println("<tr>");
	        	out.println("<td width=\"200\" align=\"center\" bgcolor=\"C7E4FF\"><p><font size=\"2\">결재 경로</font></td>");
	        	out.println("<td><p><font size=\"2\"><select name=\"pathName1\" style=\"width:200pt\">");
			for( int i = 0 ; i < courseArray.length ; i++ ){
				if( defaultPath.equals( courseArray[i] ) )
					out.println("<option selected value=\'" + courseArray[i] + "\'>" + courseView[i] + "</option>");
				else	
					out.println("<option value=\'" + courseArray[i] + "\'>" + courseView[i] + "</option>");
			}
			out.println("</select>");
	        	out.println("&nbsp;<INPUT TYPE=\"BUTTON\" VALUE=\"결재경로\" OnClick=\"EDALineSelection()\">");
	        	out.println("<input type=\"checkbox\" name=\"pathStore\" value=\"store\"><b>경로&nbsp;저장</b></font></td>");
	        	out.println("</tr>");

			//파일 첨부 부분
;
	    		out.println("<tr>");
	        	out.println("<td width=200 align=\"center\" bgcolor=\"#C7E4FF\"><p><font size=\"2\">첨부 파일</font></td>");
	        	out.println("<td><p><font size=\"2\"><INPUT TYPE =\"BUTTON\" VALUE=\"파일첨부\" OnClick=\"AppendAttachFile()\"><BR>"+
	        	 "<INPUT NAME=\"ATTH0\" TYPE=\"FILE\" SIZE=45 STYLE=\"display:none\" ID=\"AtthBox0\">"+
	        	 "<INPUT NAME=\"ATTH1\" TYPE=\"FILE\" SIZE=45 STYLE=\"display:none\" ID=\"AtthBox1\">"+
	        	 "<INPUT NAME=\"ATTH2\" TYPE=\"FILE\" SIZE=45 STYLE=\"display:none\" ID=\"AtthBox2\">"+
	        	 "<INPUT NAME=\"ATTH3\" TYPE=\"FILE\" SIZE=45 STYLE=\"display:none\" ID=\"AtthBox3\">"+
	        	 "<INPUT NAME=\"ATTH4\" TYPE=\"FILE\" SIZE=45 STYLE=\"display:none\" ID=\"AtthBox4\">");
			out.println("</font></td></tr>");
			out.println("</table></div>");
			
	        	out.println("<p align=\"center\">"+
			 "<INPUT type=\"BUTTON\" value=\"상  신\" OnClick=\"Check_Form(this.form)\">");
	        	out.println("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+
			 "<INPUT style=HEIGHT: 20px\" type=\"RESET\" value=\"취  소\" ></p></td>");

			out.println("</form><p>&nbsp;</p></body></html>");
		}
		else{
			//사용자 인증에 실패했습니다.
			res.sendRedirect("../Login.html");
		}
		out.close();
	}

/*----------------------------------------------------------------- */
/**
 [메소드이름]: doPost<br>
 [기능]: 작성된 문서를 상신하는 함수.<br>
 [파라미터]: HttpServletRequest req,HttpServletResponse res<br>
 [호출자] : this<br>
 */
/*--------------------------------------------------------------- */		
	public void doPost( HttpServletRequest req , HttpServletResponse res)
		throws ServletException,IOException{
	
		HttpSession session = req.getSession(true);
		System.out.println("doPost함수 시작");
		res.setContentType("text/html;charset=euc-kr");
		//작성일자를 얻는 부분			
		Calendar current = Calendar.getInstance();
		String initYear = String.valueOf( current.get(Calendar.YEAR));
		String initMonth = String.valueOf((current.get(Calendar.MONTH) +1 ));
		String initDays = String.valueOf(current.get( Calendar.DAY_OF_MONTH ));
		String initHour = String.valueOf(current.get(Calendar.HOUR_OF_DAY));
		String initMinute = String.valueOf(current.get(Calendar.MINUTE));
		String initSecond = String.valueOf( current.get(Calendar.SECOND));
		initMonth = (initMonth.length()==1)?("0"+ initMonth):initMonth;
		initDays = (initDays.length()==1)?("0"+initDays):initDays;
		initHour = (initHour.length()==1)?("0"+initHour):initHour;
		initMinute = (initMinute.length()==1)?("0"+initMinute):initMinute;
		String initDay = initYear + "-" + initMonth + "-" + initDays + " " + initHour + ":" + initMinute + ":"+ initSecond ;
		String initTime = initMonth + initDays + initHour + initMinute;
		//사용 변수 선언
		String filepath = "c:/Groupware/file/EDA";//debug1 반드시 상대경로로 수정
		String filepath2= "./file/EDA";
		String initPerson="";
		String title="";
		String item="";
		String comm="";
		Vector file;
		//Class선언
		ApprovalDocument document;
		ApprovalCourse course;
		AttatchFile attatchFile;
		PrintWriter out = new PrintWriter(
		 new OutputStreamWriter(res.getOutputStream(), "EUC-KR"));
		 
		boolean authentication = false;

		String id = null;
		String name = null;
			
		if((session.isNew())){
			session.invalidate();
			res.sendRedirect("../Login.html");
		}
		else if(session.getValue("Authentication").equals("true")){
			authentication = true;
			id = (String) session.getValue("Id");
			name = (String) session.getValue("Name");
		}
		else{
			session.invalidate();
			res.sendRedirect("../Login.html");
		}
		if(authentication){
			//Title 출력
			out.println("<html><body>");
			out.println("<html><head><title>문서 상신</title></head>");
			out.println("<body text=\"black\" " +
		 	 "link=\"purple\" alink=\"red\"> ");
			out.println("<p align=right><img src=\'../image/우측_기안결재.gif\'></p>");
			ParseRequestData pD = new ParseRequestData(req.getInputStream());
				
			title = pD.getParameter("titleEdit");
			title = new String(title.getBytes("ISO-8859-1"),"KSC5601");

			item = pD.getParameter("itemSel");
			item = new String( item.getBytes("ISO-8859-1"), "KSC5601");

			comm = pD.getParameter("commSEdit");
			comm = new String( comm.getBytes("ISO-8859-1"), "KSC5601");

			System.out.println("제목 = " + title);//debug
			System.out.println("타입=" + item);//debug												
			System.out.println(comm);//debug
				
			//결재 경로를 저장하는 부분	 	
			String edapath = pD.getParameter("pathName1");
			edapath = new String( edapath.getBytes("ISO-8859-1"), "KSC5601");
			StringTokenizer st = new StringTokenizer( edapath ,";");
			Vector path = new Vector(); 
			Vector type = new Vector();
			while( st.hasMoreTokens() ){
				StringTokenizer st1= new StringTokenizer(st.nextToken(),",");
				path.add(st1.nextToken());
				type.add(st1.nextToken());
			}
			boolean store = false ;
			if ( ( pD.getParameter("pathStore") != null ) && ((pD.getParameter("pathStore")).equals("store")))
				store = true;
			// 파일저장
			file = pD.getAttachedFileNames();
			if(!file.isEmpty()){
				for(int i = 0 ; i< file.size() ; i++ ){
					try{
					//pD.saveFile( (String) file.elementAt(i) , filepath , initTime );
					pD.saveFile( filepath , initTime );
					}catch(Exception e){}				
					System.out.println( (String)file.elementAt(i) + "파일 업로드 성공");//debug		
				}
			}
			//ApprovalDocument Class 생성		
			item = item + initYear + initMonth ;
			document = new ApprovalDocument( item , initDay , name + "(" + id + ")",
			  ApprovalCourse.EDASUBMIT , title , comm ) ;
			System.out.println("문서 Class 생성");
			
			//상신자의 Path Class 생성	
			course = new ApprovalCourse( item, name + "(" + id + ")" , 0 , ApprovalCourse.EDASUBMIT,
			 ApprovalCourse.SUBMIT);
			System.out.println("첫번째 Path 생성");
			document.addapprovalCourse( course );

			//결재자들의 Path Class생성
			for( int i = 0 ; i< path.size() ; i++){
				if(((String)(type.elementAt(i))).equals("결재")){
					course = new ApprovalCourse( item , (String)path.elementAt(i), (i+1),
					 ApprovalCourse.NOTCOMPLETE , ApprovalCourse.SUBMITAPPROVAL );
					System.out.println((String)path.elementAt(i)+"결재");//debug
				}
				else {
					course = new ApprovalCourse( item , (String)path.elementAt(i), (i+1) ,
					 ApprovalCourse.NOTCOMPLETE , ApprovalCourse.SUBMITINFORM );
					System.out.println((String)path.elementAt(i)+"통보");//debug
				}
				document.addapprovalCourse ( course );
			}
			try{
				if( store ){
					ApprovalCourse[] courseArray = new ApprovalCourse[ path.size() ];
					//결재자들의 Path Class생성
					for ( int i = 1 ; i <= path.size() ; i++ )
						courseArray[i-1] = document.getapprovalCourse(i);
					
					System.out.println("결재 경로를 저장하기 위한 함수 시작");//여기부터
		
					EDAResultStatus result = edaController.saveApprovalCourse( name + "(" + id + ")" , null , courseArray );
	
					if( result.getResultStatus() == EDAResultStatus.SUCCESS )
						System.out.println("결재 경로 저장 성공");
					else{
						throw new Exception ( result.getReason() );
					}
				}
				//FileAccess Class Array 생성 및 Submit
				if(!file.isEmpty()){
					for( int i=0 ; i<file.size() ; i++){
			        		attatchFile = new AttatchFile( initTime+"-"+file.elementAt(i),
			        	 	 item,filepath2);  
			        		document.addattatchFile( attatchFile );
			        	}
				}
				System.out.println("DB Query 준비");//debug
				EDAResultStatus result1 = edaController.processRaiseApproval( document );
	
				if( result1.getResultStatus() == EDAResultStatus.FAILURE ){
					out.println("<p align=\"center\"><font size=\"4\" color=gray>"+
					 "<b>상신 실패</b></font></p>");
					out.println("<p align=\"center\"><hr width=\"80%\"><br>");
					out.println("Message : "+result1.getReason() );
				}
				else{
					
					out.println("<p align=\"center\"><font size=\"4\" color=gray>"+
					 "<b>상신 완료</b></font></p>");
					out.println("<p align=\"center\"><hr width=\"80%\"><br>");
					out.println("<div align=\"center\">");
					out.println("<table width=\"60%\">");
					out.println("<tr>");
					out.println("<td width=20%>제    목</td>");
					out.println("<td width=40%>"+title +"</td>");
					out.println("</tr>");
					out.println("<tr>");
					out.println("<td width=20%>문서번호</td>");
					out.println("<td width=40%>"+document.getdocID() +"</td>");
					out.println("</tr>");
					out.println("</table></div>");
					out.println("<p align=\"center\">"+
					 "<a href=\"http:/servlet/EDASubmitServlet\">"+
					 "새 문서 작성</a></p>");
					
				}

				out.println("</body></html>");		
			}
			catch(Exception e){
				System.out.println("Exception 발생 : " + e.toString() );
				System.out.println("확인 요망");
			}
		}else{
			res.sendRedirect("../Login.html");
		}
		out.close();
	}
}