<%@ page language="java" contentType="text/html; charset=utf-8" %>
<%@ page import="java.io.*" %>
<%@ page import="com.eactive.eai.rms.common.login.SessionManager" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ include file="/jsp/common/include/localemessage.jsp" %>
<%
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Expires", "0");
%>
<!DOCTYPE html>
<html lang="en">
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <jsp:include page="/jsp/common/include/css.jsp"/>
    <jsp:include page="/jsp/common/include/script.jsp"/>
    <jsp:include page="/jsp/common/include/layoutScript.jsp"/>

    <script language="javascript">
        var isPop = "${param.pop}";
        var isLayoutView = "${param.isLayoutView}";
        var isDetail = false;
        var url = '<c:url value="/onl/admin/rule/layoutMan.json" />';
        var url_view = '<c:url value="/onl/admin/rule/layoutMan.view" />';
        var url_excel = '<c:url value="/onl/admin/rule/layoutMan.excel"/>';
        var roleString = "<%=SessionManager.getRoleIdString(request)%>";
        var returnUrl = getReturnUrlForReturn();
        var sevrArr = new Array();
        const columnNames = [];

        const iso8583DataTypes = [{id:'NUMERIC',name:'[ISO8583] NUMERIC'}, {id:'ALPHA',name:'[ISO8583] ALPHA'}, {id:'DATE10',name:'[ISO8583] DATE10'}, {id:'DATE4',name:'[ISO8583] DATE4'}
            , {id:'DATE_EXP',name:'[ISO8583] DATE_EXP'}, {id:'TIME',name:'[ISO8583] TIME'}, {id:'AMOUNT',name:'[ISO8583] AMOUNT'}, {id:'LLVAR',name:'[ISO8583] LLVAR'}
            , {id:'LLLVAR',name:'[ISO8583] LLLVAR'}, {id:'LLLLVAR',name:'[ISO8583] LLLLVAR'}, {id:'BINARY',name:'[ISO8583] BINARY'}, {id:'LLBIN',name:'[ISO8583] LLBIN'}
            , {id:'LLLBIN',name:'[ISO8583] LLLBIN'}];

        const basicDataTypes = [{id:'BigDecimal',name:'BigDecimal'},{id:'String',name:'String'},{id:'Boolean',name:'Boolean'}];

        function gridRenderingInit() {
            $('#effectGrid').jqGrid({
                datatype : "json",
                mtype : 'POST',
                colNames : [ '<%=localeMessage.getString("layoutMan.layoutMapCd")%>',
                    '<%=localeMessage.getString("layoutMan.chgMapCdSvrDvCd")%>',
                    '<%=localeMessage.getString("layoutMan.ifSvcCd")%>',
                    '<%=localeMessage.getString("layoutMan.ifSvcCdSvrDvCd")%>',
                    '<%=localeMessage.getString("layoutMan.ifSvcDesc")%>',
                    'SRC/TGT'
                ],
                colModel : [ { name : 'CNVSNNAME'       , align : 'center' , width:'100'},
                    { name : 'TRANSEVRDSTCD'      , align : 'center' , width:'50'},
                    { name : 'EAISVCNAME'      , align : 'center' , width:'100'},
                    { name : 'EAISVCSEVRDSTCD'       , align : 'center' , width:'50'},
                    { name : 'EAISVCDESC'      , align : 'left'   },
                    { name : 'SOURCRSULTDSTCD' , align : 'left'   , width:'80'}
                ],
                jsonReader : {
                    root : "rows2",
                    repeatitems : false
                },
                rowNum : 10000,
                autoheight : true,
                height : "80",
                autowidth : true,
                viewrecords : true,
                ondblClickRow : function(rowId) {
                }
            });

            resizeJqGridWidth('effectGrid','content_middle','1000');

            $('#grid').children().remove();

            const itemTypes = ['Field', 'Grid', 'Group', 'Attr', 'Array'];

            columns = [ // for columnData prop
                { title: '<%= localeMessage.getString("layoutMan.itemDesc") %>', name: 'loutItemDesc', type: 'text', width:280, resize:true, minWidth:120 },
                { title: '<%= localeMessage.getString("layoutMan.itmeEn") %>', name: 'loutItemName', type: 'text', width:280, resize:true, minWidth:120 },
                { title: '<%=localeMessage.getString("standardLayout.itemLevel")%>', name: 'loutItemDepth', type: 'text', width:50 },
                { title: '<%= localeMessage.getString("standardLayout.itemType") %>', name: 'loutItemType', type: 'autocomplete', source: itemTypes, width:70 },
                { title: '<%= localeMessage.getString("standardLayout.arraySize") %>', name: 'loutItemOccCnt', type: 'text', width:90 },
                { title: '<%= localeMessage.getString("standardLayout.refField") %>', name: 'loutItemOccRef', type: 'text', width:90 },
                { title: '<%=localeMessage.getString("layoutMan.dataType")%>', name: 'loutItemDataType', type: 'autocomplete', source: basicDataTypes, width:160 },
                { title: '<%=localeMessage.getString("layoutMan.dataLen")%>', name: 'loutItemLength', type: 'numeric', width: 70, align: 'center' },
                { title: '<%=localeMessage.getString("layoutMan.decpLen")%>', name: 'loutItemDecimal', type: 'text', width: 70 },
                { title: '<%=localeMessage.getString("layoutMan.defaultVal")%>', name: 'loutItemDefault', type: 'text', width: 70 },
                { title: '<%=localeMessage.getString("layoutMan.mask")%>', name: 'loutItemMaskYn', type: 'checkbox', width: 70 },
                { title: '<%=localeMessage.getString("layoutMan.moffset")%>', name: 'loutItemMaskOffset', type: 'text', width: 50 },
                { title: '<%=localeMessage.getString("layoutMan.mLength")%>', name: 'loutItemMaskLength', type: 'text', width: 50 }
            ];

            for (let i = 0; i < columns.length; i++) {
                columnNames[i] = columns[i].name;
            }

            grid = JexcelEactiveCustom(document.getElementById('grid'), {
                data: [[]],
                columns: columns,
                rowResize: false,
                rowDrag: true,
                columnResize: true,
                columnDrag: false,
                columnSorting: false,
                defaultColAlign : 'center',
                autoIncrement: false,
                loadingSpin : true,
                allowInsertColumn: false,
                allowInsertOnTab: true,
                allowDeleteColumn : false,
                allowRenameColumn : false,
                tableOverflow:false,
                tableHeight: 2500,
                contextMenu: jexelContextMenu,
                updateTable: jexcelUpdateTableByOutCommHdr,
                onload : jexcelOnload,
                // onbeforechange : jexcelOnBeforeChange,
                onbeforepaste: jexcelOnBeforePaste,
                oneditionend : jexcelOnEditionEnd,
            });

            grid.eaAutoResize('content_middle');


            <%--+ '<img id="btn_item_delete" onClick="itemDel()" style="margin-right:5px; vertical-align:middle;" src="<c:url value="/images/bt/bt_item_delete.gif"/>"  />'--%>
            <%--+ '<img id="btn_meta" onClick="getAllMetaData()" style="margin-right:5px; vertical-align:middle;" src="<c:url value="/images/bt/bt_meta.gif"/>"  />'			--%>
            toolbarHtml='<button type="button" class="cssbtn smallBtn" id="btn_item_add" onClick="itemAdd()" style="margin-right:5px; vertical-align:middle; font-weight:bold;"><i class="material-icons">add</i><%= localeMessage.getString("common.itemAdd") %></button>'
                +'<button type="button" class="cssbtn smallBtn" id="btn_item_delete" onClick="itemDel()" style="margin-right:5px; vertical-align:middle; font-weight:bold;"><i class="material-icons">delete</i><%= localeMessage.getString("common.itemRemove") %></button>'
                +'<br/>';


            $('#grid').children().first().before(toolbarHtml);
        }

        function jexcelUpdateTableByOutCommHdr(instance, cell, col, row, val, label, cellName) {
            if (grid == undefined) {
                return;
            }
            var outCommHdrId = grid.getEaCellValue(row, 'OUTCOMMHDRID');

            if ($.trim(outCommHdrId) != '') {
                cell.classList.add('readonly');
                cell.classList.add('ui-state-focus');
            }

            jexcelUpdateTable(instance, cell, col, row, val, label, cellName);
        }

        function migCellValue(columnName, dataKey, dataArray, targetArray){
            const index = columnNames.indexOf(columnName);
            var value = dataArray[dataKey];

            if(columnName === 'loutItemMaskYn'){
                value = value == 'Y' ? 'true' : 'false';
            }

            targetArray[index] = value;
        }

        function setDataToGrid(layoutData){
            if(layoutData != null && layoutData.rows && layoutData.rows.length > 1){
                const gridData = [];
                for (let i = 1; i < layoutData.rows.length; i++) {
                    const row = layoutData.rows[i];
                    const values = [];
                    columnNames.forEach(columnName => {
                        migCellValue(columnName, columnName, row, values);
                    })

                    gridData[i - 1] = values;
                }
                grid.setData(gridData);
            }
        }

        function setDataTotalLen(){
            const itemLenIndex = columnNames.indexOf('loutItemLength');
            const dataLengthArray = grid.getColumnData(itemLenIndex);
            var totalLen = 0;
            dataLengthArray.forEach(function(dataLength){
                totalLen += Number.parseInt(dataLength);
            });
            $('#dataTotalLen').text(totalLen);
        }

        function detail(key) {
            if (!isDetail) {
                return
            };
            $.ajax({
                type: "POST",
                url: url,
                dataType: "json",
                data: {cmd: 'DETAIL', loutName: key},
                success: function (json) {
                    console.log(json);

                    var data = json.detail;
                    $("input[name=loutName]").attr('readonly',true);

                    $("#ajaxForm input[type!=radio],#ajaxForm select,#ajaxForm textarea").each(function(){
                        var name = $(this).attr("name");
                        var tag  = $(this).prop("tagName").toLowerCase();
                        var key = name.toUpperCase();
                        $(tag+"[name="+name+"]").val(data[key]);
                    });
                    var rows2 = json.rows2;
                    for(var i=0; i<rows2.length; i++){
                        var tranSevrCd = rows2[i]['TRANSEVRDSTCD'];
                        var eaiSvcSevrCd = rows2[i]['EAISVCSEVRDSTCD'];
                        for(var j=0; j<sevrArr.length; j++){
                            var sevrCd = sevrArr[j]['CODE'];
                            if(tranSevrCd==sevrCd){
                                rows2[i]['TRANSEVRDSTCD']='['+sevrCd+'] '+sevrArr[j]['NAME'];
                            }
                            if(eaiSvcSevrCd==sevrCd){
                                rows2[i]['EAISVCSEVRDSTCD']='['+sevrCd+'] '+sevrArr[j]['NAME'];
                            }
                        }
                    }
                    $("#effectGrid")[0].addJSONData(json);

                    setDataToGrid(json);
                    setDataTotalLen();
                    $("select[name=loutPtrnName]").change();
                },
                error: function (e) {
                    alert(e.responseText);
                }
            });
        }
        async function detailCombo(){
            try {
                let json = await $.ajax({
                    type: "POST",
                    url: url,
                    dataType: "json",
                    data: {cmd: 'LIST_DETAIL_COMBO'}
                });

                new makeOptions("CODE", "NAME").setObj($("select[name=eaiBzwkDstcd]")).setData(json.bizList).setFormat(codeName3OptionFormat).rendering();
                new makeOptions("CODE", "NAME").setObj($("select[name=loutPtrnName]")).setData(json.typeList).setFormat(codeName3OptionFormat).rendering();
                new makeOptions("CODE", "NAME").setObj($("select[name=useYn]")).setData(json.useYnRows).setFormat(codeName3OptionFormat).rendering();
                new makeOptions("CODE", "NAME").setObj($("select[name=eaiSevrDstcd]")).setData(json.eaiSevrCdRows).setFormat(codeName3OptionFormat).rendering();
                sevrArr = json.eaiSevrCdRows;
            } catch (e) {
                alert(e.responseText);
            }
        }
        async function init(key) {
            if(isPop){
                $(".content_top").css('display', 'none');
                $(".content_middle").css('margin-top', '0px');
                $("#btn_previous").html('<i class="material-icons">close</i> 닫기');
                $('#effectGridRow').hide()
                $('#dataTotalLenRow').hide()
                $('#titleRow').hide()
            }

            await detailCombo();

            gridRenderingInit();

            detail(key);

            initDialog();

            buttonControl(isDetail);
        }

        $(document).ready(function () {

            $("#btn_delete").click(function(){
                if(confirm("<%= localeMessage.getString("common.confirmMsg")%>")){
                    var postData = $('#ajaxForm').serializeArray();
                    postData.push({ name: "cmd" , value:"DELETE"});
                    $.ajax({
                        type : "POST",
                        url:url,
                        data:postData,
                        success:function(args){
                            alert("<%=localeMessage.getString("common.deleteMsg")%>");
                            if(isPop == "true"){
                                window.close();
                                const layout ="${param.loutName}";
                                const layoutPartName ="${param.layoutPartName}";
                                window.parent.postMessage({cmd:'DELETE', type: 'layout', layout, layoutPartName});
                            }else{
                                goNav(returnUrl);
                            }
                        },
                        error:function(e){
                            alert(e.responseText);
                        }
                    });
                }else{
                    return false;
                }
            });

            $("#btn_previous").click(function(){
                if(isPop == "true") {
                    window.close();
                } else {
                    goNav(returnUrl);//LIST로 이동
                }
            });

            $("#btn_initialize").click(function(){
                $.ajax({
                    type : "POST",
                    url:url,
                    dataType:"json",
                    data:{cmd: 'INITIALIZE',loutName:$("input[name=loutName]").val()},
                    success:function(json){
                        alert(json.message);
                    },
                    error:function(e){
                        alert(e.responseText);
                    }
                });
            });

            $("#btn_modify").click(function(){
                var postData = $('#ajaxForm').serializeArray();
                if (isDetail){
                    postData.push({ name: "cmd" , value:"UPDATE"});
                }else{
                    postData.push({ name: "cmd" , value:"INSERT"});
                }

                postData.forEach((element) => {
                    if(element.name === 'useYn'){
                        if (element.value  === null || element.value .trim() === "") {
                            element.value  = "1";
                        }
                    }
                } );

                var gridData = new Array();
                if (grid) {
                    var data = grid.getData();
                    for ( var i = 0; i < data.length; i++) {
                        const row = data[i];
                        const inputRow = {checkMetadata: 'Y',
                            loutItemDefault: '',
                            loutItemMaskYn: 'false',
                            loutItemOccCnt: '0',
                            loutItemOccRef: ''};

                        for (let j = 0; j < row.length; j++) {
                            const columnName = columnNames[j];
                            const value = String(row[j]);
                            inputRow[columnName] = value;
                        }
                        const depth = Number(inputRow['loutItemDepth']);
                        if(depth == 0){
                            inputRow['loutItemDepth'] = 1;
                        }

                        inputRow['loutItemMaskYn'] = inputRow['loutItemMaskYn'] === 'true' ? 'Y' : 'N';

                        const index = String(i+1);
                        inputRow['loutItemSerno'] = index;

                        gridData.push(inputRow);
                    }
                }

                postData.push({
                    name : "layoutItems",
                    value : JSON.stringify(gridData)
                });

                $.ajax({
                    type : "POST",
                    url:url,
                    data:postData,
                    success:function(args){
                        if(isPop == "true"){
                            if(isLayoutView == "true"){
                            	alert("<%=localeMessage.getString("common.saveMsg")%>");
                            } else {
                                alert("<%=localeMessage.getString("common.saveMsg")%> \n저장 후 변환정보 수정이 필수입니다. 변환정보를 확인하세요");
                            }
                            const origin = window.location.origin;
	
                            const layoutName = $("input[name='loutName']").val();

							parent.postMessage({
								action: 'LAYOUT_SAVED_OPEN_TRANSFORM',
					            layoutPartName: '${param.layoutPartName}',
					            isLayoutView: isLayoutView
							}, origin);

                            window.close();
                        } else {
                        	alert("<%=localeMessage.getString("common.saveMsg")%>");
                            goNav(returnUrl);
                        }
                    },
                    error:function(e){
                        alert(e.responseText);
                    }
                });
            });

            $("select[name=loutPtrnName]").change(function(){
                const index = columnNames.indexOf('loutItemDataType');
                if($(this).val() == 'ISO8583'){
                    grid.options.columns[index].source = iso8583DataTypes;
                }else{
                    grid.options.columns[index].source = basicDataTypes;
                }
                grid.updateTable();
            });

            var key = "${param.loutName}";
            if (key != "" && key != "null") {
                isDetail = true;
            }
            init(key);
        });
        function closeAddRowDialog(){
            $( '#add_row_dialog' ).dialog("close");
        }

        function addNewRow(){
            var cnt = $("input[name=add_row_count]").val();
            if(cnt == "" || cnt == undefined) return;
            const ncnt = Number(cnt);

            if (grid.getJson().length == 0){
                const ncnt = Number(cnt) -1;
                grid.setData([{}]);
                if (ncnt !=0){
                    grid.insertRow(ncnt);
                }
            }else{
                const ncnt = Number(cnt);
                grid.insertRow(ncnt);
            }

            $( '#add_row_dialog' ).dialog("close");
            closeAddRowDialog();
        }

        function initDialog(){
            $( '#add_row_dialog' ).dialog({
                resizable: false,
                autoOpen: false,
                height: "auto",
                width: 400,
                modal: true,
                buttons: {
                    "Add": function() {
                        addNewRow();
                    },
                    Cancel: function() {
                        closeAddRowDialog();
                    }
                }
            });

            $("input[name=add_row_count]").keydown(function(key){
                if (key.keyCode == 13){
                    addNewRow();
                }
            });
        }

        function itemAdd(){
            grid.resetSelection();
            $("input[name=add_row_count]").val("");
            $( '#add_row_dialog' ).dialog("open");
        }

    </script>
