<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page import="java.io.*"%>
<%@ page import="com.eactive.eai.common.util.SystemUtil"%>
<%@ 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");

	boolean isProdServer = SystemUtil.isProdServer();
%>
<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/portalorg/portalOrgMan.json" />';
var url_view = '<c:url value="/onl/apim/portalorg/portalOrgMan.view" />';
var select_approvalStatus = "";
var select_status = "";
var isProdServer = <%= isProdServer %>;
var gridRowDataMap = {};

function getGridSelectText(key, value, data) {
	if (!Array.isArray(data) || data.length === 0) {
        return "";
    }

    return data
        .filter(item => item[key] !== undefined && item[value] !== undefined)
        .map(item => String(item[key]) + ":" + String(item[value]))
        .join(';');
}

function formatCompanyRegNo(text) {
    if (!text) return "";
    return text.replace(/(\d{3})(\d{2})(\d{5})/, "$1-$2-$3");
}

/* 선택된 법인 삭제 - 상태에 따라 Soft/Hard Delete 자동 분기 */
function deleteSelectedOrgs() {
	var selectedIds = $("#grid").jqGrid('getGridParam', 'selarrrow');

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

	// 선택된 항목을 REMOVED / 비REMOVED로 분류
	var softDeleteIds = [];
	var hardDeleteIds = [];
	for (var i = 0; i < selectedIds.length; i++) {
		var rowRaw = gridRowDataMap[selectedIds[i]];
		if (rowRaw && rowRaw.orgStatus === 'REMOVED') {
			hardDeleteIds.push(selectedIds[i]);
		} else {
			softDeleteIds.push(selectedIds[i]);
		}
	}

	// 비운영 환경이 아니면 Hard Delete 불가
	if (isProdServer && hardDeleteIds.length > 0) {
		showAlert("운영 환경에서는 삭제(탈퇴) 상태인 항목을 완전삭제할 수 없습니다.", {type: 'error'});
		return;
	}

	var messages = [];
	if (softDeleteIds.length > 0) messages.push(softDeleteIds.length + "개 삭제(탈퇴 처리)");
	if (hardDeleteIds.length > 0) messages.push(hardDeleteIds.length + "개 완전삭제(DB 영구 삭제)");

	var confirmMsg = "선택된 법인: " + messages.join(", ") + "\n진행하시겠습니까?";
	var confirmType = hardDeleteIds.length > 0 ? 'error' : 'warning';

	showConfirm(confirmMsg, {
		type: confirmType,
		onConfirm: function() {
			var confirmAndExecute = function() {
				var completed = 0;
				var total = (softDeleteIds.length > 0 ? 1 : 0) + (hardDeleteIds.length > 0 ? 1 : 0);
				var resultMessages = [];
				var hasError = false;

				function checkDone() {
					completed++;
					if (completed >= total) {
						var finalType = hasError ? 'error' : 'success';
						showAlert(resultMessages.join("\n"), {type: finalType, onClose: function() {
							$("#grid").trigger("reloadGrid");
						}});
					}
				}

				if (softDeleteIds.length > 0) {
					$.ajax({
						type: "POST", url: url, dataType: "json",
						data: { cmd: 'DELETE_MULTIPLE', ids: softDeleteIds.join(',') },
						success: function(data) {
							resultMessages.push(data.message);
							if (data.status !== "success") hasError = true;
							checkDone();
						},
						error: function(e) { hasError = true; resultMessages.push("삭제 오류: " + e.responseText); checkDone(); }
					});
				}

				if (hardDeleteIds.length > 0) {
					$.ajax({
						type: "POST", url: url, dataType: "json",
						data: { cmd: 'HARD_DELETE_MULTIPLE', ids: hardDeleteIds.join(',') },
						success: function(data) {
							resultMessages.push(data.message);
							if (data.status !== "success") hasError = true;
							checkDone();
						},
						error: function(e) { hasError = true; resultMessages.push("완전삭제 오류: " + e.responseText); checkDone(); }
					});
				}
			};

			// Hard Delete 포함 시 2차 확인
			if (hardDeleteIds.length > 0) {
				showConfirm("최종 확인: 완전삭제는 되돌릴 수 없습니다. 정말로 실행하시겠습니까?", {
					type: 'error',
					title: '최종 확인',
					onConfirm: confirmAndExecute
				});
			} else {
				confirmAndExecute();
			}
		}
	});
}

