<%@page import="kr.co.kihyun.db.CommonDBManager"%>
<%@page import="java.util.Arrays"%>
<%@page import="com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader.Array"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="kr.co.kihyun.db.DBManager"%>
<%  /**
     * **********************************************************
     * @@ Program Name : total_reports.jsp
     * @@ Description : /집계자/내문서함/진행함/집계현황
     * @@ Author : 강원중
     * @@ Create Date : 2004.10.11
     * @@ History : 2014.10.07 Update by KWON,HAN :
     * @@***********************************************************
     */
%>
<%@ page contentType="text/html; charset=UTF-8"
         import="java.text.SimpleDateFormat"
         import="java.util.List"
         import="java.util.ArrayList"
         import="java.util.Map"
         import="java.util.HashMap"
         import="java.net.URLEncoder"
         import="java.net.URLDecoder"
         import="kr.co.kihyun.lang.MString"
         import="kr.co.kihyun.lang.MLong"
         import="kr.co.kihyun.lang.MInteger"
         import="kr.co.kihyun.lang.Encoder"
         import="kr.co.kihyun.text.html.TagFilter"
         import="kr.co.kihyun.beans.user.HttpSSOLogin"
         import="kr.co.kihyun.moumi.doc.MDoc"
         import="kr.co.kihyun.moumi.report.MReport"
         import="kr.co.kihyun.moumi.Moumi"
         import="kr.co.kihyun.moumi.MoumiConfig"
         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.beans.totsys.doc.table.Table"
         import="kr.co.kihyun.beans.totsys.doc.table.item.Item"
         import="kr.co.kihyun.beans.entity.TotDoc2"
         import="kr.co.kihyun.beans.entity.MDept"
         import="kr.co.kihyun.service.PrssReportsService"
         import="kr.co.kihyun.service.vo.PrssReportsVO"
         import="kr.co.kihyun.service.vo.ReportTotalVO"
         import="javax.jdo.Query"%>
