<%@ page language="java" contentType="text/html; charset=utf-8" %>
<%@ page import="java.io.*" %>
<%@ 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");
%>

<html>
<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"/>

    <script language="javascript">
        var url = '<c:url value="/onl/apim/approval/prodclient/clientMan.json" />';
        var api_url_view = '<c:url value="/onl/apim/apigroup/apiGroupMan.view" />';
        var group_url_view = '<c:url value="/onl/admin/authserver/clientMan.view" />';

        var isDetail = false;

        function isValid() {
            if ($('input[name=clientname]').val() == "") {
                alert("CLIENT명을 입력하여 주십시요.");
                $('input[name=clientname]').focus();
                return false;
            }
            if ($('input[name=clientId]').val() == "") {
                alert("CLIENT 아이디를 입력하여 주십시요.");
                $('input[name=clientId]').focus();
                return false;
            }

            return true;
        }

        function detail(key) {
            if (!isDetail) return;
            $.ajax({
                type: "POST",
                url: url,
                dataType: "json",
                data: {cmd: 'DETAIL', clientId: key},
                success: function (json) {
                    var apiList = json["apiList"];
                    $("#selectedApiGrid").jqGrid("clearGridData");
                    $("#selectedApiGrid")[0].addJSONData(apiList);

                    var data = json;
                    $("#btn_gen_id").hide();
                    $('input[name=clientId]').css('width', '100%');
                    $('input[name=clientId]').attr('readonly', true);
                    $("#btn_clientId_byte").hide();
                    $("#btn_gen_secret").hide();
                    $('input[name=clientSecret]').css('width', '100%');
                    $('input[name=clientSecret]').attr('readonly', true);
                    $("#btn_clientSecret_byte").hide();

                    $("#ajaxForm input[type!=checkbox],#ajaxForm select,#ajaxForm textarea").each(function () {
                        var name = $(this).attr("name");
                        var tag = $(this).prop("tagName").toLowerCase();
                        $(tag + "[name=" + name + "]").val(data[name]);
                    });

                    // Set the appStatus dropdown value
                    if (json.appstatus !== undefined && json.appstatus !== null) {
                        $('select[name=appStatus]').val(json.appstatus);
                    } else {
                        $('select[name=appStatus]').val('1'); // Set to normal if no value
                    }
                },
                error: function (e) {
                    alert(e.responseText);
                }
            });
        }

        function init(key, callback) {

            var selectedApiGrid = $("#selectedApiGrid");
            selectedApiGrid.jqGrid({
                datatype: "local",
                colNames: ['API ID', 'API 명'],
                colModel: [
                    {name: 'apiId', index: 'apiId', width: 100, align: 'center'},
                    {name: 'apiName', index: 'apiName', width: 100, align: 'center'}
                ],
                rowNum: 10,
                rowList: [10, 20, 30],
                pager: '#selectedApiGridPager',
                sortname: 'apiId',
                viewrecords: true,
                sortorder: "asc",
                caption: "선택된 API",
                height: 200,
                autowidth: true,
                multiselect: true,
                ondblClickRow: function (rowid, status, e) {
                    // selectedApiGrid.jqGrid('delRowData', rowid);
                }
            });
            $.ajax({
                type: "POST",
                url: url,
                dataType: "json",
                data: {cmd: 'LIST_DETAIL_COMBO'},
                success: function (json) {
                    json.portalOrgList.unshift({
                        id: "",  // 실제 저장될 값은 빈 문자열
                        orgName: "미분류"  // 화면에 표시될 텍스트
                    });
                    new makeOptions("id", "orgName")
                        .setObj($("select[name=orgid]"))
                        .setFormat(nameOptionFormat)
                        .setData(json.portalOrgList).rendering();
                },
                error: function (e) {
                    alert(e.responseText);
                }
            });

            callback(key);
        }

        $(document).ready(function () {
            var returnUrl = getReturnUrlForReturn();
            var key = "${param.clientId}";
            if (key != "" && key != "null") {
                isDetail = true;
            }
            init(key, detail);

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

                var data = $("#selectedApiGrid").getRowData();
                var gridData = [];
                for (var i = 0; i < data.length; i++) {
                    gridData.push({apiId: data[i]['apiId']});
                }

                const orgName = $("select[name=orgid] option:selected").text();
                postData.push({
                    name: "orgname",
                    value: orgName
                });

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

                $.ajax({
                    type: "POST",
                    url: url,
                    data: postData,
                    success: function (args) {
                        alert("저장 되었습니다.");
                        goNav(returnUrl);//LIST로 이동
                    },
                    error: function (e) {
                        alert(e.responseText);
                    }
                });
            });

            $("#btn_delete").click(function () {
                if (confirm("삭제하시겠습니까?")) {
                    var postData = $('#ajaxForm').serializeArray();
                    postData.push({name: "cmd", value: "DELETE"});
                    $.ajax({
                        type: "POST",
                        url: url,
                        data: postData,
                        success: function (args) {
                            if (args.status == "error") {
                                alert("동기화중 오류입니다.\n확인하여 주십시요.\n" + args.message);
                            } else {
                                alert("삭제 되었습니다.");
                                goNav(returnUrl);//LIST로 이동
                            }
                        },
                        error: function (e) {
                            alert(e.responseText);
                        }
                    });
                }
            });

            $("#btn_popup_api").click(function () {
                const args = {};
                const url2 = api_url_view += "?cmd=POPUP";
                showModal(url2, args, 1280, 860, function () {
                    const popupFrame = args.self.frames[0];
                    const returnValue = popupFrame.returnValue;
                    const frameElement = popupFrame.frameElement
                    const parentElement = frameElement.parentNode; // 부모 노드를 가져옴

                    if (parentElement) { // 부모 노드가 존재하는지 확인
                        parentElement.removeChild(frameElement);
                    }

                    var rows = $("#selectedApiGrid").jqGrid('getRowData');
                    console.log(returnValue);

                    const apiId = returnValue.apiId;
                    var apiIdExists = rows.some(function (row) {
                        return row.apiId === apiId;
                    });

                    if (apiIdExists) {
                        return;
                    }
                    returnValue.apiName = returnValue.apiDesc;
                    var ids = $("#selectedApiGrid").jqGrid('getDataIDs');
                    var lastId = ids.length > 0 ? Math.max.apply(Math, ids) : 0;
                    var newId = lastId + 1;
                    $("#selectedApiGrid").jqGrid('addRowData', newId, returnValue, "last");
                });
            });

            $("#btn_popup_api_group").click(function () {
                const args = {};
                const url2 = group_url_view += "?cmd=GROUP_POPUP";
                showModal(url2, args, 1280, 860, function () {
                    const popupFrame = args.self.frames[0];
                    const returnValue = popupFrame.returnValue;
                    const frameElement = popupFrame.frameElement
                    const parentElement = frameElement.parentNode; // 부모 노드를 가져옴

                    if (parentElement) { // 부모 노드가 존재하는지 확인
                        parentElement.removeChild(frameElement);
                    }

                    var rows = $("#selectedApiGrid").jqGrid('getRowData');
                    console.log(returnValue);
                    if (!returnValue.apiGroupApiList || returnValue.apiGroupApiList.length === 0) {
                        return; // If apiGroupApiList is empty, do nothing
                    }

                    returnValue.apiGroupApiList.forEach(function (apiGroupApi) {
                        const apiId = apiGroupApi.apiId;
                        var apiIdExists = rows.some(function (row) {
                            return row.apiId === apiId;
                        });

                        if (apiIdExists) {
                            return;
                        }
                      apiGroupApi.apiName = apiGroupApi.apiDesc;
                        var ids = $("#selectedApiGrid").jqGrid('getDataIDs');
                        var lastId = ids.length > 0 ? Math.max.apply(Math, ids) : 0;
                        var newId = lastId + 1;
                        $("#selectedApiGrid").jqGrid('addRowData', newId, apiGroupApi, "last");
                    });
                });
            });

            $("#btn_delete_api").click(function () {
                var grid = $("#selectedApiGrid");
                var selectedRowIds = grid.jqGrid('getGridParam', 'selarrrow'); // 선택된 행의 ID 배열을 가져옴
                if (selectedRowIds.length > 0) {
                    // 선택된 행의 ID를 복사한 배열을 사용
                    var idsToDelete = selectedRowIds.slice();

                    for (var i = 0; i < idsToDelete.length; i++) {
                        grid.jqGrid('delRowData', idsToDelete[i]); // 선택된 각 행을 삭제
                    }
                } else {
                    alert("Please select at least one row to delete.");
                }
            });

            $("#btn_previous").click(function () {
                goNav(returnUrl);//LIST로 이동
            });

            $("#btn_gen_id").click(function () {
                //$('input[name=clientId]').val(generateString(32));
                $('input[name=clientId]').val(generateString($("#btn_clientId_byte").val()));
            });

            $("#btn_gen_secret").click(function () {
                //$('input[name=clientSecret]').val(generateString(128));
                $('input[name=clientSecret]').val(generateString($("#btn_clientSecret_byte").val()));
            });

            buttonControl(isDetail);
            titleControl(isDetail);
        });

        const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

        function generateString(length) {
            let result = '';
            const charactersLength = characters.length;
            const randomValues = new Uint32Array(length);
            window.crypto.getRandomValues(randomValues);
            for (let i = 0; i < length; i++) {
                result += characters.charAt(randomValues[i] % charactersLength);
            }
            return result;
        }

    </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">
        <div class="search_wrap">
            <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="R" status="DETAIL,NEW"><i
                    class="material-icons">arrow_back</i> <%= localeMessage.getString("button.previous") %>
            </button>
        </div>
        <div class="title" id="title">${rmsMenuName}</div>

        <form id="ajaxForm">
            <table class="table_row" cellspacing="0">
                <tr>
                    <th style="width:180px;"><%= localeMessage.getString("clntManDtl.clntNm") %> <small>(*)</small></th>
                    <td><input type="text" name="clientname"/></td>
                </tr>
                <tr>
                    <th><%= localeMessage.getString("clntManDtl.clntId") %> <small>(*)</small></th>
                    <td>
                        <input type="text" name="clientid" style="width: calc(100% - 142px);"/>
                        <select name="clientId_byte" id="btn_clientId_byte" style="width: 76px;">
                            <option value="32" selected="selected">32 byte</option>
                            <option value="64">64 byte</option>
                            <option value="128">128 byte</option>
                            <option value="256">256 byte</option>
                        </select>
                        <img src="<c:url value="/img/btn_pop_input.png"/>" id="btn_gen_id"/>
                    </td>
                </tr>
                <tr>
                    <th>APP 상태</th>
                    <td>
                        <div class="select-style">
                            <select name="appstatus">
                                <option value="1" selected>정상</option>
                                <option value="0">차단</option>
                            </select>
                        </div>
                    </td>
                </tr>
                <tr>
                    <th>법인</th>
                    <td>
                        <div class="select-style">
                            <select id="orgId" class="form-control" name="orgid">
                            </select>
                        </div>
                    </td>
                </tr>
            </table>
        </form>
        <div style="font-size:0;">
            <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 5px ">
                <div class="table_row_title" style="margin-bottom: 0px">API</div>
                <div style="text-align: end;">
                    <button type="button" class="cssbtn" id="btn_delete_api" level="W" status="DETAIL,NEW">
                        <i class="material-icons">delete</i> <%= localeMessage.getString("button.delete") %>
                    </button>
                    <button type="button" class="cssbtn" id="btn_popup_api" level="W" status="DETAIL,NEW">
                        <i class="material-icons">add</i> API <%= localeMessage.getString("button.add") %>
                    </button>
                    <button type="button" class="cssbtn" id="btn_popup_api_group" level="W" status="DETAIL,NEW">
                        <i class="material-icons">add</i> API 그룹<%= localeMessage.getString("button.add") %>
                    </button>
                </div>
            </div>
            <div style="display:inline-block; width:calc(100%); vertical-align:top;">
                <div id="selectedApiList" style="margin-top:10px;">
                    <table id="selectedApiGrid"></table>
                </div>
            </div>
        </div>
    </div><!-- end content_middle -->
</div><!-- end right_box -->
</body>
</html>
