<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>기존 고객 조회 - 메이드유 CRM</title>
    
    <link rel="stylesheet" href="/css/web/font.css">
    <link rel="stylesheet" href="/css/kiosk/new-patient.css">
	
	<script src="/js/web/jquery.min.js"></script>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
	<script src="/js/web/jquery-ui.js"></script>

    <style>
        /* 페이지 기본 레이아웃 */
        .page-body.search-mode {
            display: flex;
            justify-content: center;
            align-items: center;
            padding-top: 60px;
        }

        .search-card {
            width: 100%;
            max-width: 480px;
        }

        .phone-group {
            display: flex;
            align-items: center;
            gap: 8px;
            width: 100%;
        }

        .phone-group input {
            flex: 1;
            text-align: center;
            height: 44px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            font-size: 16px;
        }

        /* [변경] 스크롤 기능을 위한 테이블 컨테이너 */
        .user-list-container {
            max-height: 450px; /* 약 10row 기준 높이 (1row 당 약 45px) */
            overflow-y: auto;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            margin-top: 10px;
        }

        .user-list-table {
            width: 100%;
            border-collapse: collapse;
        }

        /* [변경] 헤더 고정 스타일 */
        .user-list-table thead th {
            position: sticky;
            top: 0;
            background-color: #f8f9fa;
            padding: 12px 8px;
            border-bottom: 2px solid var(--border-color);
            font-size: 13px;
            color: var(--text-sub);
            text-align: center;
            z-index: 10;
        }

        .user-list-table td {
            padding: 12px 8px;
            border-bottom: 1px solid #eee;
            font-size: 14px;
            text-align: center;
            color: var(--text-main);
            cursor: pointer;
        }

        .user-list-table tr:hover td {
            background-color: #f1f8ff;
        }

        /* 라디오 버튼 스타일 */
        .user-radio {
            width: 18px;
            height: 18px;
            accent-color: var(--primary-color);
            cursor: pointer;
        }

        /* jQuery UI 버튼 스타일 */
        .btn-registration {
            background-color: var(--primary-color) !important;
            color: #ffffff !important;
            border: 1px solid var(--primary-color) !important;
            font-weight: 600 !important;
        }

        .btn-registration:hover {
            background-color: var(--primary-hover) !important;
        }

        .ui-dialog {
            border-radius: 12px !important;
            padding: 0 !important;
            overflow: hidden;
            border: none !important;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1) !important;
        }
        
        .ui-dialog-titlebar {
            background: #fff !important;
            border: none !important;
            border-bottom: 1px solid var(--border-color) !important;
            padding: 15px 20px !important;
        }

        /* 커스텀 스크롤바 디자인 */
        .user-list-container::-webkit-scrollbar {
            width: 6px;
        }
        .user-list-container::-webkit-scrollbar-thumb {
            background-color: #ccd3d9;
            border-radius: 10px;
        }
        .user-list-container::-webkit-scrollbar-track {
            background-color: #f1f3f5;
        }
    </style>
