<%@ 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=euc-kr">
    <jsp:include page="/jsp/common/include/css.jsp"/>
    <jsp:include page="/jsp/common/include/script.jsp"/>
    <link href="<c:url value="/addon/bootstrap-5.3.2/css/bootstrap.min.css"/>" rel="stylesheet"/>
    <script src="<c:url value="/addon/bootstrap-5.3.2/js/bootstrap.bundle.min.js"/>"></script>
    <!-- FilePond stylesheet -->
    <link href="<c:url value="/addon/filepond/filepond.min.css"/>" rel="stylesheet">
    <!-- FilePond JavaScript library -->
    <script src="<c:url value="/addon/filepond/filepond.min.js"/>"></script>
    <!-- FilePond plugin for file validation -->
    <script src="<c:url value="/addon/filepond/plugin/filepond-plugin-file-validate-type.min.js"/>"></script>
    <script language="javascript">
        var url = '<c:url value="/onl/transaction/apim/apiInterfaceMan.json"/>';
        var url_view = '<c:url value="/onl/transaction/apim/apiInterfaceMan.view"/>';
        var url_file = '<c:url value="/onl/transaction/apim/apiInterfaceMan.file"/>';

        var selectName = "searchEaiBzwkDstcd";	// selectBox Name
        function init(callback) {
            $.ajax({
                type: "POST",
                url: url,
                dataType: "json",
                data: {cmd: 'LIST_COMBO'},
                success: function (json) {
                    new makeOptions("BIZCODE", "BIZNAME").setObj($("select[name=searchEaiBzwkDstcd]")).setNoValueInclude(true).setNoValue("", "전체").setData(json.bizList).setFormat(codeName3OptionFormat).rendering();

                    setSearchable(selectName);	// 콤보에 searchable 설정
				    putSelectFromParam();

                    if (typeof callback === 'function') {
                        callback();
                    }
                },
                error: function (e) {
                    alert(e.responseText);
                }
            });

        }

        function detail() {
            var postData = getSearchForJqgrid("cmd", "LIST"); //jqgrid에서는 object 로
            $("#grid").setGridParam({url: url, postData: postData}).trigger("reloadGrid");
        }

        function search() {
            var postData = getSearchForJqgrid("cmd", "LIST"); //jqgrid에서는 object 로
            $("#grid").setGridParam({url: url, postData: postData, page: 1}).trigger("reloadGrid");
        }

        function ioFormatter(cellvalue, options, rowObject) {
            var serviceType = sessionStorage["serviceType"];
            if (cellvalue == "I") {
                return "타발";
            } else if (cellvalue == "O") {
                return "당발";
            }
        }

        function adapterNameShortFormatter(cellvalue, options, rowObject) {
            if (cellvalue == null || cellvalue == '')
                return ''
            return cellvalue.substring(1, 4);
        }

        function apiStatusFormatter(cellvalue, options, rowObject) {
            switch (cellvalue) {
                case 'E': return '장애';
                case 'D': return '지연';
                case 'C': return '점검';
                default: return '정상';
            }
        }

        function list() {
            detail()
            var gridPostData = getSearchForJqgrid("cmd", "LIST"); //jqgrid에서는 object 로
            $('#grid').jqGrid({
                datatype: "json",
                mtype: 'POST',
                url: url,
                postData: gridPostData,
                colNames: ['업무구분',
                    '<%= localeMessage.getString("eaiMessage.eaiSvcName")%>(*)',
                    '<%= localeMessage.getString("eaiMessage.eaiSvcDesc")%>',
                    'API FULL PATH',
                    '요청',
                    '응답',
                    '상태',
                    '작성자',
                    '가상응답여부',
			        '변경일시(*)',
                    'SyncAsyncType',
                ],
                colModel: [{name: 'eaiBzwkDstcd', align: 'center', width: '40', sortable: false},
                    {name: 'eaiSvcName', align: 'left', width: '100', sortable: true},
                    {name: 'eaiSvcDesc', align: 'left', sortable: false},
                    {name: 'apiFullPath', align: 'left', sortable: false},
                    {name: 'fromAdapter', align: 'center', width: '30', formatter: adapterNameShortFormatter, sortable: false},
                    {name: 'toAdapter', align: 'center', width: '30', formatter: adapterNameShortFormatter, sortable: false},
                    {name: 'statusCode', align: 'center', width: '30', formatter: apiStatusFormatter, sortable: false},
                    {name: 'author', align: 'center', width: '40', sortable: false},
			        {name : 'simYn', align : 'center' , width:'40', hidden: true },
			        {name : 'lastModifiedDate', align : 'center' , width:'60', sortable: true},
                    {name: 'syncAsyncType', align: 'center', width: '40', hidden: true},
                ],
                jsonReader: {
                    repeatitems: false
                },
                pager: $('#pager'),
                page: '${param.page}',
                rowNum: '${rmsDefaultRowNum}',
                autoheight: true,
                height: $("#container").height(),
                autowidth: true,
                viewrecords: true,
			    multiselect: true,
			    multiboxonly: false,
                rowList: eval('[${rmsDefaultRowList}]'),               
                ondblClickRow: function (rowId) {
                    var rowData = $(this).getRowData(rowId);
                    let key = rowData['eaiSvcName'];
                    const syncAsyncType = rowData['syncAsyncType'];
                    if (syncAsyncType === 'syncAsync') {
                        const sendRecvType = key.charAt(key.length - 2); // 끝에서 두 번째 문자 추출
                        if (sendRecvType === 'R') {
                            // 문자열의 시작 부분부터 끝에서 세 번째 문자까지 추출
                            var start = key.substring(0, key.length - 2);
                            // 문자열의 마지막 문자 추출
                            var end = key.charAt(key.length - 1);
                            // 시작 부분, 새로운 문자 'S', 그리고 마지막 부분을 결합
                            key = start + 'S' + end;
                        }
                    }

                    var url2 = url_view;
                    url2 += '?cmd=DETAIL';
                    url2 += '&page=' + $(this).getGridParam("page");
                    url2 += '&returnUrl=' + getReturnUrl();
                    url2 += '&menuId=' + '${param.menuId}';
                    //검색값
                    url2 += '&' + getSearchUrl();
                    //key값
                    url2 += '&eaiSvcName=' + key;
                    goNav(url2);
                },
                onSortCol :function(sidx,colnum,sort_order){
                  	var gridPostData = getSearchForJqgrid("cmd","LIST");
                  	var sortorder="";
                  	if( sort_order == "") 
                  		sortorder ='asc';
                  	else
                  		sortorder = sort_order;
                  	gridPostData["sortName"] =sidx;
                	gridPostData["sortOrder"]=sortorder;
                	$("#grid").setGridParam({ url:url, postData: gridPostData, sortname:sidx, sortorder:sortorder, page:"1"}).trigger("reloadGrid");             	 
                }
            });
            
        }

        $(document).ready(function () {

            init(list);

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

            $("#btn_search").click(function () {
                search();
            });
            $("#btn_new").click(function () {
                var url2 = url_view;
                url2 += '?cmd=DETAIL';
                url2 += '&page=' + $("#grid").getGridParam("page");
                url2 += '&returnUrl=' + getReturnUrl();
                url2 += '&menuId=' + '${param.menuId}';
                //검색값
                url2 += '&' + getSearchUrl();
                //key값
                url2 += '&eaiSvcName=';

                goNav(url2);
            });

            $("input[name^=search]").keydown(function (key) {
                if (key.keyCode == 13) {
                    $("#btn_search").click();
                }
            });

		function callDownload(interfaceId){
			const url = '<c:url value="/loader.do" />';
			const postData = [];
			postData.push({ name: "cmd" , value: 'interface'});
			postData.push({ name: "control" , value:"downloadfull"});
			postData.push({ name: "interfaceId" , value: interfaceId});
			return new Promise((resolve, reject) => {
				$.ajax({
					type: "POST",
					url: url,
					data: postData,
					success: function (response) {
						resolve(response);
					},
					error: function (error) {
						reject(error);
					}
				});
			});
		}
		async function deployDownload(interfaceId){
			try {
				let response = await callDownload(interfaceId);
				return response.trim();
			} catch (error) {
				window.alert(interfaceId+' download error '+JSON.stringify(error));
			}
		}
		
		$("#btn_download").click(async function(){
			const rowIds = $('#grid').jqGrid('getGridParam', 'selarrrow');
			let successCount = 0;
			let failedCount = 0;
			for(let i = 0; i < rowIds.length; i++){
				const rowData = $("#grid").getRowData(rowIds[i]);
				const response = await deployDownload(rowData['eaiSvcName']);
				if(response != null && response.includes('success')){
					successCount++;	
				}else{
					failedCount++
				}				
			}
			window.alert('이관 대상 API 성공['+successCount+']건, 실패['+failedCount+']건 서버에 다운로드 완료');
		});
		
        buttonControl();

		// 25.11.25 파일 가져오기 할 때 중복 검사 기능추가.
        FilePond.registerPlugin(FilePondPluginFileValidateType);

        let uploadErrors = [];
        let processedCount = 0;
        let totalFiles = 0;

        // FilePond 인스턴스 생성
        const pond = FilePond.create(document.querySelector('.filepond'), {
            instantUpload: false,
            allowRevert: false,
            acceptedFileTypes: ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/json'],

         	// 서버 설정
			server: {
				process: {
					url: url_file + '?cmd=LIST_IMPORT_FILE&serviceType=' + sessionStorage["serviceType"],
					method: 'POST',
					ondata: (formData) => {
                        const chkBox = document.querySelector('#uploadModal input[name="importDupliCheck"]'); 
                        const isChecked = chkBox ? chkBox.checked : false;
                        formData.append('importDupliCheck', isChecked);
                        return formData;
                    },
                    onerror: (response) => {
                        return response;
                    }
                }
            }
        });

        // 파일 처리 결과 수신
        pond.on('processfile', (error, file) => {
            processedCount++;

            if (error) {
                let errorMsg = '';
                
                if (error.body) {
					errorMsg = error.body;
                } else if (typeof error === 'string') {
                    errorMsg = error;
                } else {
					errorMsg = '가져오기 중 오류가 발생 했습니다.';
                }
                
                let fileName = 'UnKnown';
                if (file) {
					if(file.filename) fileName = file.filename;
					else if (file.file && file.file.name) fileName = file.file.name;
                }

                uploadErrors.push('파일명 [ ' + fileName + '] \n MESSAGE : ' + errorMsg);
            }

            // 모든 파일 처리 완료 시
            if (processedCount >= totalFiles) {
                setTimeout(() => {
                    if (uploadErrors.length > 0) {
                        const msg = "파일 처리 중 오류가 발생했습니다. \n" + uploadErrors.join('\n');

                        // 실패 시 변수 초기화
                        uploadErrors = [];
                        processedCount = 0;

                        $('#btn_search').click();
                        alert(msg);

                    } else {
                        alert('모든 파일이 성공적으로 업로드 되었습니다.');
                        $('#uploadModal').modal('hide');
                        $('#btn_search').click();
                    }
                }, 100);
            }
        });

        // 업로드 버튼 클릭 이벤트
        document.getElementById('uploadButton').addEventListener('click', function(e) {
            e.stopPropagation(); 
            
            uploadErrors = [];
            processedCount = 0;

            const currentFiles = pond.getFiles();
            totalFiles = currentFiles.length;

            if (totalFiles === 0) {
                alert("업로드 할 파일을 선택하세요.");
                return;
            }

            const chkBox = document.getElementById('importDupliCheck');

            if (chkBox && !chkBox.checked) {
                if (!confirm("중복검사를 체크하지 않는 경우 기존 값은 덮어 씌워집니다. \n진행하시겠습니까?")) {
                    return; 
                }
            }

            pond.processFiles();
        });

        // 모달이 닫힐 때만 초기화
        $('#uploadModal').on('hidden.bs.modal', function(e) {
            resetPond();
        });

        function resetPond() {
            pond.removeFiles(); 

            const chkBox = document.getElementById('importDupliCheck');
            if (chkBox) chkBox.checked = false;

            processedCount = 0;
            totalFiles = 0;
            uploadErrors = [];
        }

    });

    </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_download" level="W" status="DETAIL"><i class="material-icons">cloud_download</i> 이관</button>
            <button type="button" class="cssbtn" id="btn_import" level="R" data-bs-toggle="modal"
                    data-bs-target="#uploadModal"><i
                    class="material-icons">upload</i> <%=localeMessage.getString("button.import")%>
            </button>
            <button type="button" class="cssbtn" id="btn_new" level="W"><i
                    class="material-icons">add</i> <%= localeMessage.getString("button.new") %>
            </button>
            <button type="button" class="cssbtn" id="btn_search" level="R"><i
                    class="material-icons">search</i> <%= localeMessage.getString("button.search") %>
            </button>
        </div>
        <div class="title" id="title">${rmsMenuName}</div>
        <table class="search_condition" cellspacing=0;>
            <tbody>
            <tr>
                <th style="width:180px;">업무구분명</th>
                <td>
                    <select name="searchEaiBzwkDstcd" value="${param.searchEaiBzwkDstcd}"></select>
                </td>
                <th style="width:180px;"><%= localeMessage.getString("eaiMessage.eaiSvcName")%></th>
                <td>
                    <input type="text" name="searchEaiSvcName" value="${param.searchEaiSvcName}">
                </td>
            </tr>
            <tr>
                <th style="width:180px;"><%= localeMessage.getString("eaiMessage.eaiSvcDesc")%></th>
                <td>
                    <input type="text" name="searchEaiSvcDesc" value="${param.searchEaiSvcDesc}">
                </td>
                <th style="width:180px;">API FULL PATH</th>
                <td>
                    <input type="text" name="searchApiFullPath" value="${param.searchApiFullPath}">
                </td>
            </tr>
            </tbody>
        </table>
        <div class="help-text" style="color:#666; font-size:12px; margin-top:5px;">(*) : 정렬가능항목</div>
        <table id="grid"></table>
        <div id="pager"></div>
    </div><!-- end content_middle -->
</div><!-- end right_box -->
<!-- Modal -->
<div class="modal fade" id="uploadModal" tabindex="-1" aria-labelledby="uploadModalLabel" aria-hidden="true">
    <!-- 모달 내용 -->
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="material-icons"
                                           style="vertical-align: sub; font-size: 25px">publish</i> <%=localeMessage.getString("button.import")%>
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
            	<!-- 파일 업로드 시 중복체크 -->
            	
            	<input type="checkbox" id="importDupliCheck" name="importDupliCheck">
            		<label class="form-check-label" for="importDupliCheck">중복검사</label>
                <input type="file" class="filepond" name="file" multiple data-allow-reorder="true"
                       data-max-file-size="3MB" data-max-files="10">
            </div>
            <div class="modal-footer">
                <button id="uploadButton" class="btn btn-primary">IMPORT <%=localeMessage.getString("button.execute")%>
                </button>
            </div>
        </div>
    </div>
</div>
</body>
</html>