<%@ 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");
%>

<!DOCTYPE html>
<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"/>
    <style>
        .CodeMirror {
            border: 1px solid #eee;
            height: auto;
        }
    </style>
    <script language="javascript">
        var url = '<c:url value="/onl/transaction/apim/apiSpecMan.json" />';
        var url_org ='<c:url value="/onl/transaction/apim/apiSpecMan.view" />';
        var isDetail = false;
        var sampleRequestEditor, sampleResponseEditor, testbedSpecEditor;

        function init() {
            var key = "${param.eaiSvcName}";
            // console.log({key});
            if (key !== "" && key !== null) {
                isDetail = true;
                detail(key);
            } else {
                buttonControl(false);
            }

            initializeCodeMirror();
            initializeSummernote();
        }

        function initializeCodeMirror() {
            var commonOptions = {
                lineNumbers: true,
                matchBrackets: true,
                mode: "application/json",
                autoCloseBrackets: true,
                viewportMargin: Infinity, // This allows the editor to expand beyond the default height
                extraKeys: {"Ctrl-Space": "autocomplete"}
            };

            sampleRequestEditor = CodeMirror.fromTextArea(document.getElementById('sampleRequest'), commonOptions);
            sampleResponseEditor = CodeMirror.fromTextArea(document.getElementById('sampleResponse'), commonOptions);
            testbedSpecEditor = CodeMirror.fromTextArea(document.getElementById('testbedSpec'), commonOptions);

            // Set initial size and add resize capability
            sampleRequestEditor.setSize(null, 200);
            sampleResponseEditor.setSize(null, 200);
            testbedSpecEditor.setSize(null, 200);

            // Refresh editors after initialization to ensure proper rendering
            setTimeout(function () {
                sampleRequestEditor.refresh();
                sampleResponseEditor.refresh();
                testbedSpecEditor.refresh();
            }, 1);
        }

        function initializeSummernote() {
            // Summernote 에디터 초기화 (이미지 붙여넣기 data-uri 방식, 리사이징 지원)
            var commonOptions = {
                height: 300,
                toolbar: [
                    ['style', ['style']],
                    ['font', ['bold', 'underline', 'clear']],
                    ['color', ['color']],
                    ['para', ['ul', 'ol', 'paragraph']],
                    ['table', ['table']],
                    ['insert', ['link', 'picture', 'video']],
                    ['view', ['codeview', 'help']]
                ]
            };

            initSummernote('#description', commonOptions);
            initSummernote('#apiRequestSpec', commonOptions);
            initSummernote('#apiResponseSpec', commonOptions);
        }

        function detail(key) {
            // console.log('Before AJAX call, key:', key);  // Log the key before the AJAX call
            $.ajax({
                type: "POST",
                url: url,
                dataType: "json",
                data: {cmd: 'DETAIL', eaiSvcName: key},
                success: function (data) {
                    // console.log('AJAX response data:', data);

                    $("#ajaxForm input, #ajaxForm textarea, #ajaxForm select").each(function () {
                        var name = $(this).attr("name");

                        if (name === 'displayYn') {
                            $('#displayYn').prop('checked', data.displayYn === "Y");
                            return;
                        }

                        if (name === 'displayRoleCode') {
                            $('input[name="displayRoleCode"]').prop('checked', false);
                            if (data.displayRoleCode) { // displayRoleCode가 있을 때만 실행
                                var roles = data.displayRoleCode.split(',').map(role => role.trim());
                                roles.forEach(role => {
                                    $('input[name="displayRoleCode"][value="' + role + '"]').prop('checked', true);
                                });
                            }
                            return;
                        }

                        if (name === 'displayOrg') {
                            $('#displayOrg').val(data.displayOrg || '');
                            $('#displayOrgName').val(data.orgName || '');
                            return;
                        }

                        var tag = $(this).prop("tagName").toLowerCase();
                        var value = data[name] || ''; // Provide a default empty string if the value is null or undefined

                        if (name === 'description' || name === 'apiRequestSpec' || name === 'apiResponseSpec') {
                            $('#' + name).summernote('code', value);
                        } else if (name === 'sampleRequest') {
                            sampleRequestEditor.setValue(value);
                        } else if (name === 'sampleResponse') {
                            sampleResponseEditor.setValue(value);
                        } else if (name === 'testbedSpec') {
                            testbedSpecEditor.setValue(value);
                        } else {
                            if (name !== 'apiId')
                                $(tag + "[name=" + name + "]").val(value);
                        }
                    });
                    $("#apiId").val(key);
                    // console.log('After setting apiId, key:', key);  // Log the key after setting apiId

                    buttonControl(true);

					// 조회된 Spec 데이터가 없다면 인터페이스 화면의 값을 세팅함.
					if (!data.apiId) {
	                    var args = window.dialogArguments;
						
						if (args && args.apipath) {
							// HS04 의 fullpath 메서드/URL로 분리
							var rawString = args.apipath;

							var parts = rawString.split('|');

							var method = parts[0].trim();
							var url = parts[1].trim();
							
							if ($('#apiName').val() === "" && args.eaiSvcDesc) {
								$('#apiName').val(args.eaiSvcDesc);
							}

							if ($('#apiUrl').val() === "" && url) {
								$('#apiUrl').val(url);
							}

							if (method) {
								$('#apiMethod').val(method);
							}

							if ($('#apiContentType').val() === "" && args.contentType) {
								$('#apiContentType').val(method);
							}
						}
					}
                },
                error: function (e) {
                    console.error('AJAX error:', e);  // Log any errors
                    alert(e.responseText);
                }
            });
        }

        function saveApiSpec() {
            var postData = $('#ajaxForm').serializeArray();
            postData.push({name: 'cmd', value: 'INSERT'});
            postData = postData.filter(item =>
                !['description', 'apiRequestSpec', 'apiResponseSpec', 'sampleRequest', 'sampleResponse',
                  'testbedSpec', 'displayRoleCode', 'displayYn', 'displayOrg', 'displayOrgName'].includes(item.name)
            );
            postData.push({name: 'description', value: $('#description').summernote('code')});
            postData.push({name: 'apiRequestSpec', value: $('#apiRequestSpec').summernote('code')});
            postData.push({name: 'apiResponseSpec', value: $('#apiResponseSpec').summernote('code')});
            postData.push({name: 'testbedSpec', value: testbedSpecEditor.getValue()});
            postData.push({name: 'sampleRequest', value: sampleRequestEditor.getValue()});
            postData.push({name: 'sampleResponse', value: sampleResponseEditor.getValue()});

            postData.push({name: 'displayYn',  value: $('#displayYn').is(':checked') ? 'Y' : 'N'});

            // displayOrg 값 추가
            var displayOrgValue = $('#displayOrg').val();
            if (displayOrgValue) {
                postData.push({name: 'displayOrg', value: displayOrgValue});
            }

            // displayRoleCode 값 추가
            var roleValues = $('input[name="displayRoleCode"]:checked')
                .map(function() { return $(this).attr('value'); })
                .get()
                .join(',');

            if (roleValues) {
                postData.push({name: 'displayRoleCode', value: roleValues});
            }

            $.ajax({
                type: "POST",
                url: url,
                data: postData,
                beforeSend: function() {
                	$("[id^='btn_']").prop("disabled", true);
                	$("#btn_save").text("처리중 . . . . .");
                },
                success: function () {
                    alert("<%= localeMessage.getString("common.saveMsg") %>");
                },
                error: function (e) {
                    alert(e.responseText);
                },
                complete: function() {
                	$("[id^='btn_']").prop("disabled", false);
					$("#btn_save").text("수정");
                }
            });
        }

        // displayOrg를 선택하고 돌아올 때의 처리
        window.selectOrg = function(selectedOrgs) {
            // if (!selectedOrgs || selectedOrgs.length === 0) {
            //     return;
            // }

            // ID는 hidden input에 저장
            var orgIds = selectedOrgs.map(org => org.id).join(',');
            $('#displayOrg').val(orgIds);

            // 화면에는 기관명 표시
            var orgNames = selectedOrgs.map(org => org.orgName).join(', ');
            $('#displayOrgName').val(orgNames);
        };

        function formatDisplayOrg(orgIds) {
            if (!orgIds) return '';
            return orgIds.split(',').map(id => id.trim()).join(', ');
        }

        function openOrgPopup() {
            var popupUrl = url_org + "?cmd=POPUP_LIST";

            var selectedOrgIds = $('#displayOrg').val() || ''; // 현재 선택된 기관 ID들
            if (selectedOrgIds) {
                popupUrl += "&selectedOrgIds=" + encodeURIComponent(selectedOrgIds);
            }

            var args = { title:'공개 법인 리스트', selectedOrgIds: selectedOrgIds };
            showModal(popupUrl, args, 450, 550);
        }

        // 팝업에서 선택한 데이터를 부모창으로 반환하는 함수
        function selectOrg(selectedOrgs) {
            if (!selectedOrgs || selectedOrgs.length === 0) {
                $('#displayOrg').val('');
                $('#displayOrgName').val('');
                return;
            }
            var orgIds = selectedOrgs.map(org => org.id).join(',');
            $('#displayOrg').val(orgIds);

            var orgNames = selectedOrgs.map(org => org.orgName).join(', ');
            $('#displayOrgName').val(orgNames);
        }

        function deleteApiSpec() {
            if (!confirm("<%= localeMessage.getString("common.confirmMsg") %>")) {
                return;
            }

            $.ajax({
                type: "POST",
                url: url,
                data: { cmd: 'DELETE', apiId: $('#apiId').val() },
                beforeSend: function() {
                	$("[id^='btn_']").prop("disabled", true);
                	$("#btn_delete").text("처리중 . . . . .");
                },
                success: function() {
                    alert("<%= localeMessage.getString("common.deleteMsg") %>");
                    window.close();
                },
                error: function(e) {
                    alert(e.responseText);
                },
                complete: function() {
                	$("[id^='btn_']").prop("disabled", false);
					$("#btn_delete").text("삭제");
                }
            });
        }

        function generateSpecFromLayout() {
            $.ajax({
                type: "POST",
                url: url,
                data: {
                    cmd: 'GENERATE_SPEC',
                    apiId: $('#apiId').val()
                },
                beforeSend: function() {
                	$("[id^='btn_']").prop("disabled", true);
                	$("#btn_generate_spec").text("처리중 . . . . .");
                },
                success: function(data) {
                    // Update the editors with generated content
                    $('#apiRequestSpec').summernote('code', data.requestSpec);
                    $('#apiResponseSpec').summernote('code', data.responseSpec);
                    sampleRequestEditor.setValue(data.sampleRequest);
                    sampleResponseEditor.setValue(data.sampleResponse);
                    testbedSpecEditor.setValue(data.testbedSpec);

                    alert("API 스펙이 성공적으로 생성되었습니다.\n* 필수여부는 직접 입력이 필요합니다.");
                },
                error: function(e) {
                    alert("API 스펙 생성 중 오류가 발생했습니다: " + e.responseText);
                },
                complete: function() {
                	$("[id^='btn_']").prop("disabled", false);
					$("#btn_generate_spec").text("SPEC 자동 생성");
                }
            });
        }

        $(document).ready(function () {
            init();

            $("#btn_save").click(saveApiSpec);
            $("#btn_close").click(function () {
                window.close();
            });
            $("#btn_select_org").click(openOrgPopup);
            $("#btn_delete").click(deleteApiSpec);

            $("#btn_generate_spec").click(generateSpecFromLayout);
        });
    </script>
