

<%@page import="org.apache.poi.xwpf.usermodel.TOC"%>
<%@page import="kr.co.kihyun.prop.QueryStringList"%>
<%@page import="kr.co.iniline.swift.sp.api.SPApiManager"%>
<%@page import="java.net.HttpURLConnection"%>
<%@page import="java.net.URL"%>
<%@page import="org.apache.commons.lang.StringEscapeUtils"%>
<%@page import="java.util.Set"%>
<%@page import="java.io.ObjectInputStream"%>
<%@page import="java.io.InputStream"%>
<%@page import="java.util.Enumeration"%>
<%@page import="kr.co.kihyun.service.vo.TotReportVO"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.sql.ResultSetMetaData"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="kr.co.kihyun.db.CommonDBManager"%>
<%@page import="kr.co.kihyun.beans.entity.MUser"%>
<%@page import="kr.co.kihyun.beans.entity.MDept"%>
<%
	/**
     * **********************************************************@@ Program
     * Name : doc_list.jsp Description	: /집계자/내문서함/등록함/문서 목록 Author	: 기현테크
     * Create Date	: 2010.11.25 History	:
     * Modify Date	: 2015.03-03  /제출자료/제출진행/자료제출/자료상세 보기
     * @@***********************************************************
     */
%>

<%@ page contentType="text/html; charset=UTF-8"
	import="java.net.URLEncoder" import="java.net.URLDecoder"
	import="kr.co.kihyun.lang.MString" import="kr.co.kihyun.lang.MLong"
	import="kr.co.kihyun.text.html.HtmlUtil"
	import="kr.co.kihyun.lang.StringConverter"
	import="kr.co.kihyun.text.html.ServletUtil"
	import="kr.co.kihyun.beans.user.HttpSSOLogin"
	import="kr.co.kihyun.moumi.Moumi"
	import="kr.co.kihyun.moumi.report.MReport"
	import="kr.co.kihyun.moumi.MoumiConfig"
	import="kr.co.kihyun.beans.user.Dept"
	import="kr.co.kihyun.beans.user.UserView"
	import="kr.co.kihyun.beans.totsys.report.Report"
	import="kr.co.kihyun.beans.totsys.report.ReportView"
	import="kr.co.kihyun.beans.totsys.report.ReportViewManager"
	import="kr.co.kihyun.text.hml.Hwp"
	import="kr.co.kihyun.text.html.HtmlUtil"
	import="kr.co.kihyun.beans.totsys.report.tots.ReportsViewer"
	import="kr.co.kihyun.lang.MInteger"
	import="kr.co.kihyun.beans.totsys.doc.table.Table"
	import="kr.co.kihyun.beans.totsys.doc.table.item.Item"
	import="kr.co.kihyun.text.excel.Excel" import="org.slf4j.Logger"
	import="org.slf4j.LoggerFactory" import="kr.co.kihyun.beans.user.User"
	import="kr.co.kihyun.text.html.TagFilter"
	import="kr.co.kihyun.lang.MLong" import="javax.jdo.PersistenceManager"
	import="javax.jdo.Transaction"
	import="kr.co.kihyun.beans.entity.util.*"
	import="kr.co.kihyun.beans.entity.*"
	import="kr.co.kihyun.service.vo.PrssReportsVO"
	import="java.util.HashMap" import="java.util.Map"
	import="kr.co.kihyun.service.PrssReportsService"
	import="java.util.List" import="java.util.Map.Entry"
	import="javax.jdo.Query"
	%>

<%@ include file="/totsys/common/inc/sec/secure.inc.jsp"%>

<%
		//로그인 아이디 없을 시 로그인 세션 populate

		//if(HttpSSOLogin.getLoginID(request)==null){
		//    HttpSSOLogin sso=new HttpSSOLogin();
		//    sso.doPost(request,response);
		//}

		String usID;
		if(HttpSSOLogin.getLoginID(request) != null){
			usID = HttpSSOLogin.getLoginID(request);
		}else{
			usID = (String) session.getAttribute("SSO_USER_ID");
		}
		//out.print(HttpSSOLogin.getLoginID(request)+" ==== "+HttpSSOLogin.getDeptID(request));
		// 수정이력 첨부파일 다운로드
		String filedn=request.getParameter("filedn");
		String vid=request.getParameter("vid");
		String fn=request.getParameter("fn");


PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
Transaction tx = pm.currentTransaction();
CommonDBManager acdbm = new CommonDBManager();
ResultSet rs = null;
try {
        /**
         * ******* Parameter ********
         */

        String tmpStrMagam = MString.checkNull(request.getParameter("tmpStrMagam"));

				if(filedn!=null&&vid!=null&&fn!=null){
					if(filedn.equals("Y")){
						fn=StringEscapeUtils.unescapeHtml(fn);

						rs = acdbm.execQuery(QueryStringList.ReportVersionFileSql,vid);
						if(rs.next()){
							InputStream is = rs.getBinaryStream(1);
							if(is!=null){
								ObjectInputStream ois = new ObjectInputStream(is);
								Map<String, List<Byte>> map= (Map<String, List<Byte>>)ois.readObject();
								ois.close();
								is.close();
								Set<String> keyset=map.keySet();
						   		for(String fileName:keyset){
						   			if(fileName.equals(fn)){

						   				//20170919 파일명변환('-난수') 에러나서 remark처리함 by wonseok Lee
						   				//int checkComma = fileName.lastIndexOf(".");
						   	            // int checkCommaBefore = fileName.lastIndexOf("_");
						   	            //fileName = fileName.substring(0, checkCommaBefore).concat(fileName.substring(checkComma));
										fileName=URLEncoder.encode(fileName, "UTF-8").replaceAll(":","_").replace("+", " ") +";";
						   	    out.clear();
						   	    response.setContentType("application/octet-stream");
										response.setHeader("Content-Disposition","attachment; filename="+fileName);
										response.setHeader("Cache-Control","private");
										List<Byte> blist=map.get(fn);
											if(blist!=null){
							        		ServletOutputStream sos=response.getOutputStream();
												for(int b:blist)sos.write(b);
													sos.flush();
													sos.close();
											}
						   			}
								}
							}
						}
							out.flush();
							out.close();
							return;
					}
				}
				Long reportID = MLong.parseLong(request.getParameter("reportID"), null);
				String query = QueryStringList.CheckMigulhamSql;
				if(reportID == null){
					out.println("현재 접속자 수가 많아 서비스가 원할하지 않습니다. 잠시후 이용하여 주시기 바랍니다.");
					return;
				}

				rs = acdbm.execQuery(query,reportID);
				boolean isMigulham = false;
				if(rs.next()&&request.getRequestURI().contains("totsys/common/inc/documents/report/report_view.jsp")){
					isMigulham=true;
				}

				Logger LOG = LoggerFactory.getLogger(this.getClass());

        TotReport totReport = pm.getObjectById(TotReport.class, reportID);
        String Magam;
        String docName = totReport.getTotDoc().getName();
        Long downDocId = null;
        try {
            downDocId = totReport.getSlaveTotDoc().getId();
        } catch (Exception ex) {
            downDocId = null;
        }

        /* if(tmpMagamGubun.equals("99991230")){
         Magam="선착순집계";
         }else{
         Magam=tmpStrMagam;
         }*/
        // System.out.println("   tmpStrMagam:::::::"+tmpStrMagam);
        // TODO: extract method.
        String report = null;
        if (totReport.getSlaveTotDoc() == null) {
            report = TotReportUtil.toHTML(totReport);
        } else {
            TotDoc slaveDoc = totReport.getSlaveTotDoc();
            if (!slaveDoc.getCompReports(pm).isEmpty()) {
                report = TotReportUtil.toHTML(totReport.getTotDoc(), slaveDoc.getCompReports(pm));
            }
        }

        /**
         * ******* report view ******
         */
        String note = MString.checkNull(totReport.getNote());
        String realFileName = "";
        String viewFileName = "";
        for (String fileName : totReport.getAttachments().keySet()) {
            viewFileName += fileName + ";";
            realFileName += fileName + ";";
        }
        Long downDocID = totReport.getSlaveTotDoc() == null ? null : totReport.getSlaveTotDoc().getId();

        String[] realFileNameList = realFileName.split(";");
        String[] viewFileNameList = viewFileName.split(";");
        // 연계수정
//      String memo = MString.checkNull(totReport.getRecentHistory() == null ? null : totReport.getRecentHistory().getMemo());

        String url = clearXSS(request.getParameter("url"), "");

        if (url == null) {
            url = "";
        }
//			int visit = 0;

//			Board totperComment = totReport.getTotDoc().getBoard();
//
//			if (totperComment != null) {
//				tx.begin();
//				visit = totperComment.getVisit();
//				totperComment.setVisit(visit + 1);
//				pm.makePersistent(totperComment);
//				tx.commit();
//			}

		//수정이력 셀렉트 시작
		// PRSS = 5 만 셀렉트(결제자 수정)

		String sql = QueryStringList.SelectReportVersionSql;
		rs = acdbm.execQuery(sql,totReport.getId());
		ResultSetMetaData meta = rs.getMetaData();
		ArrayList<HashMap<String,String>> versionList=new ArrayList<HashMap<String,String>>();
		while(rs.next()){
		HashMap<String,String> map = new HashMap<String,String>();
		for(int i=1;i<=meta.getColumnCount();i++){
			String colName = meta.getColumnName(i);
			map.put(colName, rs.getString(colName));
		}
		versionList.add(map);
		}

		//수정이력 셀렉트 끝
%>
<html>
<head>

<link rel="stylesheet" href="/totsys/common/css/text.css"
	type="text/css">
<link rel="stylesheet" href="/totsys/common/css/kecttep.css"
	type="text/css">
<link rel="stylesheet" href="/totsys/common/css/tabs.css"
	type="text/css">
<link rel="stylesheet" href="/totsys/common/css/SquareButtons.css"
	type="text/css">
<script src="/totsys/common/js/rollover.js"></script>
<script src="/totsys/common/js/popup.js"></script>
<script type="text/javascript" src="/totsys/common/js/jquery-1.12.4.min.js"></script>
<script type="text/javascript"
	src="/totsys/common/js/jquery.fixFormTable.js"></script>
<script type="text/javascript"
	src="/totsys/common/js/jquery.custom.indicator.js"></script>
<script type="text/javascript">
	function fixShowError() {
		$(".formDiv").find("table td").children().show();
	}

	// 첨부파일 다운로드를 hidden iframe 으로 실행한다. (2014.09.05 by youngjun cho)
	function doDownloadFileTargetFrm(src) {
		var target = document.getElementById("hiddenFrm"); // iframe hidden element.
		target.src = src;
	}

	/*
	 * 테이블 각 셀 garbage 요소를 제거하여, 레이아웃을 정돈한다.
	 * 2014.09.15 by YoungJun Cho.
	 */

	$(document).ready(function() {
		$.fixViewFormTableForXMLNameSpace($(".formDiv")
				.find("table td").children(), {});
		//ie10,11 호환성보기 수정 - 테두리 없어지는 문제 수정
		$('#formDiv > table').attr({'border':'1','bo':'true'}).css('border','1px solid #000')
    	.find('td').each(function(i,o){
			if($(o).closest('table').attr('bo')=='true'){
				$(this).css('border','1px solid #000');
			}
  		});
		$('.versiondetail > td > table').attr('border', '1').css('border','1px solid #000');
		$('#formDiv span').css('line-height','2');
	});
	/* 자료입력 테이블 input element 뒤에 font, span 등의 불필요한 element 를 삭제처리. 끝 */

	var gEventY = 0;
	var gEventX = 0;
	/**
	 * Ajax기능을 사용하여 서버에 첨부파일 리스트을 요청하는 함수
	 * @param {type} p_deptId
	 * @param {type} p_lov_type
	 * @returns {undefined}
	 */
	//            function popupViewInner(p_index, obj_id, p_reportID) {
	//                gEventY = window.event.y;
	//                gEventX = window.event.x;
	//
	//                $.ajax({
	//                    url: "/servlet/kr.co.kihyun.service.servlet.AjaxProcessServlet",
	//                    type: "POST",
	//                    dataType: "json",
	//                    data: {
	//                        proc_type: "attatch_file",
	//                        index: p_index,
	//                        file_index: obj_id,
	//                        report_id: p_reportID
	//                    },
	//                    success: function(data) {
	//                        fn_callBackForSuccess(data);
	//                    },
	//                    error: function(e) {
	//                        alert("error=" + e);
	//                    },
	//                    beforeSend: function() {
	//                        $.customIndicator.show(window.self);
	//                    },
	//                    complete: function() {
	//                        $.customIndicator.hide(window.self);
	//                    }
	//                });
	//            }
	//
	//            /**
	//             * fn_getDeptLOV함수의 성공 시 호출되는 함수
	//             * @param {type} data
	//             * @returns {undefined}
	//             */
	//            function fn_callBackForSuccess(data) {
	//                var fileList = "";
	//
	//                var index = "";
	//                var fileIndex = "";
	//                var reportID = "";
	//                var fileName = "";
	//                var fileNameEncode = "";
	//
	//                if (data != null) {
	//                    for (var i = 0; i < data.length; i++) {
	//                        index = data[i].index;
	//                        fileIndex = data[i].fileIndex;
	//                        reportID = data[i].reportID;
	//                        fileName = data[i].fileName;
	//                        fileNameEncode = data[i].fileNameEncode;
	//                        fileList += "<span style='color: #FF9C1B; font-weight: bold;'>+첨부파일 " + (i + 1) + " : </span><a onclick=\"popupClose(\'" + fileIndex + "\');\" href=\'/servlet/kr.co.kihyun.text.html.HttpViewer?saveAs=" + fileNameEncode + "\&fileName=" + fileNameEncode + "\&reportID=" + reportID + "\' target=\'hiddenFrame\'>" + fileName + "</a><br />";
	//                    }
	//                    document.getElementById("fileName" + index).innerHTML = fileList;
	//                }
	//
	//                $(".ajdxjdrnfl").hide();
	//                /*
	//                 //+++++++++++++++++++++++++++++++++++++
	//                 //그외 첨부파일은 모두 클로즈한다.
	//                 var tempIndex = "";
	//                 $(".ajdxjdrnfl").each(function() {
	//                 tempIndex = $(this).attr("id")
	//                 if(fileIndex != tempIndex) {
	//                 cpt_layer = document.getElementById(tempIndex);
	//                 cpt_layer.style.display='none';
	//                 }
	//                 });
	//                 */
	//
	//                //cpt_layer = document.getElementById(fileIndex);
	//                cpt_layer = $("#" + fileIndex);
	//
	//                //gEventY = cpt_layer.offsetTop;
	//                //gEventX = cpt_layer.offsetLeft;
	//                if (cpt_layer.css("display") === "none") {
	//                    cpt_layer.css({
	//                        "top": function() {
	//                            return gEventY + 50;
	//                        },
	//                        "left": function() {
	//                            return gEventX - 100;
	//                        },
	//                        "width": 200
	//                    });
	//                    //cpt_layer.style.top = gEventY + 50; //window.event.y - 10;
	//                    //cpt_layer.style.left = gEventX - 100; //window.event.x - 130;
	//                    //cpt_layer.style.display='';
	//                    //cpt_layer.style.width = 200;
	//
	//                    cpt_layer.show();
	//                }
	//            }
	//수정하기 기능 함수
	var isMod = false;
	function toggleModify() {
		isMod = !isMod;
		$('#ifrmod').css('visibility', 'hidden');
		if (isMod) {
			$('#btnimg').attr({
				'src' : '/totsys/common/images/bt_modifycancel.gif',
				'alt' : '수정취소'
			});
			$.customIndicator.show(window.self);
			$('.viewArea').hide();
			$('.modArea').show();
			try {
				$('#ifrmod')[0].contentWindow.document
						.write($('[name=modifyFormsub]')[0].outerHTML);
				$('#ifrmod')[0].contentWindow.document.modifyFormsub.submit();

			} catch (e) {
				alert(e);
			}
		} else {
			$('#btnimg').attr({
				'src' : '/totsys/common/images/bt_modify.gif',
				'alt' : '수정하기'
			});
			$('.viewArea').show();
			$('.modArea').hide();
		}
	}
	var viewForm;
	function ifrmodLoaded() {
		try {
			if ($('#ifrmod')[0].contentWindow.fn_goToList) {
				$('#ifrmod')[0].contentWindow.fn_goToList = function() {
					parent.$.customIndicator.show(window.show);
					parent.location.href = parent.location.href;
				};
			}
			var ifrbody = $('#ifrmod')[0].contentWindow.document.body;
			$('#ifrmod').css('visibility', 'visible');
			ifrbody = $(ifrbody);
			viewForm = ifrbody.find('[name=viewForm]')[0].outerHTML;
			ifrbody.find('table:first').hide();
			ifrbody.find('#header').hide();
			ifrbody.find('#contents tbody:first > tr:lt(7)').hide();
			setTimeout(
					function() {
						var ifrbody = $('#ifrmod')[0].contentWindow.document.body;
						ifrbody = $(ifrbody);
						$('#ifrmod')
								.height(
										$('#ifrmod')[0].contentWindow.document.body.scrollHeight);
					}, 100);
			$.customIndicator.hide(window.self);
		} catch (e) {
		}
	}
	function versionFileDown(vid, fn) {
		$('#hiddenFrm').attr(
				'src',
				'/totsys/common/inc/documents/report/report_view.jsp?filedn=Y&vid='
						+ vid + '&fn=' + encodeURI(fn));
	}

</script>
<%if(request.getRequestURI().toString().contains("common/inc/documents/report/report_view.jsp")){ %>
<script>
// 미결함에서 열 경우 엑셀 다운로드 지원을 위해
	var outhtml='',clone;
	function downExl(ishan){
 		var clone=$('#formDiv').clone();
 		outhtml=clone.html().replace(/<!--[\s\S]*?-->/g,'');
 		//alert(outhtml);return;
 		$('#downexl').remove();
 		var form='<form id="downexl" style="display:none;" method="post" target="downexl" action="/totsys/common/inc/documents/report/report_view_excel2.jsp">';
 		//컨트롤키 누르고 클릭시 utf-8 로 다운로드
		try{
			if(event.ctrlKey){
        		form+='<input type="hidden" name="enc" value="utf-8"/>';
    		}
		}catch(e){}
 		form+='<input type="hidden" name="downexl" value="true"/>';
 		form+='<input type="hidden" name="outhtml" value=""/>';
 		form+='<input type="hidden" name="docname" value="<%=URLEncoder.encode(docName,"utf-8")%>"/>';
 		if(ishan)form+='<input type="hidden" name="ishan" value="true"/>';
 		form+='<iframe style="display:none;" name="downexl"></iframe>';
 		form+='</form>';
 		form=$(form).appendTo('body');
 		outhtml=encodeURIComponent(outhtml);
 		form.find('[name=outhtml]').val(outhtml);
 		form.submit();
	}
 </script>
<%} %>
</head>
<body>
	<form name="modifyFormsub" method="post"
		action="/totsys/repoper/mydocbox/tempbox/temp_report_modify.jsp"
		style="display: none;">
		<input type="hidden" name="strPage" value="1"> <input
			type="hidden" name="findOption" value=""> <input
			type="hidden" name="findWord" value=""> <input type="hidden"
			name="reportType" value=""> <input type="hidden"
			name="doctName" value="<%=totReport.getTotDoc().getName()%>">
		<input type="hidden" name="reportID" value="<%=reportID%>"> <input
			type="hidden" name="totperInfo" value=""> <input
			type="hidden" name="tmpStrMagam" value="<%=tmpStrMagam%>">
	</form>
	<table width="100%" border="0" cellspacing="0" cellpadding="0">
		<tr valign="top"
			style="padding-top: 10; padding-bottom: 25; padding-left: 10;">
			<!------------------------------- 집계자 정보 시작 ------------------------------->
			<jsp:include page="/totsys/common/inc/totper/totper.jsp" flush="true">
				<jsp:param name="docID" value='<%=totReport.getTotDoc().getId()%>' />
				<jsp:param name="tmpMagam" value="<%=tmpStrMagam%>" />
			</jsp:include>
			<!------------------------------- 집계자 정보 끝 --------------------------------->
		</tr>
		<tr valign="top" style="padding-top: 10px; padding-bottom: 25px;">
			<td colspan="4">
				<table border="0" width="800" cellpadding="0" cellspacing="0">
					<tr>
						<td>
							<table border=0 cellpadding="0" cellspacing="0">
								<tr>
									<td class="kecttep_tdmenu" width="147" nowrap
										style="padding-left: 20px;"><%=MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.executionCode")%>
									</td>
									<td class="kecttep_top2_graytd" style="padding-left: 15;">
										<%=totReport.getTotDoc().getExecutionCode()%>
									</td>
								</tr>
							</table>
						</td>
					</tr>
					<tr>
						<td>
							<table border=0 cellpadding="0" cellspacing="0">
								<tr>
									<td class="kecttep_tdmenu" width="147" nowrap
										style="padding-left: 20px;"><%=MoumiConfig.getMessageBundle().getString("moumi.message.tot_report.acceptanceCode")%>
									</td>
									<td class="kecttep_top2_graytd" style="padding-left: 15;">
										<%=totReport.getAcceptanceCode()%>
									</td>
								</tr>
							</table>
						</td>
					</tr>
				</table>
			</td>
		</tr>
		<!---- 본문  시작---->
		<!-- 수정내역 히스토리 시작-->
		<% if( (downDocId == null || downDocId == 0L)){
		%>

		<tr class="modHistory">
			<td><br />
			<br />
				<table width="100%" border="0" cellspacing="0" cellpadding="0">
					<tbody>
						<tr>
							<td style="width: 14px;"><img
								src="/totsys/common/images/ico_3.gif"></td>
								<!-- 자료수정내역토글 -->
							<td width="250" align="left" class="kecttep_title"
								style="padding-left: 5px;cursor: pointer;" onclick="$('.versionTbl').toggle();">자료 수정 내역 확인</td>
							<td>&nbsp;</td>
							<td>&nbsp;</td>
						</tr>
					</tbody>
				</table>
				<table width="800" class="kecttep_list_table versionTbl" style="display: none;"
					bordercolor="#e3e3e3" border="1" cellspacing="0" cellpadding="0">
					<tbody>
						<tr>
							<td align="center" class="kecttep_tdmenu" nowrap="">&nbsp;수정자&nbsp;</td>
							<td align="center" class="kecttep_tdmenu">&nbsp;부서명&nbsp;</td>
							<td align="center" class="kecttep_tdmenu">&nbsp;수정일자&nbsp;</td>
							<td align="center" class="kecttep_tdmenu" nowrap="">&nbsp;비고&nbsp;</td>
						</tr>
						<%
							for(HashMap<String,String> row:versionList){
						%>
						<tr valign="middle"
							style="padding-top: 3px; background-color: white; cursor: pointer; height: 25px; text-align: center;"
							onmouseover="this.style.backgroundColor = 'F9F9F9'"
							onmouseout="this.style.backgroundColor = 'white'"
							bgcolor="#ffffff"
							onclick="$('.versiondetail').not($(this).next()).hide();$(this).next().toggle();">
							<td class="kecttep_graytd vtcen" nowrap=""><%=row.get("MODIFIER_NAME")%>(<%=row.get("MODIFIER_ID")%>)
							</td>
							<td class="kecttep_graytd vtcen" nowrap=""><%=row.get("MODIFIER_DEPT_NAME")%>
							</td>
							<td class="kecttep_graytd vtcen" nowrap=""><%=row.get("REG_DATE").substring(0,16)%>
							</td>
							<td class="kecttep_last_graytd vtcen" nowrap="">&nbsp;</td>
						</tr>
						<!-- 수정 이력 상세 -->
						<tr class="versiondetail" style="display: none;">
							<td colspan="4" style="padding: 10px;">
								<%
									String id=row.get("ID");


				            			rs = acdbm.execQuery("SELECT TEMPLATE_HTML FROM MOUMI_TOT_REPORT_VERSION where id=? with ur",id);
				            			if(rs.next()){
				            				out.print(rrs.getString(1));
				            			}




				            			rs = acdbm.execQuery("SELECT attachments FROM MOUMI_TOT_REPORT_VERSION where id=? with ur",id);
				            			if(rs.next()){
				            				InputStream is = rs.getBinaryStream(1);
				            				if(is!=null){
				            					ObjectInputStream ois = new ObjectInputStream(is);
					            				Map<String, List<Byte>> map= (Map<String, List<Byte>>)ois.readObject();
					            				ois.close();
					            				is.close();
					            				Set<String> keyset=map.keySet();
					            				if(keyset.size()>0){
																	out.print("<table border='0' cellspacing='0' cellpadding='0'>");
																	out.print("<tbody><tr>");
																	out.print("<td style='width: 14px;'>");
																	out.print("<img src='/totsys/common/images/ico_1.gif'></td>");
																	out.print("<td align='left' class='kecttep_title' style='padding-left: 5px;'>[첨부파일]</td>");
																	out.print("</tr>");
																	out.print("</tbody></table>");
																	int idx=1;
						            				for(String fileName:keyset){
						            					out.print("<font color=\"#FF6600\">");
						            					out.print("<b>+</b>");
						            					out.print(Moumi.getMessageBundle().getString("moumi.message.tot_doc.add"));
						            					out.print(Moumi.getMessageBundle().getString("moumi.message.tot_doc.file")+idx++);
						            					out.print("</font>&nbsp;");
						            					out.print("<a href=\"javascript:void(0)\" onclick=\"versionFileDown("+id+",'"+fileName+"');\">");
						            					//20170919 파일명변환('-난수') 에러나서 remark처리함 by wonseok Lee
						            					//int checkComma = fileName.lastIndexOf(".");
					                                    //int checkCommaBefore = fileName.lastIndexOf("_");
					                                    //fileName = fileName.substring(0, checkCommaBefore).concat(fileName.substring(checkComma));
						            					out.print(MString.checkNull(fileName));
						            					out.print("</a><br/>");
					            					}
					            				}
				            				}
				            			}


								%>
							</td>
						</tr>
						<%
							}
						%>

					</tbody>
				</table> <br /></td>
		</tr>
	<%}else{


		}%>

		<!-- 수정내역 히스토리 끝-->
		<tr>
			<td width="80">
				<!-- 수정하기 기능 추가 -->
				<table>
					<tr>
						<td>
							<%
								if (downDocId == null || downDocId == 0L) {
							%>
						<!--
							 <a
							href="/totsys/common/inc/documents/report/report_view_excel1.jsp?reportID=<%=reportID%>"
							target="_parent"> <img
								src="/totsys/common/images/bt_excel.gif"
								alt="<%=MoumiConfig.getMessageBundle().getString("moumi.message.button_small.excel")%>" />
						</a>
						 -->
						 <img style="cursor: pointer;" onclick="downExl();" src="/totsys/common/images/bt_excel.gif" alt="<%= MoumiConfig.getMessageBundle().getString("moumi.message.button_small.excel")%>" />
						 <%
 	} else {
 %>
 <a
							href="/totsys/common/inc/documents/tot_reports/total_reports_excel.jsp?reportID=<%=reportID%>&gradeCode=-1&searchType=-1&displaySummary=false&docID=<%=downDocId%>&tableNum=&docName=<%=URLEncoder.encode(docName, "UTF-8")%>"
							target="_parent"> <img
								src="/totsys/common/images/bt_excel.gif"
								alt="<%=MoumiConfig.getMessageBundle().getString("moumi.message.button_small.excel")%>" />
						</a>
<%}%>
						</td>
						<td>
							<!-- 수정버튼 --> <%
 	if(isMigulham && (downDocID == null)){
 %> <img id="btnimg"
							src="/totsys/common/images/bt_modify.gif" alt="수정하기"
							style="cursor: pointer;" onclick="toggleModify();" /> <%
 	}
 %>
						</td>
					</tr>
				</table>
			</td>
		</tr>

		<tr class="modArea" style="display: none;">
			<td><br /> <iframe id="ifrmod" onload="ifrmodLoaded();"
					style="height: 500%; width: 100%; border-width: 0; visibility: hidden;"
					frameborder="0"></iframe></td>
		</tr>
		<tr class="viewArea">
			<td>
				<%


					StringBuffer htm = null;
                    htm = new StringBuffer();
                    htm.append(report);

                    int tag_textinput_idx = 0;

                    while (true) { //자료입력창 한글에서 박스로 안묶이고 보이게 하기.
                        tag_textinput_idx = htm.indexOf("<table width=700 border=0><tr><td width='100%' align=left>");
                        if (tag_textinput_idx != -1) {
                            int serch_textinput = htm.indexOf("</td></tr></table>",
                                    tag_textinput_idx);
                            htm = htm.replace(serch_textinput,
                                    serch_textinput + 18,
                                    "</TEXT></P></td></tr><tr><td><P><TEXT>");
                            htm = htm.replace(tag_textinput_idx,
                                    tag_textinput_idx + 58,
                                    "</TEXT></P></td></tr><tr><td><P><TEXT>");
                        } else {
                            break;
                        }
                    }

                    tag_textinput_idx = 0;

                    while (true) {
                        tag_textinput_idx = htm.indexOf("<table width=700 border=0>");
                        if (tag_textinput_idx != -1) {
                            int serch_textinput = htm.indexOf("</td></tr></table>",
                                    tag_textinput_idx);
                            htm = htm.replace(serch_textinput,
                                    serch_textinput + 18,
                                    "</TEXT></P></td></tr><tr><td><P><TEXT>");
                            htm = htm.replace(tag_textinput_idx,
                                    tag_textinput_idx + 71,
                                    "</TEXT></P></td></tr><tr><td><P><TEXT>");
                        } else {
                            break;
                        }
                    }
				%> <!---------------------- reportForm start -------------------->
				<%
					if (downDocID != null) {

		               tx.begin();

		               TotDoc totDoc = pm.getObjectById(TotDoc.class, downDocID);
		               MUser mUser = pm.getObjectById(MUser.class, usID);
				       String dtID = MString.checkNull(mUser.getDept());
		               int searchType = MInteger.parseInt(request.getParameter("searchType"), -1);
		               Long docID = totDoc.getId();
		               int listType = TotReportProcess.ALL.ordinal();
		               String innerFindOption = "";
		               String innerFindWord = "";
		               String howSort = "";
		               String sort = "2";

		               if (searchType >= 0) {
		                   if (searchType == TotReportProcess.COMP.ordinal()) {
		                       listType = TotReportProcess.COMP.ordinal();
		                   } else if (searchType == TotReportProcess.ACCEPT.ordinal()) {
		                       listType = TotReportProcess.ACCEPT.ordinal();
		                   } else {
		                       listType = TotReportProcess.ALL.ordinal();
		                   }
		               }

		               int count = 0;

		               PrssReportsService prssService = new PrssReportsService(pm);

		               Map params = new HashMap();
		               params.put("docId", docID);
		               params.put("listType", listType);
		               params.put("findOption", innerFindOption);
		               params.put("filterValue", innerFindWord);
		               params.put("howSort", howSort);
		               params.put("sort", sort);
		               params.put("dpId", dtID);

		               //검색메인쿼리와 레코드갯수조회쿼리를 생성 후 멤버변수로 저장
		               prssService.createPrssTotalReportsSearchQuery(params);

		               List<PrssReportsVO> list = null;
		               //만족하는 레코드가 존재하면 조회
		               list = prssService.executeQuery(PrssReportsVO.class);

		               count = list.size();

		               int index = -1;
		               int slavePaddingLeft = 0;
		               for (int i = 0; i < count; i++) {
		                   index = i;

		                   PrssReportsVO prssVO = (PrssReportsVO) list.get(i);
		                   TotReportProcess process = (TotReportProcess) prssVO.getProcess();

		                   if ("2".equals(prssVO.getDeptNo())) {
		                       slavePaddingLeft = 30;
		                   } else {
		                       slavePaddingLeft = 0;
		                   }

		                   int kkk = prssVO.getProcess().ordinal();
		                   String html = null;
		                   if (process == TotReportProcess.COMP && prssVO.getDownDocId() == null) {
		                       TotReport totReportVO = pm.getObjectById(TotReport.class, prssVO.getId());
		                       html = Excel.adjustFmlaToExcel(TagFilter.removeBlankPara(TotReportUtil.toHTML(totReportVO))); //표를 만들어 찍어주는 부분
		                   }
				%>
				<table border="0" width="100%" cellpadding="0" cellspacing="0">
					<tr>
						<td class="kecttep_title" style="padding-left: 5" align="left"
							width="100%"><img src="/totsys/common/images/ico_1.gif">
							<%=prssVO.getOrganName() == null ? "" : prssVO.getOrganName()%>&nbsp;&nbsp;
							<%=prssVO.getDeptName() == null ? "" : prssVO.getDeptName()%>&nbsp;&nbsp;
							<%=prssVO.getOwnerName() == null ? "" : prssVO.getOwnerName()%>
						</td>
					</tr>
					<tr>
						<td>
						<%
							//연계문서 상세내용 파일취합일경우 서식 출력안함
							if(totReport.getTotDoc().getAppendType()!=TotDocAppendType.FILE){
						%>
							<div id="formDiv" class="formDiv"
								style="padding-top: 20; overflow-x: auto;">
								<%--<%= Excel.adjustFmlaToExcel(TagFilter.removeBlankPara(TotReportUtil.toHTML(totReportVO))) %>--%>
								<%=(process == TotReportProcess.COMP) ? html : ""%>
							</div>
						<%} %>
						</td>
					</tr>
					<%
						if ("Y".equals(prssVO.getIsAttachments())) {
					                                /*<%-- if (!reportList.get(d).getAttachments().isEmpty()) { */
					%>
					<tr>
						<td style="padding-left: <%=slavePaddingLeft%>" align="left">
							<%
								for (String fileName : prssVO.getAttachmentsMap(pm).keySet()) {
							%> <!--// iframe 으로 target 을 지정한 첨부파일 다운로드 (2014.09.05 by youngjun cho) -->
							<font color="#FF6600"> <b>+</b><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.add")%><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.file")%>
						</font>&nbsp; <a href="javascript:void(0)"
							onclick="doDownloadFileTargetFrm('/servlet/kr.co.kihyun.text.html.HttpViewer?fileName=<%=URLEncoder.encode(fileName, "UTF-8")%>&checkFile=Y&reportID=<%=prssVO.getId()%>')">

								<%	//20170918 난수 걸러내는 처리 안하게 함. by wonseok Lee
									//int checkComma = fileName.lastIndexOf(".");
								    //                                int checkCommaBefore = fileName.lastIndexOf("_");
								    //                                fileName = fileName.substring(0, checkCommaBefore).concat(fileName.substring(checkComma));
								%> <%=MString.checkNull(fileName)%>
						</a><br /> <!--iframe 으로 target 을 지정한 첨부파일 다운로드 //-->
						<%
						 	}
						 %>
						</td>
					</tr>
					<%
						}
					%>
				</table> <br />
				<%
					}
                     tx.rollback();
                 } else {
                	 //파일취합일경우 서식 출력안함
                	 if(totReport.getTotDoc().getAppendType()!=TotDocAppendType.FILE){
		 				%>
						<div id="formDiv" class="formDiv"
							style="padding-top: 20; overflow-x: auto;">
							<%--
		                	ie10,11 호환성 보기 스타일 문제 수정
		                    <%=report.replaceAll("<td", "<td style='word-break:break-all;' ")%>
		                 --%>
							<%=report%>
						</div> <script>
							$('#formDiv td').each(function() {
								$(this).css('word-break', 'break-all');
							});
						</script>
						<%
                	 }
				}
 				%>
			</td>
			<!---- 본문  끝---->
		</tr>

		<%
			if (realFileNameList.length != 0 && !MString.isNull(realFileNameList[0])) {
		%>
		<tr class="viewArea">
			<td colspan="4">
				<table border="0" cellpadding="0" cellspacing="0">
					<tr>
						<td style="width: 14"><img
							src="/totsys/common/images/ico_1.gif"></td>
						<td class="kecttep_title" style="padding-left: 5" align="left">[<%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.add")%><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.file")%>]
						</td>
					</tr>
				</table>
			</td>
		</tr>

		<tr class="viewArea">
			<td colspan="4">
				<div id="repoperMessage" style="display: '';">
					<table border="0" cellpadding="0" cellspacing="0">
						<%
							if (realFileNameList[0] != null && realFileNameList[0] != "") {
						                                for (int i = 0; i < realFileNameList.length; i++) {
						                                    if (i == 0) {
						%>
						<%
							}
						%>
						<tr>
							<td class="body" style="padding-left: 20"><font
								color="#FF6600"> <b>+</b><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.add")%><%=Moumi.getMessageBundle().getString("moumi.message.tot_doc.file")%>
									<%=(i + 1)%>
							</font>&nbsp; <!--// iframe 으로 target 을 지정한 첨부파일 다운로드 (2014.09.05 by youngjun cho) -->
								<a href="javascript:void(0)"
								onclick="doDownloadFileTargetFrm('/servlet/kr.co.kihyun.text.html.HttpViewer?fileName=<%=URLEncoder.encode(realFileNameList[i], "UTF-8")%>&checkFile=Y&reportID=<%=reportID%>')">
									<!--20170821 수정  by wonseok Lee-->
									<%=realFileNameList[i]%>

									<%
										//int checkComma = viewFileNameList[i].lastIndexOf(".");
									    //                                int checkCommaBefore = viewFileNameList[i].lastIndexOf("_");
									    //                                viewFileNameList[i] = viewFileNameList[i].substring(0, checkCommaBefore).concat(viewFileNameList[i].substring(checkComma));
									%>

							</a>
							<!-- iframe 으로 target 을 지정한 첨부파일 다운로드 //--></td>
						</tr>
						<%
							}
						                            }
						%>
						<tr>
							<td style="padding-left: 20">
								<p class="body">
									<font class="body"><%=HtmlUtil.toHtml(note)%></font>
								</p>
							</td>
						</tr>
					</table>
				</div>
			</td>
		</tr>
		<%
			}
		%>
	</table>

	<!--// 첨부파일 다운로드 서블릿을 호출할 iframe. (2014.09.05 by youngjun cho) -->
	<iframe id="hiddenFrm" frameborder="0" width="0" height="0" src=""
		style="display: none"></iframe>
	<!-- 첨부파일 다운로드 서블릿을 호출할 iframe //-->
</body>
</html>

<%
	} catch (Exception ex) {
				if(null != rs) rs.cloase();
        ex.printStackTrace();
        out.println(kr.co.kihyun.text.html.ServletUtil.getJavaScript("alert('" + Moumi.getMessageBundle().getString("moumi.message.popup.requestAdmin") + "');"));
        out.println(kr.co.kihyun.text.html.ServletUtil.getJavaScript("history.back(-1);"));
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        acdbm.execClose();
        pm.close();
    }
%>
