<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page import="java.io.*"%>
<%@ 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"/>
    <script language="javascript" >
      var url      = '<c:url value="/onl/apim/approval/portalApprovalMan.json" />';
      var url_view = '<c:url value="/onl/apim/approval/portalApprovalMan.view" />';
      var hardDeleteEnabled = ${hardDeleteEnabled};
      const APPROVAL_TYPE_DISPLAY = {
          'USER': '법인사용자',
          'APP': 'API 사용'
      };
      
      function dateFormat(cellvalue, options, rowObject) {
    		if ( cellvalue == null || cellvalue.length < 8 )
    			return '';
    		return  cellvalue.substr(0 ,4) + '-' +
    				cellvalue.substr(4, 2) + '-' +
    				cellvalue.substr(6, 2) ;
    	}

      function deleteSelectedApprovals() {
        var selectedIds = $("#grid").jqGrid('getGridParam', 'selarrrow');

        if (selectedIds.length === 0) {
          showAlert("삭제할 승인 요청을 선택해주세요.", {type: 'warning'});
          return;
        }

        if (!hardDeleteEnabled) {
          showAlert("완전삭제 기능이 비활성화되어 있습니다.", {type: 'error'});
          return;
        }

        var confirmMsg = "선택된 " + selectedIds.length + "건을 완전삭제(DB 영구 삭제)하시겠습니까?";
        showConfirm(confirmMsg, {
          type: 'error',
          onConfirm: function() {
            showConfirm("최종 확인: 완전삭제는 되돌릴 수 없습니다. 정말 실행하시겠습니까?", {
              type: 'error',
              title: '최종 확인',
              onConfirm: function() {
                $.ajax({
                  type: "POST", url: url, dataType: "json",
                  data: { cmd: 'HARD_DELETE_MULTIPLE', ids: selectedIds.join(',') },
                  success: function(data) {
                    showAlert(data.message, {
                      type: data.status === 'success' ? 'success' : 'error',
                      onClose: function() { $("#grid").trigger("reloadGrid"); }
                    });
                  },
                  error: function(e) {
                    showAlert("완전삭제 오류: " + e.responseText, {type: 'error'});
                  }
                });
              }
            });
          }
        });
      }

      $(document).ready(function() {
        $('#grid').jqGrid({
          datatype: "json",
          mtype: 'POST',
          url: url,
          postData: {
            cmd: 'LIST',
            searchApprovalType: $('select[name=searchApprovalType]').val(),
            searchApprovalStatus: $('select[name=searchApprovalStatus]').val(),
            searchApprovalSubject: $('input[name=searchApprovalSubject]').val()
          },
          colNames: ['No.', 'id',  '제목',  '승인 유형', '승인 유형', '승인 상태','요청자', '생성일', '예상완료일'],
          colModel: [
            { name: 'rowNum', align: 'center', width: '30', sortable: false},
            { name: 'id', align: 'center', key: true, hidden: true },
            { name: 'approvalSubject', align: 'center', width: 200 },
            { name: 'approvalType', align: 'center', width: 80, formatter: function(cellvalue) { return APPROVAL_TYPE_DISPLAY[cellvalue] || cellvalue;}},
            { name: 'approvalType', align: 'center', width: 80, hidden: true},
            { name: 'approvalStatus.description', align: 'center', width: 80 },
            { name: 'requester.userName', align: 'center', width: 100 },
            { name: 'createdDate', align: 'center', width: 120, formatter: 'date', formatoptions: { srcformat: 'ISO8601Long', newformat: 'Y-m-d H:i:s' } },
            { name: 'expectEndDate', align: 'center', width: 100, formatter: dateFormat},
          ],
          jsonReader: {
            repeatitems: false
          },
          pager: $('#pager'),
          rowNum: '${rmsDefaultRowNum}',
          rowList: eval('[${rmsDefaultRowList}]'),
          viewrecords: true,
          autowidth: true,
          height: 'auto',
          multiselect: true,
          multiboxonly: true,
          ondblClickRow: function(rowId) {
            var rowData = $(this).getRowData(rowId);
            var id = rowData['id'];
            var approvalType = rowData['approvalType'];
            var args = {};
            var url2 = url_view;
            url2 += '?cmd=DETAIL';
            url2 += '&menuId=' + '${param.menuId}';
            url2 += '&type=' + approvalType;
            url2 += '&id=' + id;

            showModal(url2, args, 800, 650, function(){
              $("#grid").trigger("reloadGrid");
            });
          },
          loadComplete: function(d) {
            var records = $(this).getGridParam('records');
            var page = $(this).getGridParam('page');
            var rowNum = $(this).getGridParam('rowNum');
            var rows = $(this).getDataIDs();

            for (var i = 0; i < rows.length; i++) {
                var number = ((page - 1) * rowNum + i) + 1;
                // var reverseNumber = records - ((page - 1) * rowNum + i);
                $(this).setCell(rows[i], 'rowNum', number);
            }

            // 승인 상태별 행 배경색: 요청됨(#fff3cd) / 진행중(#d1ecf1) 강조
            if (d && d.rows) {
                for (var j = 0; j < d.rows.length; j++) {
                    var st = d.rows[j].approvalStatus || {};
                    var code = st.code || '';
                    var desc = st.description || '';
                    var bg = '';
                    if (code === 'REQUESTED' || desc === '요청됨') {
                        bg = '#fff3cd';
                    } else if (code === 'PROCESSING' || desc === '진행중') {
                        bg = '#d1ecf1';
                    }
                    if (bg) {
                        $('#grid tr#' + $.jgrid.jqID(d.rows[j].id)).css('background-color', bg);
                    }
                }
            }
          },
          loadError: function(jqXHR, textStatus, errorThrown) {
            var location = '<%=request.getContextPath()%>/';
            comloadError(jqXHR, textStatus, errorThrown, location);
          }
        });

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

        $("#btn_search").click(function() {
          var postData = getSearchForJqgrid("cmd", "LIST");
          $("#grid").setGridParam({ url: url, postData: postData, page: 1 }).trigger("reloadGrid");
        });

        $("#btn_delete_selected").click(function() {
          deleteSelectedApprovals();
        });

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

        buttonControl();
      });
    </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">
            <c:if test="${hardDeleteEnabled}">
                <button type="button" class="cssbtn" id="btn_delete_selected" level="W" style="background-color: #dc3545; border-color: #dc3545; color: white;"><i class="material-icons">delete_forever</i> 선택 삭제</button>
            </c:if>
            <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">승인 요청 목록<span class="tooltip">승인 요청을 관리합니다.</span></div>
        <c:if test="${hardDeleteEnabled}">
            <div style="background:#fff3cd; border:1px solid #ffc107; padding:8px 15px; margin:5px 0; border-radius:4px; color:#856404;">
                <strong>[주의]</strong> 삭제 기능은 <strong>개발(dev) 환경에서만</strong> 동작합니다. 선택 삭제 시 승인 요청과 승인자 이력이 DB에서 영구 삭제됩니다.
            </div>
        </c:if>
        <form id="ajaxForm" onsubmit="return false;">
            <table class="search_condition" cellspacing="0">
                <tbody>
                <tr>
                    <th style="width:10%;">승인 유형</th>
                    <td style="width:15%;">
                        <div class="select-style">
                            <select name="searchApprovalType">
                                <option value="">전체</option>
                                <option value="APP">API 사용</option>
                                <option value="USER">법인사용자</option>
                            </select>
                        </div>
                    </td>
                    <th style="width:10%;">승인 상태</th>
                    <td style="width:15%;">
                        <div class="select-style">
                            <select name="searchApprovalStatus">
                                <option value="">전체</option>
                                <option value="REQUESTED">요청됨</option>
                                <option value="PROCESSING">진행중</option>
                                <option value="DENIED">반려됨</option>
                                <option value="END">승인됨</option>
                            </select>
                        </div>
                    </td>
                    <th style="width:10%;">제목</th>
                    <td><input type="text" name="searchApprovalSubject" value="${param.searchApprovalSubject}"></td>
                </tr>
                </tbody>
            </table>
        </form>
        <table id="grid"></table>
        <div id="pager"></div>
    </div><!-- end content_middle -->
</div><!-- end right_box -->
</body>
</html>
