<%@ 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/approvalline/portalApprovalLineMan.json" />';
var url_view = '<c:url value="/onl/apim/approvalline/portalApprovalLineMan.view" />';
var isDetail = false;
var globalVars = {
		approverList: [],
		usedApprovalTypes: [],
	    originalApprovalType: null,
	    originalApproverList: []
	};
	
function init (callback){
	$.ajax({  
		type : "POST",
		url:url,
		dataType:"json",
		data:{	cmd: 'INIT_COMBO'	},
		success:function(json){
			new makeOptions("CODE","NAME").setObj($("select[name=approvalType]"))
			.setData(json.approvalTypeRows).setFormat(nameOptionFormat).rendering();
			
			globalVars.usedApprovalTypes = json.usedApprovalTypes || [];
			
			if(typeof callback === 'function') {
				callback();
			}
		},
		error:function(e){
			alert(e.responseText);
		}
	});
} 

function detail(key){
	$.ajax({  
		type : "POST",
		url:url,
		dataType:"json",
		data:{cmd: 'DETAIL',		id: key},
		success:function(data){
			$("#ajaxForm input[type!=radio],#ajaxForm select,#ajaxForm textarea").each(function(){
				var name = $(this).attr("name");
				var tag  = $(this).prop("tagName").toLowerCase();
				$(tag+"[name="+name+"]").val(data[name]);
			});

			$("select[name=approvalType]").val(data.approvalType).prop("selected", true);
			
			globalVars.originalApprovalType = data.approvalType;
			
			if (Array.isArray(data.portalApprovalLineUsers)) {
                globalVars.approverList = data.portalApprovalLineUsers.map(user => ({
                    userId: user.userId,
                    name: user.userName 
                }));
                
                globalVars.originalApproverList = JSON.parse(JSON.stringify(globalVars.approverList));
                generateUser($("#approverList"));
			}
		},
		error:function(e){
			alert(e.responseText);
		}
	});

}

function searchUser() {
    $("#gridUser").setGridParam({
    	postData: {
    		cmd: 'SEARCH_USER', 
   			username: $('#searchUserValue').val()
    	}, 
    	datatype: 'json'
    }).trigger('reloadGrid', [{page: 1}]);
    
}
function addUser(id, name) {
	var exists = globalVars.approverList.some(function(u){
		return u.id === id;
	});
    if(!exists){
        globalVars.approverList.push({
        	userId: id,
        	name: name
       	});
        generateUser($("#approverList"));
        $("#noApproverMsg").hide();
    } else {
    	alert("이미 추가된 승인자입니다.");
    }
}

function generateUser($selector) {
	$selector.empty();
	
	if (globalVars.approverList.length === 0){
        $("#noApproverMsg").show();
	} else {
		$("#noApproverMsg").hide();
		var $table = $('<table>').addClass('table_row');
        
		globalVars.approverList.forEach(function(user, idx){
			var $tr = $('<tr>').data('userId', user.userId);
            var $td = $('<td>').css({
                'display': 'flex',
                'justify-content': 'space-between',
                'align-items': 'center',
                'padding': '0 5px'
            });
            
            var $span = $('<span>').text((idx + 1) + '. ' + user.name);
            
            var $delBtn = $("<button>").attr({
                class: "cssbtn smallBtn",
                type: "button"
            }).text("선택취소").css({
                'margin-left': 'auto'
            }).click(function() {
                globalVars.approverList.splice(idx, 1);
                generateUser($selector);
            });
            
            $td.append($span).append($delBtn);
            $tr.append($td);
            $table.append($tr);
        });
		
		$selector.append($table);
		
		// 드래그 앤 드롭 기능 초기화
        $table.sortable({
            items: 'tr',
            cursor: 'move',
            update: function(event, ui) {
                globalVars.approverList = $table.find('tr').map(function(idx,element) {
                	var name = $(element).find('span').text().split('. ')[1];
                    $(element).find('span').text((idx + 1) + '. ' + name);

                    return {
                        userId: $(element).data('userId'),
                        name: name, 
                    	approvalOrder: idx + 1
                    };
                }).get();
                
                updateApprovalUserList();
            }
        });
    }
    updateApprovalUserList();
}
	