</head>
<body>
    <div class="new-patient-container">
        <header class="page-header">
            <h1 class="title">기존 고객 조회</h1>
        </header>

        <main class="page-body search-mode">
            <section class="form-section-card search-card">
                <div class="section-title">
                    연락처 조회
                    <span id="phone-error" class="validation-msg" style="visibility: hidden;">번호를 정확히 입력해주세요.</span>
                </div>

                <div class="form-row">
                    <label class="required">연락처</label>
                    <div class="phone-group">
                        <input type="tel" id="phone1" maxlength="3" placeholder="010" inputmode="numeric" value="010">
                        <span>-</span>
                        <input type="tel" id="phone2" maxlength="4" placeholder="0000" inputmode="numeric" value="3873">
                        <span>-</span>
                        <input type="tel" id="phone3" maxlength="4" placeholder="0000" inputmode="numeric" value="8265">
                    </div>
                </div>

                <div style="margin-top: 20px;">
                    <button type="button" class="registration_bth" style="width: 100%;" onclick="validateAndSearch()">조회하기</button>
                </div>
            </section>
        </main>

        <footer class="page-footer">
            <button type="button" class="cancel_btn" onclick="moveKiosk()">뒤로가기</button>
        </footer>
    </div>

    <div id="customerDialog" title="고객 선택" style="display:none;">
        <p style="margin: 15px 0 10px; font-size: 14px; color: #666;">접수하실 고객님을 선택해 주세요.</p>
        
        <div class="user-list-container">
            <table class="user-list-table">
                <thead>
                    <tr>
                        <th>선택</th>
                        <th>성함</th>
                        <th>생년월일</th>
                        <th>성별</th>
                        <th>최근 방문일</th>
                    </tr>
                </thead>
                <tbody id="userListBody">
                </tbody>
            </table>
        </div>
    </div>

    <script>
        const inputs = [
            document.getElementById('phone1'),
            document.getElementById('phone2'),
            document.getElementById('phone3')
        ];

        $(document).ready(function() {
            // jQuery UI Dialog 설정
            $("#customerDialog").dialog({
                autoOpen: false,
                modal: true,
                width: 600, // 스크롤바 공간을 고려하여 너비 소폭 확장
                resizable: false,
                show: { effect: "fade", duration: 200 },
                hide: { effect: "fade", duration: 200 },
                buttons: [
                    {
                        text: "접수하기",
                        class: "btn-registration",
                        click: function() {
                            submitBtn();
                        }
                    },
                    {
                        text: "닫기",
                        click: function() {
                            $(this).dialog("close");
                        }
                    }
                ]
            });

            // 행 클릭 시 라디오 버튼 선택
            $(document).on('click', '.user-list-table tbody tr', function() {
                $(this).find('input[type="radio"]').prop('checked', true);
            });
        });

        inputs.forEach((input, index) => {
            input.addEventListener('input', (e) => {
                e.target.value = e.target.value.replace(/[^0-9]/g, '');
                if (e.target.value.length === e.target.maxLength && index < 2) {
                    inputs[index + 1].focus();
                }
            });
        });

        function validateAndSearch() {
            const values = inputs.map(input => input.value);
            const phoneNumber = values.join('');
            
            if (values[1].length < 3 || values[2].length < 4) {
                $("#phone-error").css("visibility", "visible");
                return;
            }

            $.ajax({
                url: '/kiosk/getUserByPhoneNumber.do',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ phoneNumber: phoneNumber }),
                success: function(res) {
                    let html = "";
                    if( res.msgCode == 0 ){
                        const userList = res.list;
                        console.log(userList);
                        if (!userList || userList.length === 0) {
                            alert("조회된 정보가 없습니다.");
                            return;
                        }

                        userList.forEach((user, index) => {
                            html += `
                                <tr>
                                    <td><input type="radio" name="selectedUser" class="user-radio" value="${user.muUserId}" ${index === 0 ? 'checked' : ''}></td>
                                    <td class="user-name-cell">${user.userName}</td>
                                    <td>${user.birthday || '-'}</td>
                                    <td>${user.gender === 'M' ? '남' : (user.gender === 'F' ? '여' : '-')}</td>
                                    <td>${user.lastVisitDate || '-'}</td>
                                </tr>
                            `;
                        });
                    } else {
                        alert(res.msgDesc);
                        return;
                    }

                    $("#userListBody").html(html);
                    $("#customerDialog").dialog("open");
                },
                error: function() {
                    alert("통신 오류가 발생했습니다.");
                }
            });
        }

		function submitBtn() {
		    const selectedUser = $("input[name='selectedUser']:checked");
		    
		    // 1. 선택 여부 확인
		    if (selectedUser.length === 0) {
		        alert("접수할 고객을 선택해 주세요.");
		        return;
		    }

		    // 2. 선택된 사용자의 식별값 (userNumber) 가져오기
		    const muUserId = selectedUser.val();
		    const userName = selectedUser.closest('tr').find('.user-name-cell').text();

		    // 3. 서버로 접수 정보 전송 (AJAX)
		    $.ajax({
		        url: '/kiosk/putSubmit.do', // 실제 서버의 접수 처리 URL로 변경하세요
		        type: 'POST',
		        contentType: 'application/json',
		        data: JSON.stringify({ 
		            muUserId: muUserId,
					userName: userName 
		        }),
		        success: function(res) {
		            if (res.msgCode == 0) {
		                alert(res.msgDesc);
		                $("#customerDialog").dialog("close");
		                
		                // 접수 완료 후 메인 페이지로 이동하거나 초기화
		                location.href = "/kiosk"; 
		            } else {
		                alert(res.msgDesc);
		            }
		        },
		        error: function() {
		            alert("서버 통신 중 오류가 발생했습니다.");
		        }
		    });
		}

        function moveKiosk() {
            window.location.href = "/kiosk";
        }
    </script>
</body>
</html>