<%@ page import="com.eactive.eai.rms.common.util.CommonConstants" %>
<%@ page import="com.eactive.eai.rms.common.login.LoginVo" %>
<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ 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>
    <style>
        .table_row tbody tr.highlight_new {
            background-color: #e6f3ff !important;
        }
        .table_row tbody tr.highlight_delete {
            background-color: #ffe6e6 !important;
        }
        .table_row tbody tr.highlight_new td.status {
            color: #4a90e2;
            font-weight: normal;
        }
        .table_row tbody tr.highlight_delete td.status {
            color: #e74c3c;
            font-weight: normal;
        }
    </style>
    <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">
        <%
          LoginVo loginVo = (LoginVo) session.getAttribute(CommonConstants.LOGIN);
        %>
        var loginUser = '<%= loginVo.getUserId() %>';
        var url = '<c:url value="/onl/apim/approval/portalApprovalMan.json" />';
        var url_view = '<c:url value="/onl/apim/approval/portalApprovalMan.view" />';
        
        function dateFormat(cellvalue) {
    		if ( cellvalue == null || cellvalue.length < 8 )
    			return '';
    		return  cellvalue.substr(0 ,4) + '-' +
    				cellvalue.substr(4, 2) + '-' +
    				cellvalue.substr(6, 2) ;
    	}

        $(document).ready(function () {
            var key = "${param.id}";
            if (key) {
                detail(key);
            }
            
            $("#expectEndDate").datepicker().inputmask("yyyy-mm-dd", {'autoUnmask': true});

            $("#btn_app_approve").click(function () {
                if (confirm("승인하시겠습니까?")) {
                    $.ajax({
                        type: "POST",
                        url: url,
                        data: {cmd: "APPROVE", id: key},
                        success: function (args) {
                            <%--alert("<%= localeMessage.getString("approval.approveSuccess") %>");--%>
                            alert("승인되었습니다.");
                            if (window.dialogArguments && window.dialogArguments.self) {
                                window.dialogArguments.self.location.reload();
                            } else if (window.opener) {
                                window.opener.location.reload();
                            }
                            window.close();
                        },
                        error: function (e) {
                            alert(e.responseText);
                        }
                    });
                }
            });

            $("#btn_app_reject").click(function () {
                var rejectReason = prompt("반려 사유를 입력해 주세요");
                if (rejectReason != null) {
                    $.ajax({
                        type: "POST",
                        url: url,
                        data: {cmd: "REJECT", id: key, rejectReason: rejectReason},
                        success: function (args) {
                            alert("반려되었습니다.");
                            if (window.dialogArguments && window.dialogArguments.self) {
                                window.dialogArguments.self.location.reload();
                            } else if (window.opener) {
                                window.opener.location.reload();
                            }
                            window.close();
                        },
                        error: function (e) {
                            alert(e.responseText);
                        }
                    });
                }
            });

            $('#btn_app_redeploy').click(function () {
                if (confirm("재배포 하시겠습니까?")) {
                    $.ajax({
                        type: "POST",
                        url: url,
                        data: {cmd: "REDEPLOY", id: key},
                        success: function (args) {
                            alert("요청되었습니다.");
                            if (window.dialogArguments && window.dialogArguments.self) {
                                window.dialogArguments.self.location.reload();
                            } else if (window.opener) {
                                window.opener.location.reload();
                            }
                            window.close();
                        },
                        error: function (e) {
                            alert(e.responseText);
                        }
                    });
                }
            });
            
            $("#btn_modify").click(function () {
                if (confirm("수정하시겠습니까?")) {
                    $.ajax({
                        type: "POST",
                        url: url,
                        data: {cmd: "UPDATE", id: key, expectEndDate: $("#expectEndDate").val().replaceAll('-','')},
                        success: function (args) {
                            alert("수정되었습니다.");
                            if (window.dialogArguments && window.dialogArguments.self) {
                                window.dialogArguments.self.location.reload();
                            } else if (window.opener) {
                                window.opener.location.reload();
                            }
                            window.close();
                        },
                        error: function (e) {
                            alert(e.responseText);
                        }
                    });
                }
            });

            $("#btn_close").click(function () {
                window.close();
            });
        });

        function detail(key) {
            $.ajax({
                type: "POST",
                url: url,
                dataType: "json",
                data: {cmd: 'DETAIL', id: key},
                success: function (json) {
                    var data = json;
                    
                    if (data.approvalStatus.code == 'END') {
                    	$('#btn_modify').hide();
                    	$('#expectEndDate').hide();
                    	$('#spExpectEndDate').show();
                    	$('#spExpectEndDate').text(dateFormat(data.expectEndDate));
                    } else {
                    	$('#btn_modify').show();
                    	$('#expectEndDate').show();
                    	$('#spExpectEndDate').hide();
                    }
                    
                    $("#approvalType").text(data.approvalType === 'USER' ? "법인사용자" : "API 사용");
                    $("#approvalStatus").text(data.approvalStatus.description);
                    $("#requesterName").text(data.requester.userName);
                    $("#approvalSubject").text(data.approvalSubject);
                    $("#approvalDetail").html(data.approvalDetail);
                    $("#createdDate").text(data.createdDate).inputmask("9999-99-99 99:99:99.999", {'autoUnmask': true});
                    $("#expectEndDate").val(data.expectEndDate);

                    if (data.approvers.some(approver =>
                        approver.approverStatus === 'CURRENT' &&
                        approver.user.USERID === loginUser
                    )) {
                        document.getElementById("btn_app_approve").style.display = "";
                        document.getElementById("btn_app_reject").style.display = "";
                    } else {
                        document.getElementById("btn_app_approve").style.display = "none";
                        document.getElementById("btn_app_reject").style.display = "none";
                    }

                    if (data.approvalStatus.code === 'FAILED') {
                        document.getElementById("btn_app_redeploy").style.display = "";
                    }

                    var approversHtml = "";
                    data.approvers.sort((a, b) => a.ordinal - b.ordinal);
                    for (var i = 0; i < data.approvers.length; i++) {
                        var approver = data.approvers[i];
                        approversHtml += "<tr>";
                        approversHtml += "<td>" + approver.user.USERNAME + "</td>";
                        approversHtml += "<td>" + approver.approverStatusDescription + "</td>";
                        approversHtml += "<td>" + (approver.approvedDate ? new Date(approver.approvedDate).toLocaleString() : "") + "</td>";
                        approversHtml += "</tr>";
                    }
                    $("#approversTable tbody").html(approversHtml);

                    $("#clientName").text(data.clientName);

                    var apiServiceHtml = "";
                    for (var i = 0; i < data.apiServices.length; i++) {
                        var apiService = data.apiServices[i];
                        apiServiceHtml += "<tr>";
                        apiServiceHtml += "<td>" + apiService.groupName + "</td>";
                        apiServiceHtml += "</tr>";
                    }
                    $("#apiServiceTable tbody").html(apiServiceHtml);

                    var apisHtml = "";

                    for (var i = 0; i < data.apis.length; i++) {
                        var api = data.apis[i];
                        var apiGroupName = data.apiGroupNameList[i];
                        var isNew = false;
                        var isDelete = false;

                        if ((data.requestType === 'MODIFY' || data.requestType === 'PROD_MODIFY') && data.prevApisList && data.prevApisList.length > 0) {
                            isNew = !data.prevApisList.some(prevApi => prevApi.apiId === api.apiId);
                        }

                        if ((data.requestType === 'DELETE' || data.requestType === 'PROD_DELETE') && data.prevApisList && data.prevApisList.lenght > 0) {
                            isDelete = true;
                            isNew = false;
                        }

                        var trClass = "";
                        if (isNew) trClass = "highlight_new";
                        if (isDelete) trClass = "highlight_delete";
                        apisHtml += "<tr " + (trClass ? "class='" + trClass + "'" : "") + ">";
                        apisHtml += "<td>" + apiGroupName + "</td>";
                        apisHtml += "<td>" + api.apiName + "</td>";
                        apisHtml += "<td class='status'>" + (isNew ? "추가" : "") + (isDelete ? "삭제" : "") + "</td>";
                        apisHtml += "</tr>";
                    }

                    if ((data.requestType === 'MODIFY' || data.requestType === 'PROD_MODIFY') && data.prevApisList && data.prevApisList.length > 0) {

                        data.prevApisList.forEach(function(prevApi, index) {
                            var isDeleted = !data.apis.some(api => api.apiId === prevApi.apiId);

                            if (isDeleted) {
                                apisHtml += "<tr class='highlight_delete'>";
                                apisHtml += "<td>" + data.prevApiGroupNameList[index] + "</td>";
                                apisHtml += "<td>" + prevApi.apiName + "</td>";
                                apisHtml += "<td class='status'>삭제</td>";
                                apisHtml += "</tr>";
                            }
                        });
                    }

                    $("#apisTable tbody").html(apisHtml);
                },
                error: function (e) {
                    alert(e.responseText);
                }
            });
        }
    </script>