function updateApprovalUserList() {
	globalVars.approverList.forEach((user, idx) => {
		user.approvalOrder = idx + 1; // 순서를 idx+1로 설정
	});
	
    var approvalUserList = globalVars.approverList.map(user => user.name).join(' → ');
    $('input[name=portalApprovalLineUsers]').val(approvalUserList);
    
    $('#portalApprovalLineUsersJson').val(JSON.stringify(globalVars.approverList));
    console.log("Updated list:", approvalUserList); 
    console.log("Current approverList with order:", globalVars.approverList);
}

$(document).ready(function() {	
	var key ="${param.id}";
	isDetail = key != "" && key != "null";
	
	if (isDetail){
		$("#title").append(" 수정");
		buttonControl(true);
	} else {
		$("#title").append(" 등록");
		$("#btn_modify").html('<i class="material-icons">save</i> <%= localeMessage.getString("button.register") %>');
		buttonControl(false);
	}
	
	init(function(){
        if (isDetail) {
            detail(key);
        }
	});
	
	$("#gridUser").jqGrid({
        datatype: 'json', 
		mtype:'POST', 
		url: url, 
		postData: { cmd: 'SEARCH_USER', username: '' },
		colNames: ["사용자 ID", "사용자 이름"],
        colModel: [
            { name: 'USERID', index: '사용자 ID', key: true , width: 200, align:'center'},
            { name: 'USERNAME', index: '사용자 이름' , width: 200, align:'center'}
        ],
        viewrecords: true,
        height: 'auto',
        rowNum: 10,
        pager: '#pagerUser',
        jsonReader: {
            root: "rows",
            page: "page",
            total: "total",
            records: "records",
            repeatitems: false,
            id: "USERID"
        },
        ondblClickRow: function(rowid, iRow, iCol, e) {
            var rowData = $(this).getRowData(rowid);
            addUser(rowData.USERID, rowData.USERNAME);
        },
        loadComplete: function() {
            // 그리드 로드 완료 후 크기 조정
            $(this).setGridWidth($(this).closest('.grid_wrap').width());
        }
    });

	$("#btn_modify").click(function(){
		if (!checkRequired("ajaxForm"))	return;
		
		var formData = $('#ajaxForm').serializeArray();
		var postData = {};

		formData.forEach(function(field) {
		    postData[field.name] = field.value;
		});
	
		var approvalType = $("select[name=approvalType]").val();
	    // 사용 중인 approvalType 체크
	    if (approvalType !== globalVars.originalApprovalType
	    		&& globalVars.usedApprovalTypes.includes(approvalType)) {
	        alert("선택하신 승인 타입은 이미 사용 중입니다. \n다른 타입을 선택해 주세요.");
	        return;
	    }
	    
		var uniqueApprovers = new Set(globalVars.approverList.map(a => a.userId));
		if (uniqueApprovers.size !== globalVars.approverList.length) {
	        alert("승인자 목록에 중복된 사용자가 있습니다. \n확인 후 다시 시도해주세요.");
	        return;
	    }
		
	    if (!confirm("<%= localeMessage.getString("common.checkSave")%>")) return;
		
	    postData.portalApprovalLineUsers = $('#portalApprovalLineUsersJson').val();
		postData.cmd = isDetail ? "UPDATE" : "INSERT";
		
		$.ajax({
			type : "POST",
			url:url,
			data:postData,
			success:function(){
				alert("<%= localeMessage.getString("common.saveMsg") %>");
				$("#btn_close").trigger("click");
			},
			error: function(xhr, status, error) {
	            console.error("Error during save:", status, error);
	            alert("저장 중 오류가 발생했습니다. \n나중에 다시 시도해 주세요.");
	        }
		});
	});
	
	var originalApproverList = [];
	
	$("#btn_close").click(function(){
		window.close();
	});
	
	 $("#btn_delete").click(function(){
		 if(!confirm("<%= localeMessage.getString("common.confirmMsg")%>")) return;
		 
         $.ajax({
            type : "POST",
            url:url,
            data:{cmd: 'DELETE',		id: $('input[name=id]').val()	},
            success:function(){
               alert("<%= localeMessage.getString("common.deleteMsg") %>");
               $("#btn_close").trigger("click");
            },
            error:function(xhr, status, error){
            	console.error("Error deleting record:", error);
               alert("삭제 중 오류가 발생했습니다. \n나중에 다시 시도해 주세요.");
            }
         }); 
	   });   

	 
	$("#btn_search").click(function(){
		searchUser();
	});

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

 
</script>
</head>
	<body>
		<div class="popup_box">
			<div class="search_wrap">				
				<button type="button" class="cssbtn" id="btn_modify" level="W" status="DETAIL,NEW"><i class="material-icons">save</i> <%= localeMessage.getString("button.modify") %></button>
				<button type="button" class="cssbtn" id="btn_delete" level="W" status="DETAIL"><i class="material-icons">delete</i> <%= localeMessage.getString("button.delete") %></button>
				<button type="button" class="cssbtn" id="btn_close" level="R"><i class="material-icons">cancel</i> <%= localeMessage.getString("button.close") %></button>
			</div>
			<div class="title" id ="title"><%= localeMessage.getString("portalApprovalLine.title2") %></div>	
			
			<form id="ajaxForm">
				<input type="hidden" name="id">
				<input type="hidden"  id="portalApprovalLineUsersJson">
				<table class="table_row" cellspacing="0">
					<tr>
						<th style="width:25%; min-width:100px;"><%= localeMessage.getString("portalApprovalLine.approvalName") %> <font color="red"> *</font></th>
						<td><input type="text"  name="approvalName" data-required data-warning="승인이름을 입력하여 주십시요."/></td>
					</tr>
					<tr>
						<th><%= localeMessage.getString("portalApprovalLine.approvalType") %> <font color="red"> *</font></th>
						<td>
							<div class="select-style" style="position: relative; width: 100%;">
								<select name="approvalType"  data-required data-warning="승인타입을 입력하여 주십시오" id="approvalType"/>
							</div>
						</td>
					</tr>
					<tr>
						<th><%= localeMessage.getString("portalApprovalLine.approvalUserList") %> <font color="red"> *</font></th>
						<td><input type="text"  name=portalApprovalLineUsers data-required data-warning="승인자를 선택하여 주십시요." /></td></td>
					</tr>
				</table>
			
			<div style="padding:20px 0px 0px 0px;">
				<div class="title" ><%= localeMessage.getString("portalApprovalLine.title3") %></div>
				<div style="padding:5px 0;">
					<input type="text" id="searchUserValue" name="searchUserValue" placeholder="사용자 검색하기" style="width:39%; margin-right: 3px;  display:inline-block;">
			        <button type="button" class="cssbtn" id="btn_search" level="R" status="DETAIL,NEW"><i class="material-icons">search</i> <%= localeMessage.getString("button.search") %></button>
			    </div>
		    </div>        
		    
            <div style="display: flex;">
                <div class="width1 grid_wrap" style="margin-right:40px;">
                    <table id="gridUser"class="table_row" cellspacing="0" ></table>
                    <div id="pagerUser" class="pagerUser"></div>
                </div>
                
                <div style="flex-grow:1;">
                    <span id="noApproverMsg" style="display: flex; justify-content: center; align-items: center;">
                    	<h2>승인자를 선택해 주세요</h2>
                   	</span>
                    <div id="approverListContainer">
	                    <ul id="approverList">
	                    <!-- 승인자 리스트가 여기에 동적으로 추가 -->
	                    </ul>
                    </div>
                </div>
                
			</div>
			</form>
		</div><!-- end popup_box -->	
	</body>
</html>

