<%@page import="kr.co.kihyun.beans.tosys.etc1.TotsysEtc"%>
<%    /**
     * **********************************************************@@ Program Name
     * : popup_inform_preview.jsp Description	: 집계문서 미리보기(등록과, 변경에서 같이 사용 Author
     * : 기현테크 Create Date	: 2010.11.25 History	:
     * @@***********************************************************
     */
%>
<%@ page contentType="text/html; charset=UTF-8"
         import="java.net.URLEncoder"
         import="java.net.URLDecoder"
         import="javax.jdo.PersistenceManager"
         import="kr.co.kihyun.beans.entity.util.*"
         import="kr.co.kihyun.beans.entity.TotDoc"
         import="kr.co.kihyun.lang.MString"
         import="kr.co.kihyun.lang.MLong"
         import="kr.co.kihyun.lang.Encoder"
         import="kr.co.kihyun.lang.MInteger"
         import="kr.co.kihyun.text.html.TagFilter"
         import="kr.co.kihyun.beans.entity.*"
         import="kr.co.kihyun.moumi.doc.MDocPreview"
         import="kr.co.kihyun.moumi.doc.table.item.MItem"
         import="kr.co.kihyun.beans.totsys.doc.table.item.ItemList"
         import="kr.co.kihyun.moumi.Moumi"
         import="javax.jdo.Transaction"
         import="java.util.*"%>