<%@ include file="/totsys/common/inc/sec/secure.inc.jsp"%>
<%
	String strRid=request.getParameter("rid");
	Long rid=Long.parseLong(strRid);
    PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
    Transaction tx = pm.currentTransaction();

    try {

        String usID = HttpSSOLogin.getLoginID(request);
        int sysAuth = HttpSSOLogin.getSysAuth(request);
        String dpID = HttpSSOLogin.getDeptID(request);
//        String dpNM = HttpSSOLogin.getDeptName(request);//20160421 추가 - 부서명

        /**
         * **** Parameter *****
         */
        Long docID = MLong.parseLong(request.getParameter("docID"), null);
//        int tableNum = MInteger.parseInt(request.getParameter("tableNum"), 0); //전체내용이 우선적으로 보여지도록 할 때 적용
        int tableNum = MInteger.parseInt(request.getParameter("tableNum"), 1);  //1번표가 우선적으로 보여지도록 할 때 적용
        String docType = clearXSS(request.getParameter("docType"), null);
        Long reportID = MLong.parseLong(request.getParameter("reportID"));

        int searchType = MInteger.parseInt(request.getParameter("searchType"), -1);
        String prssSelected = request.getParameter("prssSelect");
        boolean prssSelect = prssSelected != null;
//        System.out.println(" -------------- " + prssSelect);
        String[] displaySummaryValues = request.getParameterValues("displaySummary");
        boolean displaySummary = displaySummaryValues != null;
        int gradeCode = MInteger.parseInt(request.getParameter("gradeCode"), -1);
        String type = clearXSS(request.getParameter("type"), "");
        int rowDelType = MInteger.parseInt(request.getParameter("rowDelType"), 0);
        String tableval = clearXSS(request.getParameter("tableval"), "0");

        String strPage = clearXSS(request.getParameter("strPage"), "");
        String findOption = clearXSS(request.getParameter("findOption"), "");
        String findWord = URLDecoder.decode(MString.checkNull(request.getParameter("findWord")), "UTF-8");
        String stDate = clearXSS(request.getParameter("stDate"), "");
        String edDate = clearXSS(request.getParameter("edDate"), "");

        String searchDepth = clearXSS(request.getParameter("searchDepth"), "");
        String innerStrPage = "";
        String innerFindOption = "";
        String innerFindWord = "";

        if ("inner".equals(searchDepth)) {
            innerStrPage = clearXSS(request.getParameter("innerStrPage"), "");
            innerFindOption = clearXSS(request.getParameter("innerFindOption"), "");
            innerFindWord = URLDecoder.decode(MString.checkNull(request.getParameter("innerFindWord")), "UTF-8");
        } else {
            innerStrPage = clearXSS(request.getParameter("innerStrPage"), "");
            innerFindOption = clearXSS(request.getParameter("innerFindOption"), "");
            //검색어 깨어짐 해결
            innerFindWord = URLDecoder.decode(MString.checkNull(request.getParameter("innerFindWord")), "UTF-8");
        }
        String sort = clearXSS(request.getParameter("sort"), "");
        int listType = searchType;
        String howSort = clearXSS(request.getParameter("howSort"), "");

        if(findWord != null || innerFindWord != null){
            String[] filter_word= {"--", "\\(", "\\)", "\\'", "\\\""};
            for(int ii=0; ii< filter_word.length;ii++){
                findWord = findWord.replaceAll(filter_word[ii], "");
                innerFindWord = innerFindWord.replaceAll(filter_word[ii], "");
            }
        }

        String mngcode = clearXSS(request.getParameter("mngcode"), "");//20160509 추가
        if( "PRSS".equals(docType) && dpID.contains("A00") && docID > 1700000000){
        mngcode = "".equals(mngcode) ? "": mngcode ;//20160509 추가
        }
        tx.begin();

        TotDoc totDoc = pm.getObjectById(TotDoc.class, docID);
        String userId = totDoc.getUser();
        AccessAuth docAccAuth = totDoc.getAccessAuth();
        String docName = totDoc.getName();
        String regID = totDoc.getUser(pm).getId();
        String deptID = totDoc.getDept(pm).getId();

        //======================================================================
        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("mngcode", mngcode);//20160509 추가 교육청 코드
        params.put("dpId", dpID);//20160509 추가 교육청 코드
//        System.out.println("params ------------- " + params);

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

        List<PrssReportsVO> list = null;

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


        count = list.size();
        //======================================================================

        List<TotReport> compReportList = null;  //전체
        List<TotReport> organReportList = null; //기관
        List<TotReport> gradeReportList1 = null; //학교
        List<TotReport> gradeReportList2 = null; //학교
        List<TotReport> gradeReportList3 = null; //학교
        List<TotReport> gradeReportList4 = null; //학교
        List<TotReport> gradeReportList5 = null; //학교

        int allReportCount = 0;          //전체-전체
        int organReportCount_all = 0;    //기관-전체
        int gradeReport1Count_all = 0;   //유치원-전체
        int gradeReport2Count_all = 0;   //초등학교-전체
        int gradeReport3Count_all = 0;   //중학교-전체
        int gradeReport4Count_all = 0;   //고등학교-전체
        int gradeReport5Count_all = 0;   //기타학교-전체

        int totReportCount = 0;          //전체-제출완료
        int organReportCount = 0;        //기관-제출완료
        int gradeReport1Count = 0;       //유치원-제출완료
        int gradeReport2Count = 0;       //초등학교-제출완료
        int gradeReport3Count = 0;       //중학교-제출완료
        int gradeReport4Count = 0;       //고등학교-제출완료
        int gradeReport5Count = 0;       //기타학교-제출완료

        if (displaySummary) {
            List totalList = null;
            totalList = prssService.getReportTotalByDocId(docID);

            if (totalList != null && totalList.size() > 0) {
                for (Object obj : totalList) {
                    ReportTotalVO totalVO = (ReportTotalVO) obj;

                    allReportCount = MInteger.parseInt(totalVO.getAllCnt().toString(), 0);
                    organReportCount_all = MInteger.parseInt(totalVO.getAllOrganCnt().toString(), 0);
                    gradeReport1Count_all = MInteger.parseInt(totalVO.getAllGrade1Cnt().toString(), 0);
                    gradeReport2Count_all = MInteger.parseInt(totalVO.getAllGrade2Cnt().toString(), 0);
                    gradeReport3Count_all = MInteger.parseInt(totalVO.getAllGrade3Cnt().toString(), 0);
                    gradeReport4Count_all = MInteger.parseInt(totalVO.getAllGrade4Cnt().toString(), 0);
                    gradeReport5Count_all = MInteger.parseInt(totalVO.getAllGrade5Cnt().toString(), 0);

                    totReportCount = MInteger.parseInt(totalVO.getTotReportCnt().toString(), 0);
                    organReportCount = MInteger.parseInt(totalVO.getOrganReportCnt().toString(), 0);
                    gradeReport1Count = MInteger.parseInt(totalVO.getGrade1ReportCnt().toString(), 0);
                    gradeReport2Count = MInteger.parseInt(totalVO.getGrade2ReportCnt().toString(), 0);
                    gradeReport3Count = MInteger.parseInt(totalVO.getGrade3ReportCnt().toString(), 0);
                    gradeReport4Count = MInteger.parseInt(totalVO.getGrade4ReportCnt().toString(), 0);
                    gradeReport5Count = MInteger.parseInt(totalVO.getGrade5ReportCnt().toString(), 0);
                }
            }

            if (totReportCount > 0) {
                compReportList = prssService.getRecursiveAllReports(docID, TotReportProcess.COMP, "");       //전체-제출완료
            }
            if (organReportCount > 0) {
                organReportList = prssService.getRecursiveAllReports(docID, TotReportProcess.COMP, "organ");  //기관-제출완료
            }
            if (gradeReport1Count > 0) {
                gradeReportList1 = prssService.getRecursiveAllReports(docID, TotReportProcess.COMP, "1");      //1 유치원-제출완료
            }
            if (gradeReport2Count > 0) {
                gradeReportList2 = prssService.getRecursiveAllReports(docID, TotReportProcess.COMP, "2");      //2 초등학교-제출완료
            }
            if (gradeReport3Count > 0) {
                gradeReportList3 = prssService.getRecursiveAllReports(docID, TotReportProcess.COMP, "3");      //3 중학교-제출완료
            }
            if (gradeReport4Count > 0) {
                gradeReportList4 = prssService.getRecursiveAllReports(docID, TotReportProcess.COMP, "4");      //4 고등학교-제출완료
            }
            if (gradeReport5Count > 0) {
                gradeReportList5 = prssService.getRecursiveAllReports(docID, TotReportProcess.COMP, "5");      //4 기타학교-제출완료
            }

        }

        tx.commit();

        /**
         * ********* HTML Form values **********
         */
        int tableCount = new Table().getCount(docID);
        int[] lineNum = new int[tableCount];
        String[] delSelect = new String[tableCount];
        StringBuffer queryBuff = new StringBuffer();
        if (rowDelType == 1) {
            for (int i = 0; i < tableCount; i++) {
                if (type.equals("first")) {
                    if (i == 0) {
                        lineNum[i] = 1;
                    } else {
                        lineNum[i] = MInteger.parseInt(request.getParameter("table" + i + ""), -1);
                    }
                } else {
                    lineNum[i] = MInteger.parseInt(request.getParameter("table" + i + ""), 0);
                }

                queryBuff.append("&table" + i + "=" + lineNum[i]);
            }
        }
                        int index = -1;
                        int slavePaddingLeft = 0;
                        //tx.begin();
                        String reportIds = ""; //20160419 추가

                        if (count > 0) {
                            int listCount = list.size();

                            for (int i = 0; i < listCount; i++) {
                                index = i;

                                PrssReportsVO prssVO = (PrssReportsVO) list.get(i);
                            	if(!prssVO.getId().equals(rid))continue;
                                TotReportProcess process = (TotReportProcess) prssVO.getProcess();

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

                                int kkkk = prssVO.getProcess().ordinal();
                                String html = null;
                                if ((process == TotReportProcess.COMP || process == TotReportProcess.TEMP || process == TotReportProcess.APPROVE) && prssVO.getDownDocId() == null) {
                                    //html = prssVO.getToHTML(pm, tableNum, tableNum > 0, true); //표를 만들어 찍어주는 부분
                                    TotReport report = pm.getObjectById(TotReport.class, prssVO.getId());
                                    html = TotReportUtil.toHTML(report, tableNum, tableNum > 0, true); //표를 만들어 찍어주는 부분
                                }

                    %>
                    <tr>
                        <td style="padding-left: <%= slavePaddingLeft%>">
                            <table border="0" width="100%" cellpadding="0" cellspacing="0">
                                <tr>
                                    <td style="width: 14"><input type=checkbox name='check' id="check<%=index%>" value="<%=index%>">
		                                <input type="hidden" name="checkPrss<%=index%>" id="checkPrss<%=index%>" value="<%=prssVO.getProcess().ordinal()%>">
		                                <input type='hidden' name='checkReportID<%=index%>' value='<%=prssVO.getId()%>'>
                                    </td>
                                <td class="kecttep_title" style="padding-left: 5" align="left" width="100%">
                                    <%= prssVO.getUpperDeptName() == null ? "" : prssVO.getOrganName() + " - " + prssVO.getUpperDeptName() + " - "%>
                                    <%= prssVO.getDeptName()%>&nbsp;&nbsp;
                                    <%= MString.checkNull(prssVO.getOwnerName())%>
                                    <!-- 제출날짜추가 2015.04.29 진승환-->
                                    &nbsp;<%= prssVO.getSubmitDate() == null ? "" : new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(prssVO.getSubmitDate())%>
                                    <% if (prssVO.getDownDocId() != null) {
                                            out.write("   [" + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.subdoc") + "]");
                                        }%>
                                    [<%=process%>]
                                </td>
                                <td></td>
                    </tr>
                </table>
        </td>
    </tr>
    <tr>
        <!--<td align="left">-->
        <!--// 2014.10.16 by youngjun cho. jquery 로 테이블표의 레이아웃을 정리하기 위한 class명("fixTarget") 추가 -->
<td align="left" style="padding-left: <%= slavePaddingLeft%>" class="fixTarget"><!--//도표 나오는 부분//-->

            <%if(prssSelect){%>
            <%= ((process == TotReportProcess.COMP || process == TotReportProcess.TEMP || process == TotReportProcess.APPROVE) && prssVO.getDownDocId() == null) ? (html == null ? "" : html) : ""%>
            <%}else{%>
            <%= ((process == TotReportProcess.COMP) && prssVO.getDownDocId() == null) ? (html == null ? process : html) : process%>
            <%}%>
            <input type='hidden' id='kkkk<%=index%>' value='<%= kkkk%>'>
        </td>
    </tr>
    <tr>
        <td style="padding-left: <%= slavePaddingLeft%>">
            <table border="0" width="100%" cellpadding="0" cellspacing="0">

                <% if ("Y".equals(prssVO.getIsAttachments()) || (null != prssVO.getAttachmentsPath() && !"".equals(prssVO.getAttachmentsPath()))) { %>
                <!-- 2014.10.08 Add by KWON,HAN : 제출완료 -> 제출완료, 회수요청 -->
                <%if (process == TotReportProcess.COMP || process == TotReportProcess.NOTE) {%>
                <tr><!-- 첨부파일 -->
                    <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")%>
                        <a href="javascript:void(0);" onclick="popupViewInner('<%=index%>', 'file<%=index%>', '<%=prssVO.getId()%>');" title="첨부파일을 확인하시려면 클릭해주세요."><img src="/totsys/totper/mydocbox/prssbox/reports/images/disk2.gif"></a>
                    </td>
                </tr>
                <div class="ajdxjdrnfl" id="file<%=index%>" style="display: none; position: absolute; z-index: 2;">
                    <tr><td height="10"></td></tr>
                    <tr>
                        <td style="padding-left: 10" align="left">
                            <div id="fileNameList<%=index%>"></div>
                        </td>
                    </tr>
                </div>
                <%} else {%> &nbsp; <%}%>
                <%}%>
            </table>
        </td>
    </tr>
    <%
                //20160419  추가
                if(i == 0){
                    reportIds = String.valueOf( prssVO.getId() );
                }else{
                    reportIds = reportIds + "|" + String.valueOf( prssVO.getId() );
                }
break;
            }  //end of for list
        }   //end of if( count > 0)


    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
    }
%>