</head>
<body>
<div class="popup_box">
    <div class="search_wrap">
        <button type="button" class="cssbtn" id="btn_generate_spec" level="W" status="DETAIL">
            <i class="material-icons">auto_fix_high</i> SPEC 자동 생성
        </button>
        <button type="button" class="cssbtn" id="btn_save" level="W" status="DETAIL"><i
                class="material-icons">save</i> <%= localeMessage.getString("button.modify") %>
        </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_close" level="R" status="DETAIL"><i
                class="material-icons">close</i> <%= localeMessage.getString("button.close") %>
        </button>
    </div>
    <div class="title">API 스펙 관리</div>
    <form id="ajaxForm">
        <input type="hidden" name="apiId" id="apiId" class="form-control">
        <table class="table_row" cellspacing="0">
            <tr>
                <th>API 이름</th>
                <td><input type="text" name="apiName" id="apiName" class="form-control"></td>
            </tr>
            <tr>
                <th>간단 설명</th>
                <td><input type="text" name="apiSimpleDescription" id="apiSimpleDescription" class="form-control"></td>
            </tr>
            <tr>
                <th>API URL</th>
                <td><input type="text" name="apiUrl" id="apiUrl" class="form-control"></td>
            </tr>
            <tr>
                <th>API 메소드</th>
                <td>
                    <select name="apiMethod" id="apiMethod" class="form-select">
                        <option value="GET">GET</option>
                        <option value="POST">POST</option>
                        <option value="PUT">PUT</option>
                        <option value="DELETE">DELETE</option>
                    </select>
                </td>
            </tr>
            <tr>
                <th>공개 여부</th>
                <td>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="displayYn" id="displayYn" value="Y">
                        <label class="form-check-label" for="displayYn">공개</label>
                    </div>
                </td>
            </tr>
            <tr>
                <th>공개 권한</th>
                <td>
                    <div id="roleCheckboxes" style="display: flex;">
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="checkbox" name="displayRoleCode" value="ROLE_USER">
                            <label class="form-check-label" style="margin-right: 15px;">개인사용자</label>
                        </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="checkbox" name="displayRoleCode" value="ROLE_CORP_USER">
                            <label class="form-check-label" style="margin-right: 15px;">법인사용자</label>
                        </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="checkbox" name="displayRoleCode" value="ROLE_CORP_MANAGER">
                            <label class="form-check-label">법인관리자</label>
                        </div>
                    </div>
                </td>
            </tr>
            <tr>
                <th>공개 법인</th>
                <td>
                    <div style="display: flex;">
                        <input type="text" id="displayOrgName" class="form-control" style="margin-right: 5px;" readonly>
                        <input type="hidden" id="displayOrg" name="displayOrg">
                        <button type="button" class="smallBtn2 cssbtn" id="btn_select_org">
                            <i class="material-icons">add</i> 선택
                        </button>
                    </div>
                </td>
            </tr>
            <tr>
                <th>API Content Type</th>
                <td><input type="text" name="apiContentType" id="apiContentType" class="form-control"></td>
            </tr>
            <tr>
                <th>설명</th>
                <td><textarea name="description" id="description" class="form-control" rows="3"></textarea></td>
            </tr>
            <tr>
                <th>테스트베드 스펙</th>
                <td><textarea name="testbedSpec" id="testbedSpec" class="form-control" rows="5"></textarea></td>
            </tr>
            <tr>
                <th>요청 메시지 스펙</th>
                <td><textarea name="apiRequestSpec" id="apiRequestSpec" class="form-control" rows="5"></textarea></td>
            </tr>
            <tr>
                <th>요청 메시지 예제</th>
                <td><textarea name="sampleRequest" id="sampleRequest" class="form-control" rows="5"></textarea></td>
            </tr>

            <tr>
                <th>응답 메시지 스펙</th>
                <td><textarea name="apiResponseSpec" id="apiResponseSpec" class="form-control" rows="5"></textarea></td>
            </tr>
            <tr>
                <th>응답 메시지 예제</th>
                <td><textarea name="sampleResponse" id="sampleResponse" class="form-control" rows="5"></textarea></td>
            </tr>
            <tr>
                <th>응답 유형</th>
                <td>
                    <select name="responseType" class="form-select">
                        <option value="sample">Sample</option>
                        <option value="mock">Mock</option>
                    </select>
                </td>
            </tr>
            <tr>
                <th>Mock URL</th>
                <td><input type="text" name="mockUrl" class="form-control"></td>
            </tr>
        </table>
    </form>
</div>
</body>
</html>