<%@ include file="/totsys/common/inc/sec/secure.inc.jsp"%>
<%
    PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
    Transaction tx = pm.currentTransaction();
    try {
        /**
         * ********* parameter value **********
         */
        Long docID = MLong.parseLong(request.getParameter("docID"), null);
        String docName = clearXSS(URLDecoder.decode(MString.checkNull(request.getParameter("docName")), "UTF-8"), "");
        String acceptanceLimitStrategy = clearXSS(request.getParameter("acceptanceLimitStrategy"), LimitByDeadlineStrategy.class.getSimpleName().toString());
        String usrFilenames = clearXSS(URLDecoder.decode(MString.checkNull(request.getParameter("usrFilenames")), "UTF-8"), "");
        String svrFilenames = clearXSS(URLDecoder.decode(MString.checkNull(request.getParameter("svrFilenames")), "UTF-8"), "");
        String itemNames = Encoder.toJava(clearXSS(MString.checkNull(request.getParameter("itemNames")), ""));
        String itemSizes = Encoder.toJava(clearXSS(MString.checkNull(request.getParameter("itemSizes")), ""));
        String itemDescs = Encoder.toJava(clearXSS(MString.checkNull(request.getParameter("itemDescs")), ""));

        String itemExprs = Encoder.toJava(clearXSS(MString.checkNull(request.getParameter("itemExprs")), ""));
        String itemTypes = Encoder.toJava(clearXSS(MString.checkNull(request.getParameter("itemTypes")), ""));
        int defItemSize = MInteger.parseInt(MString.checkNull(request.getParameter("defItemSize")));
        String mode = clearXSS(MString.checkNull(request.getParameter("mode")), "");
        String callType = MString.checkNull(request.getParameter("callType"));

        if (defItemSize < 1) {
            defItemSize = 10;
        }

        /**
         * ********** doc values ***********
         */
        TotDoc totDoc = docID == null ? null : pm.getObjectById(TotDoc.class, docID);
        String docForm = "";

        /**
         * *********** item values **********
         */
        StringBuffer itemNamesBuf = new StringBuffer();
        StringBuffer itemSizesBuf = new StringBuffer();
        StringBuffer itemDescsBuf = new StringBuffer();
        StringBuffer itemExprsBuf = new StringBuffer();
        StringBuffer itemTypesBuf = new StringBuffer();
        StringBuilder insertInputCellName = new StringBuilder();

        if (mode != null && mode.equals("regist")) {
            docForm = (String) session.getAttribute("docForm");
			System.out.print("test");
        } else if (mode != null && mode.equals("modify")) {
            docForm = totDoc.getForm();
        } else if (mode != null && mode.equals("preview")) {
            docForm = totDoc.getForm();
            docName = totDoc.getName();
            if (totDoc.getTotTables().iterator().hasNext()) {
                defItemSize = totDoc.getTotTables().iterator().next().getItemSize();
            }

            /**
             * ******** Item values *********
             */
            ItemList itemList = new ItemList();
            //v2. 13.SQL 삽입 : itemList.executeQuery()에서 prepare SQL 문으로 되어 있다.
            itemList.executeQuery(docID);
            //=================
            int itemCount = itemList.getCount();
            String[] itemNameList = itemList.getNameList();
            String[] itemDescList = itemList.getDescList();
            String[] itemExprList = itemList.getExprList();
            int[] itemTypeList = itemList.getTypeList();
            int[] itemNumList = itemList.getNumList();
            int[] itemSizeList = itemList.getSizeList();
            int[] tableNumList = itemList.getTableNumList();
            int[] colNumList = itemList.getFieldNumList();
            int[] rowNumList = itemList.getRecordNumList();
            int[] itemBNWList = itemList.getBNWList();
            String[] itemTypeNameList = itemList.getTypeNameList();
            //dform.itemNames.value = dform.itemNames.value + i + ':' + itemNameList[i] + 'MItem.LIST_DELIM';

            for (int i = 0; i < itemCount; i++) {
                if (insertInputCellName.toString().length() == 0) {
                    if ("empty".equals(itemDescList[i].trim())) {
                        insertInputCellName.append(itemNameList[i]);
                    }
                } else {
                    if ("empty".equals(itemDescList[i].trim())) {
                        insertInputCellName.append("," + itemNameList[i]);
                    }
                }
                itemNamesBuf.append(i + ":" + itemNameList[i] + MItem.LIST_DELIM);
                itemSizesBuf.append(i + ":" + itemSizeList[i] + MItem.LIST_DELIM);
                itemDescsBuf.append(i + ":" + itemDescList[i] + MItem.LIST_DELIM);
                itemExprsBuf.append(i + ":" + itemExprList[i] + MItem.LIST_DELIM);
                itemTypesBuf.append(i + ":" + MItem.getTypeName(itemTypeList[i]) + MItem.LIST_DELIM);
            }

            itemNames = itemNamesBuf.toString();
            itemSizes = itemSizesBuf.toString();

            itemDescs = itemDescsBuf.toString();

            itemExprs = itemExprsBuf.toString();
            itemTypes = itemTypesBuf.toString();
        }

        /**
         * ********* preview로 docForm 변환 **********
         */
        String putValScript = "";
        String changeAllScript = "";
        String docBodyForm = "";
        String docTitleForm = "";
        String inputForm = "";

        MDocPreview docPreView = new MDocPreview();

        docPreView.convert(docForm, itemNames, itemSizes, itemExprs, itemTypes, itemDescs, defItemSize);

        docForm = docPreView.getInputForm();
        putValScript = docPreView.getPutValScript();

        changeAllScript = docPreView.getChangeAllScript();
        changeAllScript = changeAllScript.replaceAll("[$]", ".");

        inputForm = docPreView.getInputForm();
        /*
         if(mode != null && !mode.equals("preview")){
         StringTokenizer stkNames = new StringTokenizer(itemNames,(MItem.LIST_DELIM));
         StringTokenizer stkDesc = new StringTokenizer(itemDescs,(MItem.LIST_DELIM));

         int itemCount = stkNames.countTokens();
         String strTmp;
         String[] itemNameListScript = new String[itemCount];
         String[] itemDescListScript = new String[itemCount];

         for (int i=0; i < itemCount; i++) {
         strTmp = stkNames.nextToken();
         itemNameListScript[i] = strTmp.substring(strTmp.indexOf(":")+1, strTmp.length()).trim();

         strTmp = stkDesc.nextToken();
         itemDescListScript[i] = strTmp.substring(strTmp.indexOf(":")+1, strTmp.length()).trim();

         if("empty".equals(itemDescListScript[i].trim())){
         if(insertInputCellName.toString().length() == 0)
         insertInputCellName.append(itemNameListScript[i]);
         else
         insertInputCellName.append(","+itemNameListScript[i]);
         }
         }
         }
         */
        if (mode != null && !mode.equals("preview")) {
            String[] stkNames = TotsysEtc.getDeliToArr(itemNames, "!@!");
            String[] stkDesc = TotsysEtc.getDeliToArr(itemDescs, "!@!");
            int itemCount = stkNames.length;
            String strTmp;
            String[] itemNameListScript = new String[itemCount];
            String[] itemDescListScript = new String[itemCount];
            for (int i = 0; i < itemCount; i++) {
                strTmp = stkNames[i];
                itemNameListScript[i] = strTmp.substring(strTmp.indexOf(":") + 1, strTmp.length()).trim();
                strTmp = stkDesc[i];
                itemDescListScript[i] = strTmp.substring(strTmp.indexOf(":") + 1, strTmp.length()).trim();
                if ("empty".equals(itemDescListScript[i].trim())) {
                    if (insertInputCellName.toString().length() == 0) {
                        insertInputCellName.append(itemNameListScript[i]);
                    } else {
                        insertInputCellName.append("," + itemNameListScript[i]);
                    }
                }
            }
        }
%>
<html lang="ko">
	<head>
		<meta charset="UTF-8">
		<title>양식테스트</title>
        <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/popup.css" type="text/css">
        <link rel="stylesheet" href="/totsys/common/css/basic.css" type="text/css">
        <script src="/totsys/common/js/rollover.js"></script>
        <script src="/totsys/common/js/checkNum.js"></script>
        <script src="/totsys/common/js/util.js"></script>
        <script src="/totsys/common/js/calendar.js"></script>
        <script src="/totsys/common/js/drag.js"></script>
        <script src="/totsys/common/js/jquery-1.12.4.min.js"></script>
        <script src="/totsys/common/js/jquery.fixFormTable.js"></script>
        <script>
            function formTypeCheck() {
                if (opener.dform.tableCount.value > 1 && opener.dform.tableType[1].checked == true) {
                    if (confirm('<%=Moumi.getMessageBundle().getString("moumi.message.popup.formTypeTableSet")%>')) {
                        opener.dform.tableType[0].focus();
                        return false;
                    }
                } else if (opener.dform.isDynaTable == false && opener.dform.tableType[1].checked == true) {
                    if (confirm("<%=Moumi.getMessageBundle().getString("moumi.message.popup.formTypeSet")%>")) {
                        opener.dform.tableType[0].focus();
                        return false;
                    }
                }

                return true;
            }

            function nextblur(type) {
                var items = "<%=insertInputCellName.toString()%>";
                var count = 0;
                splitItems = items.split(",");

                for (i = 0; i < splitItems.length; i++) {
                    if (splitItems[i] == type)
                        break;
                    count++;
                }
                if (splitItems.length <= count + 1)
                    dform[type].blur();
                else
                    dform[splitItems[count + 1]].focus();
            }

            <%if ("regbox1step".equals(callType)) {%>
            function reuseForm(){
				if(opener.doLink){
					opener.confirm = this.confirm;
					opener.doLink('<%= docID %>', '<%= totDoc.getName() %>', '<%= totDoc.getTotTables().iterator().next().getType() %>');
				}else{
					var dolink;
					for(var i=0;i<parent.frames.length;i++){
						if(parent.frames[i].doLink){
							parent.frames[i].doLink('<%= docID %>', '<%= totDoc.getName() %>', '<%= totDoc.getTotTables().iterator().next().getType() %>');
						}
					}
				}
				self.close();
			}
            <%}%>

            function saveform() {
                if (!formTypeCheck())
                    return;
                opener.dform.action = '/servlet/kr.co.kihyun.beans.totsys.doc.HttpDocRegister';
                opener.dform.target = '_self';
                opener.dform.submit();
                window.close();
            }

            function modifyform() {
                if (!formTypeCheck())
                    return;
                opener.dform.action = '/servlet/kr.co.kihyun.beans.totsys.doc.HttpDocFormModifyer';
                opener.dform.target = '_self';
                opener.dform.submit();
                window.close();
            }

            <%= putValScript%>

            <%
            if (changeAllScript.length() > 0) {
            %>
            function changeAll() {
                <%= changeAllScript%>
            }
            <%
            }
            %>

            /*
             * 자료입력 테이블 input element 뒤에 font, span 등의 불필요한 element 를 삭제처리. 시작
             * 2014.09.12 by YoungJun Cho.
             */
            $(document).ready(function() {
                $.fixRegistFormTable( $("#formDiv").find("table"), {});
                //ie10,11 호환성 수정 - 수식 배경색
                $('[type=text]').each(function(){
                	var bc=$(this).attr('iseval');
                	if(bc=='true'){
                		$(this).css({'background-color':'#cbddfb'});
                	}
                });
                $('#SetWin').next().width($('#formDiv table:first').width()+80);
              //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');
						}
	          		});
                $('#formDiv span').css('line-height','2');

            });
            /* 자료입력 테이블 input element 뒤에 font, span 등의 불필요한 element 를 삭제처리. 끝 */
        </script>
    </head>
    <body style='' onload="scrollObjectContent('formDiv');">
    <div id="SetWin" style="position: absolute; Visibility: hidden; width: 100px; height: 100px; background: silver; border: 1px #333333 solid; line-height: 1.4em; padding: 3px 3px"></div>
        <table>
            <tr>
                <td style="height: 19px; width: 29px;background-image:url('/totsys/common/web/documents/tot_doc/images/popupt_top_left.gif');"></td>
                <td style="height: 19px; background-image:url('/totsys/common/web/documents/tot_doc/images/popupt_top_center.gif');">&nbsp;</td>
                <td style="height: 19px; width: 30px; background-image:url('/totsys/common/web/documents/tot_doc/images/popupt_top_right.gif');"></td>
            </tr>
            <tr>
                <td style="background-image:url('/totsys/common/web/documents/tot_doc/images/popupt_center_left.gif')">&nbsp;</td>
                <td>
                    <table>
                        <tr>
                            <td class="pl_10">
                                <table>

                                    <!-- 뉴타이틀 -->
                                    <jsp:include page="/totsys/common/inc/title/title.jsp" flush="true" />
                                    <!-- 뉴타이틀 -->

                                    <tr>
                                        <td>
                                            <form name='dform' method='post'>
	                                            <table>
	                                                    <!-- 표시작 -->
	                                                    <tr>
	                                                        <td>
	                                                            <div id="formDiv" style="padding-top: 20px;<%=session.getAttribute("formWidth") == null ? "":"width: "+session.getAttribute("formWidth")%>; ">
	                                                                <!-- config Content start -->
	                                                                <%= docForm%>
	                                                                <!-- config Content end -->
	                                                            </div>
	                                                        </td>
	                                                    </tr>
	                                                    <!-- 표 끝 -->
	                                                    <!-- (버튼) 계산, 종료, 재사용-->
	                                                    <tr>
	                                                        <td></td>
	                                                    </tr>
	                                                    <tr>
	                                                        <td class="center">
	                                                        <%if (changeAllScript.length() > 0) {%>
	                                                            <a href=# onClick='changeAll();changeAll();changeAll();changeAll();'>
	                                                                <img alt="board" src="/totsys/common/images/bt_cal.gif">
	                                                            </a>
	                                                        <%}%>
	                                                            <a href="#" onclick='window.close();'><img alt="board" src="/totsys/common/images/bt_end.gif"></a>
	                                                            <a href="/totsys/common/inc/documents/tot_doc/tot_doc_excel.jsp?docID=<%=docID%>&docName=<%=URLEncoder.encode(docName)%>&mode=<%=mode%>">
	                                                                <img alt="board" src="/totsys/common/images/bt_big_excel_save.gif">
	                                                            </a>
	                                                        <%if ("regbox1step".equals(callType)) {%>
	                                                            <a href="#" onclick="reuseForm();"><img alt="board" src="/totsys/common/images/bt_reuse_form.gif"></a>
	                                                        <%}%>
	                                                        </td>
	                                                    </tr>
	
	                                                    <tr>
	                                                        <td></td>
	                                                    </tr>
	                                            </table>
                                            </form>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                    </table>
                </td>
                <td style="background-image:url('/totsys/common/web/documents/tot_doc/images/popupt_center_right.gif');">&nbsp;</td>
            </tr>
            <tr>
                <td style="height: 24px; background-image:url('/totsys/common/web/documents/tot_doc/images/popupt_bottom_left.gif');"></td>
                <td style="height: 24px; background-image:url('/totsys/common/web/documents/tot_doc/images/popupt_bottom_center.gif');">&nbsp;</td>
                <td style="background-image:url('/totsys/common/web/documents/tot_doc/images/popupt_bottom_right.gif');"></td>
            </tr>
        </table>
    </body>
</html>
<%
} catch (Exception ex) {

    ex.printStackTrace();
%>
<script>
    <!--
    alert('<%=Moumi.getMessageBundle().getString("moumi.message.popup.falseTable")%>');
    window.close();
    //-->
</script>
<%
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();

    }
%>
