<%@ page import="com.eactive.eai.rms.common.datasource.DataSourceTypeManager" %>
<%@ page import="com.eactive.eai.rms.common.login.LoginVo" %>
<%@ page import="com.eactive.eai.rms.common.util.CommonConstants" %>
<%@ 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>
    <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/portal.jsp"/>
    <!-- 마스킹 해제 관련 스타일 추가 -->
    <style>
        .cssbtn.active {
            background-color: #f0f0f0;
            color: #666;
        }
        .alert {
            padding: 10px 15px;
            margin-bottom: 15px;
            border: 1px solid transparent;
            border-radius: 4px;
            display: flex;
            align-items: center;
        }
        .alert-warning {
            color: #856404;
            background-color: #fff3cd;
            border-color: #ffeeba;
        }
        .alert i {
            margin-right: 8px;
        }
        .unmasked-field {
            background-color: #fff3cd;
            color: #856404;
            padding: 2px 5px;
            border-radius: 3px;
        }
    </style>
    <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" />';
      var file_download = '<c:url value="/file/download.do" />';
      $(document).ready(function() {
        var key = "${param.id}";
        if (key) {
          detail(key);
        }

          $("#btn_unmask").click(function() {
              var status = $(this).attr("status");
              if(status === "DETAIL") {
                  var reason = prompt("마스킹 해제 사유를 입력해 주세요");
                  if (reason) {
                      $.ajax({
                          type: "POST",
                          url: url,
                          data: {
                              cmd: "UNMASK",
                              id: key,
                              reason: reason
                          },
                          success: function(data) {
                              // UI 업데이트
                              updateDetailView(data);
                              // 버튼 상태 변경
                              $("#btn_unmask").hide();

                              // 마스킹 해제 상태 표시
                              $(".popup_content").prepend(
                                  '<div class="alert alert-warning" id="unmask-alert">' +
                                  '<i class="material-icons">warning</i> ' +
                                  '현재 마스킹 해제된 상태로 조회중입니다' +
                                  '</div>'
                              );
                          },
                          error: function(e) {
                              alert(e.responseText);
                          }
                      });
                  }
              } else {
                  // 마스킹 보기로 되돌리기
                  detail(key);
                  $(this)
                      .attr("status", "DETAIL")
                      .html('<i class="material-icons">lock_open</i> 마스킹해제')
                      .removeClass('active');  // 활성화 상태 클래스 제거

                  // 마스킹 해제 상태 알림 제거
                  $("#unmask-alert").remove();
              }
          });

        $("#btn_user_approve").click(function() {
          if (confirm("승인하시겠습니까?")) {
            $.ajax({
              type: "POST",
              url: url,
              data: {cmd: "APPROVE", 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_user_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_user_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_close").click(function() {
          window.close();
        });
      });

      function downloadFile(fileId, fileSn) {
        window.location.href = file_download + '?fileId=' + fileId + '&fileSn=' + fileSn;
      }

      function detail(key) {
        $.ajax({
          type: "POST",
          url: url,
          dataType: "json",
          data: {cmd: 'DETAIL', id: key},
          success: function(json) {
            var data = json;
            $("#approvalType").text(data.approvalType === 'USER' ? "법인사용자" : "API 사용");
            $("#approvalStatus").text(data.approvalStatus.description);
            $("#requesterName").text(data.requester.userName);
            $("#approvalSubject").text(data.approvalSubject);
            $("#createdDate").text(data.createdDate).inputmask("9999-99-99 99:99:99", {'autoUnmask': true});

            // 상세 내용이 있을 때만 tr 표시
            if (data.approvalDetail && $.trim(data.approvalDetail)) {
              $("#approvalDetail").html(data.approvalDetail);
              $("#approvalDetailRow").show();
            } else {
              $("#approvalDetailRow").hide();
            }

            data.approvers.sort((a, b) => a.ordinal - b.ordinal);
            var approversHtml = "";
            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);

            // Display Portal User details
            var portalUser = data.portalUser;
            $("#loginId").text(portalUser.loginId);
            $("#userName").text(portalUser.userName);
            $("#mobileNumber").text(portalUser.mobileNumber);
            $("#userStatusDescription").text(portalUser.userStatusDescription);
            $("#roleCodeDescription").text(portalUser.roleCodeDescription);
            if (data.approvers.some(approver =>
                approver.approverStatus === 'CURRENT' &&
                approver.user.USERID === loginUser
            )) {
              document.getElementById("btn_user_approve").style.display = "";
              document.getElementById("btn_user_reject").style.display = "";
            } else {
              document.getElementById("btn_user_approve").style.display = "none";
              document.getElementById("btn_user_reject").style.display = "none";
            }

            if (data.approvalStatus.description === '배포실패'){
              document.getElementById("btn_user_redeploy").style.display = "";
            }

            // Display Portal Org details
            var portalOrg = portalUser.portalOrgUIs;
            $("#orgName").text(portalOrg.orgName);
            $("#orgStatusDescription").text(portalOrg.orgStatusDescription);
            $("#serviceName").text(portalOrg.serviceName);
            $("#corpRegNo").text(formatCorpRegNo(portalOrg.corpRegNo));
            $("#compRegNo").text(formatCompanyRegNo(portalOrg.compRegNo));

            $("#scPhoneNumber").text(portalOrg.scPhoneNumber); // 고객센터 전화번호
            $("#orgPhoneNumber").text(portalOrg.orgPhoneNumber); // 회사 전화번호
            $("#ceoName").text(portalOrg.ceoName); // 대표자 성명
            $("#orgIndustryType").text(portalOrg.orgIndustryType || ""); // 업종
            $("#orgAddr").text(portalOrg.orgAddr); // 소재지
            $("#orgSectors").text(portalOrg.orgSectors || ""); // 업태
            $("#orgCode").text(portalOrg.orgCode);
            $("#ipWhitelist").text(portalOrg.ipWhitelist || "");

            if (portalOrg.compRegFile) {
              $("#fileName").text(portalOrg.fileName);
              if (portalOrg.fileName) {
                $("#fileWrapper").show().off('click').on('click', function() {
                  downloadFile(portalOrg.compRegFile, '1');  // fileSn은 단일 파일이므로 '1'로 고정
                });
                $("#compRegFile").val(portalOrg.compRegFile);
              } else {
                $("#fileWrapper").hide();
              }
            } else {
              $("#fileName").text("");
              $("#fileWrapper").hide();
            }
          },
          error: function(e) {
            alert(e.responseText);
          }
        });
      }
      function updateDetailView(data) {
          $("#approvalType").text(data.approvalType === 'USER' ? "법인사용자" : "API 사용");
          $("#approvalStatus").text(data.approvalStatus.description);
          $("#requesterName").text(data.requester.userName);
          $("#approvalSubject").text(data.approvalSubject);
          $("#createdDate").text(data.createdDate).inputmask("9999-99-99 99:99:99", {'autoUnmask': true});

          // 상세 내용이 있을 때만 tr 표시
          if (data.approvalDetail && $.trim(data.approvalDetail)) {
              $("#approvalDetail").html(data.approvalDetail);
              $("#approvalDetailRow").show();
          } else {
              $("#approvalDetailRow").hide();
          }

          // 승인자 목록 업데이트
          updateApprovers(data.approvers);

          // 사용자 정보 업데이트
          var portalUser = data.portalUser;
          $("#loginId").text(portalUser.loginId);
          $("#userName").text(portalUser.userName);
          $("#mobileNumber").text(portalUser.mobileNumber);
          $("#userStatusDescription").text(portalUser.userStatusDescription);
          $("#roleCodeDescription").text(portalUser.roleCodeDescription);

          // 법인 정보 업데이트
          var portalOrg = portalUser.portalOrgUIs;
          updateOrgInfo(portalOrg);

          // 마스킹 상태에 따라 데이터를 다르게 표시
          var isMasked = $("#btn_unmask").attr("status") === "DETAIL";

          // 마스킹 해제 상태일 때 스타일 변경
          if (!isMasked) {
              // 마스킹 해제된 필드들 하이라이트
              $("#userName, #loginId, #mobileNumber, #ipWhitelist").addClass("unmasked-field");

              // 마스킹 해제 상태 알림 표시
              if (!$("#unmask-alert").length) {
                  $(".popup_content").prepend(
                      '<div class="alert alert-warning" id="unmask-alert">' +
                      '<i class="material-icons">warning</i> ' +
                      '현재 마스킹 해제된 상태로 조회중입니다' +
                      '</div>'
                  );
              }
          } else {
              // 마스킹된 상태로 되돌리기
              $(".unmasked-field").removeClass("unmasked-field");
              $("#unmask-alert").remove();
          }
      }

      function updateApprovers(approvers) {
          var approversHtml = "";
          approvers.sort((a, b) => a.ordinal - b.ordinal);
          for (var i = 0; i < approvers.length; i++) {
              var approver = 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);
      }

      // 법인 정보 업데이트 함수
      function updateOrgInfo(portalOrg) {
          $("#orgName").text(portalOrg.orgName);
          $("#orgStatusDescription").text(portalOrg.orgStatusDescription);
          $("#serviceName").text(portalOrg.serviceName);
          $("#corpRegNo").text(formatCorpRegNo(portalOrg.corpRegNo));
          $("#compRegNo").text(formatCompanyRegNo(portalOrg.compRegNo));
          $("#scPhoneNumber").text(portalOrg.scPhoneNumber);
          $("#orgPhoneNumber").text(portalOrg.orgPhoneNumber);
          $("#ceoName").text(portalOrg.ceoName);
          $("#orgIndustryType").text(portalOrg.orgIndustryType || "");
          $("#orgAddr").text(portalOrg.orgAddr);
          $("#orgSectors").text(portalOrg.orgSectors || "");
          $("#orgCode").text(portalOrg.orgCode);
          $("#ipWhitelist").text(portalOrg.ipWhitelist || "");
      }
    </script>
</head>
<body>
<div class="popup_box">
    <div class="title" id="approvalSubject" style="margin-top: 15px;"></div>

    <div class="search_wrap">
        <button type="button" class="cssbtn" id="btn_unmask" level="W" status="DETAIL"><i class="material-icons">lock_open</i> 마스킹해제</button>
    </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 id="requesterName"></td>
                <th>생성일</th>
                <td id="createdDate"></td>
            </tr>
            <tr id="approvalDetailRow">
                <th>상세 내용</th>
                <td colspan="3">
                    <div id="approvalDetail" style="white-space: pre-wrap;"></div>
                </td>
            </tr>
        </table>

        <div class="title">사용자 정보</div>
        <table class="table_row" cellspacing="0">
        	<colgroup>
        		<col style="width:20%"/>
        		<col style="width:30%"/>
        		<col style="width:20%"/>
        		<col style="width:30%"/>
        	</colgroup>
            <tr>
                <th>이메일 아이디</th>
                <td colspan="3"><span id="loginId"></span></td>
            </tr>
            <tr>
                <th>이름</th>
                <td><span id="userName"></span></td>
                <th>권한</th>
                <td><span id="roleCodeDescription"></span></td>
            </tr>
            <tr>
                <th>핸드폰 번호</th>
                <td><span id="mobileNumber"></span></td>
                <th>사용자 상태</th>
                <td><span id="userStatusDescription"></span></td>
            </tr>
        </table>

        <div class="title">법인 정보</div>
        <table class="table_row" cellspacing="0">
            <tr>
                <th style="width:20%;">법인명</th>
                <td style="width:30%;"><span id="orgName"></span></td>
                <th style="width:20%;">법인 상태</th>
                <td style="width:30%;"><span id="orgStatusDescription"></span></td>
            </tr>
            <tr>
                <th>제휴기관코드</th>
                <td><span id="orgCode"></span></td>
                <th>업태</th>
                <td><span id="orgSectors"></span></td>
            </tr>
            <tr>
                <th>서비스명</th>
                <td><span id="serviceName"></span></td>
                <th>업종</th>
                <td><span id="orgIndustryType"></span></td>
            </tr>
            <tr>
                <th>법인 등록 번호</th>
                <td><span id="corpRegNo"></span></td>
                <th>사업자 등록 번호</th>
                <td><span id="compRegNo"></span></td>
            </tr>
            <tr>
                <th>회사 전화번호</th>
                <td><span id="orgPhoneNumber"></span></td>
                <th>고객 센터 전화번호</th>
                <td><span id="scPhoneNumber"></span></td>
            </tr>
            <tr>
                <th>대표자 성명</th>
                <td><span id="ceoName"></span></td>
                <th>소재지</th>
                <td><span id="orgAddr"></span></td>
            </tr>
            <tr>
                <th>사업자 등록증</th>
                <td colspan="3">
                    <span id="fileWrapper" style="display: none; cursor: pointer;">
                        <img src="${pageContext.request.contextPath}/images/icon_file.png" style="vertical-align: middle; margin-right: 5px;">
                        <span id="fileName" style="text-decoration: underline;"></span>
                        <input type="hidden" id="compRegFile"/>
                    </span>
                </td>
            </tr>
            <tr>
                <th>사용 서버 IP 대역</th>
                <td colspan="3"><span id="ipWhitelist"></span></td>
            </tr>
        </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" style="display: none;" id="btn_user_approve" level="W"><i class="material-icons">check</i>승인</button>
        <button type="button" class="cssbtn" style="display: none;" id="btn_user_reject" level="W"><i class="material-icons">close</i>반려</button>
        <button type="button" class="cssbtn" style="display: none;" id="btn_user_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>