</head>
<body>
<div class="popup_box">
    <div class="title" id="approvalSubject" style="margin-top: 15px;"></div>
    <%--제목--%>
    <div class="popup_content">
        <table class="table_row" cellspacing="0">
            <tr>
                <th style="width:20%;">승인 유형</th>
                <td style="width:30%;"><span id="approvalType"></span></td>
                <th style="width:20%;">승인 상태</th>
                <td style="width:30%;"><span id="approvalStatus"></span></td>
            </tr>
            <tr>
                <th>요청자</th>
                <td><span id="requesterName"></span></td>
                <th>생성일</th>
                <td><span id="createdDate"></span></td>
            </tr>
            <tr>
                <th>상세 내용</th>
                <td>
                    <div id="approvalDetail" style="white-space: pre-wrap;"></div>
                </td>
                <th>예상완료일</th>
                <td>
                	<input type="text" id="expectEndDate" style="width: 120px; text-align:center"/>
                	<span id="spExpectEndDate"></span>
                </td>
            </tr>
        </table>

        <div class="title">Client 정보</div>
        <table id="client" class="table_row" cellspacing="0">
        	<colgroup>
        		<col style="width:20%"/>
        		<col style="width:80%"/>
        	</colgroup>
            <tr>
                <th style="width:20%;">이름</th>
                <td><span id="clientName"></span></td>
            </tr>
        </table>
        <div class="title">API 목록</div>
        <table id="apisTable" class="table_row" cellspacing="0">
            <thead>
            <tr>
                <th>서비스명</th>
                <th>API 이름</th>
                <th></th>
            </tr>
            </thead>
            <tbody>
            </tbody>
        </table>

        <div class="title">승인자 목록</div>
        <table id="approversTable" class="table_row" cellspacing="0">
            <thead>
            <tr>
                <th>승인자</th>
                <th>상태</th>
                <th>승인/거절 일시</th>
            </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
    <div class="popup_button">
    	<button type="button" class="cssbtn" id="btn_modify" level="W"><i
                class="material-icons">save</i>수정
        </button>
        <button type="button" class="cssbtn" style="display: none;" id="btn_app_approve" level="W"><i
                class="material-icons">check</i>승인
        </button>
        <button type="button" class="cssbtn" style="display: none;" id="btn_app_reject" level="W"><i
                class="material-icons">close</i>반려
        </button>
        <button type="button" class="cssbtn" style="display: none;" id="btn_app_redeploy" level="W"><i
                class="material-icons">close</i>재처리
        </button>
        <button type="button" class="cssbtn" id="btn_close" level="R"><i
                class="material-icons">cancel</i> <%= localeMessage.getString("button.close") %>
        </button>
    </div>
</div>
</body>
</html>