function init(){
	$.ajax({
		type : "POST",
		url:url,
		dataType:"json",
		data:{cmd: 'LIST_INIT_COMBO'},
		success:function(json){

			const comboConfigs = [
				{name: 'searchOrgStatus', data: json.orgStatusRows },
				{name: 'searchApprovalStatus', data: json.approvalStatusRows },
			];

			comboConfigs.forEach(function(config)  {
				new makeOptions("CODE","NAME")
						.setObj($("select[name=" + config.name + "]"))
						.setNoValueInclude(true)
						.setNoValue("", "<%=localeMessage.getString("combo.all")%>")
						.setData(config.data)
						.setFormat(nameOptionFormat).rendering();
			});

			putSelectFromParam();

			select_approvalStatus  = ": ;" + getGridSelectText("CODE", "NAME",	json.approvalStatusRows);
			select_status = ": ;" + getGridSelectText("CODE", "NAME",	json.orgStatusRows);

			initializeGrid();
		},
		error:function(e){
			alert(e.responseText);
		}
	});
}

function initializeGrid() {
	var gridPostData = getSearchForJqgrid("cmd","LIST"); //jqgrid에서는 object 로

	$('#grid').jqGrid({
		datatype:"json",
		mtype: 'POST',
		url: url,
		postData : gridPostData,
		colNames:['No.',
                  "id",
                  '<%= localeMessage.getString("portalOrg.orgName") %>',
                  '<%= localeMessage.getString("portalOrg.orgCode") %>',
                  '<%= localeMessage.getString("portalOrg.compRegNo") %>',
                  '<%= localeMessage.getString("portalUser.createOn") %>',
                  '<%= localeMessage.getString("portalOrg.orgStatus") %>',
                  '<%= localeMessage.getString("portalUser.approvalStatus") %>'
                  ],
		colModel:[
				{ name : 'rowNum'   	 , align:'center'	, width:'30', sortable:false  },
				{ name : 'id'  			 , align:'center'	, key:true, hidden:true},
				{ name : 'orgName'		 , align:'center'	, width:"80"},
				{ name : 'orgCode'		 , align:'center'	, width:"80"},
				{ name : 'compRegNo' 	 , align:'center' 	, formatter:formatCompanyRegNo },
				{ name : 'createdDate'	 , align:'center'	, width:"90", formatter: timeStampFormat },
				{ name : 'orgStatus'   	 , align:'center'	, width:'60',editoptions: { value: select_status }, formatter: "select"},
				{ name : 'approvalStatus' , align:'center'	, width:"60", edittype: 'select' , editoptions: { value: select_approvalStatus }, formatter: "select"}
			],
        jsonReader: {
             repeatitems:false
        },
		pager : $('#pager'),
		page : '${param.page}',
		rowNum : '${rmsDefaultRowNum}',
	    autoheight: true,
	    height: $("#container").height(),
		autowidth: true,
		viewrecords: true,
		rowList : eval('[${rmsDefaultRowList}]'),
		multiselect: true,
		multiboxonly: true,
		loadComplete:function (d){
			var records = $(this).getGridParam('records');
			var page = $(this).getGridParam('page');
			var rowNum = $(this).getGridParam('rowNum');
			var rows = $(this).getDataIDs();
			var colModel = $(this).getGridParam("colModel");

			for (var i = 0; i < rows.length; i++) {
				var number = ((page - 1) * rowNum + i) + 1;
				$(this).setCell(rows[i], 'rowNum', number);
			}
			for(var i = 0 ; i< colModel.length; i++){
				$(this).setColProp(colModel[i].name, {sortable : false});
			}

			// 원본 행 데이터 맵 구성 및 REMOVED 행 스타일링
			if (d && d.rows) {
				gridRowDataMap = {};
				for (var j = 0; j < d.rows.length; j++) {
					gridRowDataMap[d.rows[j].id] = d.rows[j];
					if (!isProdServer && d.rows[j].orgStatus === 'REMOVED') {
						$('#grid tr#' + $.jgrid.jqID(d.rows[j].id)).css({
							'background-color': '#f8d7da',
							'text-decoration': 'line-through',
							'opacity': '0.7'
						});
					}
				}
			}
		},
		ondblClickRow: function(rowId) {
			var rowData = $(this).getRowData(rowId);
		    var key = rowData['id'];

			var args = {};
			var url2 = url_view;
			url2 += '?cmd=DETAIL';
			url2 += '&page='+$(this).getGridParam("page");
			url2 += '&returnUrl='+getReturnUrl();
			url2 += '&menuId='+'${param.menuId}';
		    url2 += '&id=' + key;
			goNav(url2);
        },loadError: function (jqXHR, textStatus, errorThrown) {
        		if(jqXHR.status == 401) {
	        		var location ='<%=request.getContextPath()%>/';
		        	comloadError(jqXHR, textStatus, errorThrown ,location);
		    	}
    	}
	});

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


$(document).ready(function() {
	$("input[name=searchStartYYYYMMDD],input[name=searchEndYYYYMMDD]").inputmask("yyyy-mm-dd",{'autoUnmask':true});

	init();

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

	$("#btn_new").click(function(){
		var url2 = url_view;
		url2 += '?cmd=DETAIL';
		url2 += '&page='+$("#grid").getGridParam("page");
		url2 += '&returnUrl='+getReturnUrl();
		url2 += '&menuId='+'${param.menuId}';
		goNav(url2);
	});

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

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

	$("#startDatepicker").datepicker();
	$("#endDatepicker").datepicker();

	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">
			<button type="button" class="cssbtn" id="btn_new" level="W"><i class="material-icons">add</i> <%= localeMessage.getString("button.new") %></button>
			<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"><%= localeMessage.getString("portalOrg.title") %></div>
		<% if (!isProdServer) { %>
		<div style="background:#fff3cd; border:1px solid #ffc107; padding:8px 15px; margin:5px 0; border-radius:4px; color:#856404;">
			<strong>[비운영 환경]</strong> 삭제된(탈퇴) 데이터가 포함되어 표시됩니다. 탈퇴 상태 항목 선택 시 DB에서 영구 삭제됩니다.
		</div>
		<% } %>

		<table class="search_condition" cellspacing=0;>
			<tbody>
				<tr>
					<th style="width:10%;"><%= localeMessage.getString("portalOrg.orgName") %></th>
					<td style="width:15%;">
						<input type="text" name="searchOrgName" value="${param.searchOrgName}">
					</td>

					<th style="width:10%;"><%= localeMessage.getString("portalOrg.compRegNo") %></th>
					<td style="width:15%;">
						<input type="text" name="searchOrgCompRegNo" value="${param.searchOrgCompRegNo}">
					</td>

					<th  style="width:10%;"><%= localeMessage.getString("portalOrg.orgStatus") %></th>
					<td style="width:15%;">
						<div class="select-style">
							<select type="text" name="searchOrgStatus" value="${param.searchOrgStatus}"></select>
						</div>
					</td>

					<th style="width:10%;"><%= localeMessage.getString("portalUser.approvalStatus") %></th>
					<td style="width:15%;">
						<div class="select-style">
							<select type="text" name="searchApprovalStatus" value="${param.searchApprovalStatus}"></select>
						</div>
					</td>
				</tr>
			</tbody>
		</table>

		<table id="grid" ></table>
		<div id="pager"></div>
	  </div><!-- end content_middle -->
	</div><!-- end right_box -->
  </body>
</html>