</head>
<body>
<div class="right_box">
    <div class="content_top">
        <ul class="path">
            <li><a href="#">${rmsMenuPath}</a></li>
        </ul>
    </div><!-- end content_top -->
    <div class="content_middle" id="content_middle">
        <div class="search_wrap">
            <button type="button" class="cssbtn" id="btn_initialize" level="R" status="DETAIL"><i class="material-icons">restart_alt</i> <%= localeMessage.getString("button.reset") %></button>
            <button type="button" class="cssbtn" id="btn_delete" level="W" status="DETAIL"><i class="material-icons">delete</i> <%= localeMessage.getString("button.delete") %></button>
            <button type="button" class="cssbtn" id="btn_modify" level="W" status="DETAIL,NEW"><i class="material-icons">save</i> <%= localeMessage.getString("button.modify") %></button>
            <button type="button" class="cssbtn" id="btn_previous" level="W" status="DETAIL,NEW"><i class="material-icons">arrow_back</i> <%= localeMessage.getString("button.previous") %></button>
        </div>
        <div class="title"><%=localeMessage.getString("layoutMan.titleDetail")%>
        </div>

        <form id="ajaxForm">
            <div id="titleRow" class="table_row_title"><%=localeMessage.getString("layoutMan.titleDetail2")%></div>
            <table class="table_row">
                <tr>
                    <th style="width:20%;"><%=localeMessage.getString("layoutMan.layoutCd")%>
                    </th>
                    <td><input type="text" name="loutName"/></td>
                    <th><%=localeMessage.getString("layoutMan.layoutDesc")%>
                    </th>
                    <td><input type="text" name="loutDesc"/></td>
                </tr>
                <tr>
                    <th><%=localeMessage.getString("layoutMan.layoutTypeName")%>
                    </th>
                    <td>
                        <div class="select-style"><select name="loutPtrnName"></select></div>
                    </td>
                    <th style="width:20%;"><%=localeMessage.getString("layoutMan.bzwkdstcdName")%>
                    </th>
                    <td>
                        <div class="select-style"><select name="eaiBzwkDstcd"></select></div>
                    </td>
                </tr>
                <tr>
                    <th><%=localeMessage.getString("layoutMan.sevrDstCd")%>
                    </th>
                    <td>
                        <div class="select-style">
                            <select name="eaiSevrDstcd"></select>
                        </div>
                    </td>
                    <th><%=localeMessage.getString("combo.useYn")%>
                    </th>
                    <td>
                        <div class="select-style">
                            <select name="useYn"></select>
                        </div>
                    </td>
                </tr>
                <tr>
                    <th><%=localeMessage.getString("layoutMan.verInfo")%></th>
                    <td colspan="3">
                        <input type="text" name="verInfo" readonly/>
                    </td>
                </tr>
            </table>
        </form>
        <div id="effectGridRow">
            <div class="table_row_title"><%=localeMessage.getString("layoutMan.rowTitle")%> <span style="font-size:12px;">=><%=localeMessage.getString("layoutMan.rowSpan")%> </span></div>
            <table id="effectGrid"></table>
        </div>
        <div style="margin-top:15px;">
            <div class="table_row_title" style="display: inline;margin-bottom: -8px;"><%=localeMessage.getString("layoutMan.rowTitle2")%></div>
        </div>
        <div id = "gridDiv">
            <div id="grid"></div>
        </div>
        <table id="dataTotalLenRow" class="table_row" cellspacing="0" style="margin-top:15px;">
            <tr>
                <th style="width:20%;"><%=localeMessage.getString("layoutMan.dataTotLen")%></th>
                <td id="dataTotalLen" >	</td>
            </tr>
        </table>
    </div><!-- end content_middle -->

    <div id="add_row_dialog" title="<%=localeMessage.getString("standardLayout.appendRow")%>">
        <%=localeMessage.getString("common.countAppendRow")%> : <input type="text" name="add_row_count" style="width:30px" /><%=localeMessage.getString("layout.count")%>
    </div>
</div><!-- end right_box -->
</body>
</html>

