<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="dateUtil" uri="http://egovframework.go.kr/functions/date-util" %>

<!-- Main body -->
<div class="main_body">
    <section id="section8" class="main_bars">
        <div class="bgs-main">
            <section id="section5">
                <div class="sub_title"></div>
            </section>
        </div>
    </section>
    <div class="contants_body">
        <div class="gs_b_top">
            <ul class="lef">
                <li class="th">조회 구분</li>
                <li>
                    <select id="inqryType" name="inqryType" class="input" style="width: 250px;">
                        <option value="basic">자동차 기본사항 조회</option>
                        <option value="ledger">자동차 등록원부(갑) 조회</option>
                    </select>
                </li>
            </ul>
            <ul class="rig2">
                <li><button type="button" id="search_btn" class="newbtnss bg1">조회</button></li>
                <li><button type="button" id="reset_btn" class="newbtnss bg5" style="margin-left: 5px;">초기화</button></li>
            </ul>
            <!-- 기본정보 조회 조건 -->
            <ul id="basicSearchArea" class="lef2">
                <li class="th"><span class="essential">*</span> 부과기준일</li>
                <li>
                    <input type="text" id="levyStdde" name="levyStdde" class="input datepicker calender" style="width: 150px;" autocomplete="off" value="${dateUtil:getCurrentDateTime('yyyy-MM-dd')}"/>
                </li>
                <li class="th">차량번호</li>
                <li>
                    <input type="text" id="vhrno" name="vhrno" class="input" style="width: 150px;" placeholder="예: 12가3456" maxlength="10" autocomplete="off"/>
                </li>
                <li class="th">차대번호</li>
                <li>
                    <input type="text" id="vin" name="vin" class="input" style="width: 200px;" placeholder="예: KMHAB812345678901" maxlength="17" autocomplete="off"/>
                </li>
            </ul>
            <!-- 등록원부 조회 조건 -->
            <ul id="ledgerSearchArea" class="lef2" style="display: none;">
                <li class="th"><span class="essential">*</span> 차량번호</li>
                <li>
                    <input type="text" id="ledgerVhrno" name="ledgerVhrno" class="input" style="width: 150px;" placeholder="예: 12가3456" maxlength="10" autocomplete="off"/>
                </li>
                <li class="th"><span class="essential">*</span> 소유자명</li>
                <li>
                    <input type="text" id="cpttrNm" name="cpttrNm" class="input" style="width: 150px;" placeholder="소유자명" autocomplete="off"/>
                </li>
                <li class="th"><span class="essential">*</span> 주민번호(회원번호)</li>
                <li>
                    <input type="text" id="cpttrIhidnum" name="cpttrIhidnum" class="input" style="width: 150px;" placeholder="주민번호" maxlength="13" autocomplete="off"/>
                </li>
                <li class="th">법정동코드</li>
                <li>
                    <input type="text" id="cpttrLegaldongCode" name="cpttrLegaldongCode" class="input" style="width: 150px;" placeholder="법정동코드" maxlength="10" autocomplete="off"/>
                </li>
                <li class="th">내역표시</li>
                <li>
                    <select id="detailExpression" name="detailExpression" class="input" style="width: 100px;">
                        <option value="1">전체내역</option>
                        <option value="2">현재내역</option>
                    </select>
                </li>
            </ul>
        </div>
        <div class="gs_booking">
            <div class="row">
                <div class="col-sm-12">
                    <div class="box_column">
                        <ul class="box_title" style="display: flex; justify-content: space-between; align-items: center;">
                            <li class="tit">조회 결과</li>
                            <li class="rig">
                                <button type="button" id="btnResultClose" class="newbtn bg5" style="display: none;">닫기</button>
                            </li>
                        </ul>
                        <div class="containers" style="padding: 20px;">
                            <div id="resultContent" class="result-empty">
                                조회 버튼을 클릭하여 차량 정보를 조회하세요.
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- /Main body -->

<style>
.essential {
    color: red;
    font-weight: bold;
    margin-right: 3px;
}

.result-empty {
    text-align: center;
    padding: 0px;
    color: #999;
    font-size: 14px;
}

.result-detail-table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 10px;
}

.result-detail-table th {
    background-color: #f5f5f5;
    padding: 12px;
    border: 1px solid #ddd;
    text-align: left;
    font-weight: bold;
    width: 20%;
    color: #333;
}

.result-detail-table td {
    padding: 12px;
    border: 1px solid #ddd;
    width: 30%;
    color: #555;
}

.result-section-title {
    background-color: #2c5aa0;
    color: white;
    padding: 10px 15px;
    margin-top: 20px;
    margin-bottom: 10px;
    font-weight: bold;
    border-radius: 4px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.collapse-btn {
    cursor: pointer;
    font-size: 12px;
    font-weight: normal;
    padding: 2px 8px;
    background-color: rgba(255,255,255,0.2);
    border-radius: 3px;
}

.collapse-btn:hover {
    background-color: rgba(255,255,255,0.4);
}

.result-section-title:first-child {
    margin-top: 0;
}

/* 변경 이력 테이블 전용 스타일 */
.result-history-table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 10px;
}

.result-history-table thead th {
    background-color: #e8e8e8;
    padding: 12px 8px;
    border: 1px solid #ddd;
    text-align: center;
    font-weight: bold;
    color: #333;
    font-size: 13px;
}

.result-history-table tbody td {
    padding: 10px 8px;
    border: 1px solid #ddd;
    color: #555;
    font-size: 13px;
}

.result-history-table tbody td.text-center {
    text-align: center;
}

.result-history-table tbody td.text-left {
    text-align: left;
}

.result-history-table tbody tr:hover {
    background-color: #f9f9f9;
}
</style>

<script type="text/javascript">
    /**
     * 차량 정보 조회 모듈
     */
    (function(window, $) {
        'use strict';

        var VehicleInquiry = {

            /**
             * 조회 구분 변경 시 검색 영역 표시/숨김
             */
            onInqryTypeChange: function() {
                var inqryType = $("#inqryType").val();

                // 조회 구분에 따른 검색 영역 표시
                if (inqryType === "basic") {
                    $("#basicSearchArea").show();
                    $("#ledgerSearchArea").hide();
                } else if (inqryType === "ledger") {
                    $("#basicSearchArea").hide();
                    $("#ledgerSearchArea").show();
                }
            },

            /**
             * 조회 실행
             */
            executeSearch: function() {
                var self = this;
                var inqryType = $("#inqryType").val();

                // 조회 타입에 따라 유효성 검사 및 처리
                if (inqryType === "basic") {
                    // 기본정보: 부과기준일 필수, 차량번호 or 차대번호 중 하나 필수
                    var levyStdde = $.trim($("#levyStdde").val());
                    var vhrno = $.trim($("#vhrno").val());
                    var vin = $.trim($("#vin").val());

                    if (!levyStdde) {
                        alert("부과기준일을 입력해주세요.");
                        $("#levyStdde").focus();
                        return;
                    }

                    if (!vhrno && !vin) {
                        alert("차량번호 또는 차대번호 중 하나를 입력해주세요.");
                        $("#vhrno").focus();
                        return;
                    }

                    self.callBasicApi();
                } else if (inqryType === "ledger") {
                    // 등록원부: 차량번호, 소유자명, 주민번호 필수
                    var ledgerVhrno = $.trim($("#ledgerVhrno").val());
                    var cpttrNm = $.trim($("#cpttrNm").val());
                    var cpttrIhidnum = $.trim($("#cpttrIhidnum").val());

                    if (!ledgerVhrno) {
                        alert("차량번호를 입력해주세요.");
                        $("#ledgerVhrno").focus();
                        return;
                    }

                    if (!cpttrNm) {
                        alert("소유자명을 입력해주세요.");
                        $("#cpttrNm").focus();
                        return;
                    }

                    if (!cpttrIhidnum) {
                        alert("주민번호를 입력해주세요.");
                        $("#cpttrIhidnum").focus();
                        return;
                    }

                    self.callLedgerApi();
                }
            },

            /**
             * 기본사항 조회 API 호출
             */
            callBasicApi: function() {
                var self = this;
                var vhrno = $.trim($("#vhrno").val());
                var levyStdde = $.trim($("#levyStdde").val()).replace(/-/g, '');
                var vin = $.trim($("#vin").val());

                // BasicRequest의 @JsonProperty에 맞춰 대문자 키 사용
                // INQIRE_SE_CODE는 VmisRequestEnricher에서 자동 설정됨
                var params = {
                    VHRNO: vhrno,
                    LEVY_STDDE: levyStdde
                };

                if (vin) {
                    params.VIN = vin;
                }

                $.ajax({
                    url: '/carInspectionPenalty/callApi/getBasicInfo.do',
                    type: 'POST',
                    contentType: 'application/json; charset=UTF-8',
                    data: JSON.stringify(params),
                    dataType: 'json',
                    success: function(response) {
                        if (response.success) {
                            console.log("기본사항 조회 성공:", response.data);
                            self.displayBasicResult(response.data);
                            $("#btnResultClose").show();
                        } else {
                            alert("조회 실패\n\n" + (response.message || "알 수 없는 오류가 발생했습니다."));
                            $("#resultContent").html('<div class="result-empty">조회된 데이터가 없습니다.</div>');
                        }
                    },
                    error: function(xhr, status, error) {
                        $("#resultContent").html('<div class="result-empty">조회 중 오류가 발생했습니다.</div>');
                    }
                });
            },

            /**
             * 등록원부 조회 API 호출
             */
            callLedgerApi: function() {
                var self = this;
                var vhrno = $.trim($("#ledgerVhrno").val());
                var cpttrNm = $.trim($("#cpttrNm").val());
                var cpttrIhidnum = $.trim($("#cpttrIhidnum").val());
                var cpttrLegaldongCode = $.trim($("#cpttrLegaldongCode").val());
                var routeSeCode = $("#routeSeCode").val();
                var detailExpression = $("#detailExpression").val();

                // LedgerRequest의 @JsonProperty에 맞춰 대문자 키 사용
                // INQIRE_SE_CODE는 VmisRequestEnricher에서 자동으로 "1"(열람)로 설정됨
                var params = {
                    VHRNO: vhrno,
                    CPTTR_NM: cpttrNm,
                    CPTTR_IHIDNUM: cpttrIhidnum,
                    ROUTE_SE_CODE: routeSeCode,
                    DETAIL_EXPRESSION: detailExpression
                };

                // 선택 필드 추가
                if (cpttrLegaldongCode) {
                    params.CPTTR_LEGALDONG_CODE = cpttrLegaldongCode;
                }

                $.ajax({
                    url: '/carInspectionPenalty/callApi/getLedgerInfo.do',
                    type: 'POST',
                    contentType: 'application/json; charset=UTF-8',
                    data: JSON.stringify(params),
                    dataType: 'json',
                    success: function(response) {
                        if (response.success) {
                            console.log("등록원부 조회 성공:", response.data);
                            self.displayLedgerResult(response.data);
                            $("#btnResultClose").show();
                        } else {
                            alert("조회 실패\n\n" + (response.message || "알 수 없는 오류가 발생했습니다."));
                            $("#resultContent").html('<div class="result-empty">조회된 데이터가 없습니다.</div>');
                        }
                    },
                    error: function(xhr, status, error) {
                        $("#resultContent").html('<div class="result-empty">조회 중 오류가 발생했습니다.</div>');
                    }
                });
            },

            /**
             * 기본사항 조회 결과 표시
             */
            displayBasicResult: function(data) {
                var html = this.getBasicInfoHtml(data);
                $("#resultContent").html(html);
            },

            /**
             * 기본사항 조회 결과 HTML 생성
             */
            getBasicInfoHtml: function(data) {
                var html = '<div class="result-section-title collapsible-title" data-target="#basicInfoContent">자동차 기본사항 정보<span class="collapse-btn">[접기]</span></div>';
                html += '<div id="basicInfoContent" class="collapsible-content">';
                html += '<table class="result-detail-table">';
                html += '<colgroup><col style="width:20%"><col style="width:30%"><col style="width:20%"><col style="width:30%"></colgroup>';

                html += '<tr><th>생산년도</th><td>' + this.nvl(data.prye) + '</td>';
                html += '<th>등록일자</th><td>' + this.nvl(data.registDe) + '</td></tr>';
                html += '<tr><th>말소등록구분코드</th><td>' + this.nvl(data.ersrRegistSeCode) + '</td>';
                html += '<th>말소등록구분명</th><td>' + this.nvl(data.ersrRegistSeNm) + '</td></tr>';
                html += '<tr><th>말소등록일자</th><td>' + this.nvl(data.ersrRegistDe) + '</td>';
                html += '<th>등록상세코드</th><td>' + this.nvl(data.registDetailCode) + '</td></tr>';
                html += '<tr><th>배기량</th><td>' + this.nvl(data.dsplvl) + '</td>';
                html += '<th>사용본거지법정동코드</th><td>' + this.nvl(data.useStrnghldLegaldongCode) + '</td></tr>';
                html += '<tr><th>사용본거지행정동코드</th><td>' + this.nvl(data.useStrnghldAdstrdCode) + '</td>';
                html += '<th>사용본거지산</th><td>' + this.nvl(data.useStrnghldMntn) + '</td></tr>';
                html += '<tr><th>사용본거지번지</th><td>' + this.nvl(data.useStrnghldLnbr) + '</td>';
                html += '<th>사용본거지호</th><td>' + this.nvl(data.useStrnghldHo) + '</td></tr>';
                html += '<tr><th>사용본거지주소명</th><td>' + this.nvl(data.useStrnghldAdresNm) + '</td>';
                html += '<th>사용본거지도로명코드</th><td>' + this.nvl(data.useStrnghldRoadNmCode) + '</td></tr>';
                html += '<tr><th>사용본거지지하건물구분코드</th><td>' + this.nvl(data.usgsrhldUndgrndBuldSeCode) + '</td>';
                html += '<th>사용본거지건물본번</th><td>' + this.nvl(data.useStrnghldBuldMainNo) + '</td></tr>';
                html += '<tr><th>사용본거지건물부번</th><td>' + this.nvl(data.useStrnghldBuldSubNo) + '</td>';
                html += '<th>사용본거지우편번호코드</th><td>' + this.nvl(data.useStrnghldGrcCode) + '</td></tr>';
                html += '<tr><th>사용본거지주소전체</th><td colspan="3">' + this.nvl(data.usgsrhldAdresFull) + '</td></tr>';
                html += '<tr><th>소유자구분코드</th><td>' + this.nvl(data.mberSeCode) + '</td>';
                html += '<th>소유자명</th><td>' + this.nvl(data.mberNm) + '</td></tr>';
                html += '<tr><th>소유자구분번호</th><td>' + this.nvl(data.mberSeNo) + '</td>';
                html += '<th>전화번호</th><td>' + this.nvl(data.telno) + '</td></tr>';
                html += '<tr><th>소유자법정동코드</th><td>' + this.nvl(data.ownerLegaldongCode) + '</td>';
                html += '<th>소유자행정동코드</th><td>' + this.nvl(data.ownerAdstrdCode) + '</td></tr>';
                html += '<tr><th>소유자산</th><td>' + this.nvl(data.ownerMntn) + '</td>';
                html += '<th>소유자번지</th><td>' + this.nvl(data.ownerLnbr) + '</td></tr>';
                html += '<tr><th>소유자호</th><td>' + this.nvl(data.ownerHo) + '</td>';
                html += '<th>소유자주소명</th><td>' + this.nvl(data.ownerAdresNm) + '</td></tr>';
                html += '<tr><th>소유자도로명코드</th><td>' + this.nvl(data.ownerRoadNmCode) + '</td>';
                html += '<th>소유자지하건물구분코드</th><td>' + this.nvl(data.ownerUndgrndBuldSeCode) + '</td></tr>';
                html += '<tr><th>소유자건물본번</th><td>' + this.nvl(data.ownerBuldMainNo) + '</td>';
                html += '<th>소유자건물부번</th><td>' + this.nvl(data.ownerBuldSubNo) + '</td></tr>';
                html += '<tr><th>소유자주소전체</th><td colspan="3">' + this.nvl(data.ownerAdresFull) + '</td></tr>';
                html += '<tr><th>변경후차량번호</th><td>' + this.nvl(data.aftrVhrno) + '</td>';
                html += '<th>사용연료코드</th><td>' + this.nvl(data.useFuelCode) + '</td></tr>';
                html += '<tr><th>용도구분코드</th><td>' + this.nvl(data.prposSeCode) + '</td>';
                html += '<th>제작사명</th><td>' + this.nvl(data.mtrsFomNm) + '</td></tr>';
                html += '<tr><th>변경전차량번호</th><td>' + this.nvl(data.frntVhrno) + '</td>';
                html += '<th>차량번호</th><td>' + this.nvl(data.vhrno) + '</td></tr>';
                html += '<tr><th>차대번호</th><td>' + this.nvl(data.vin) + '</td>';
                html += '<th>차명</th><td>' + this.nvl(data.cnm) + '</td></tr>';
                html += '<tr><th>차량총중량</th><td>' + this.nvl(data.vhcleTotWt) + '</td>';
                html += '<th>자동차보험종료일자</th><td>' + this.nvl(data.caagEndde) + '</td></tr>';
                html += '<tr><th>변경일자</th><td>' + this.nvl(data.changeDe) + '</td>';
                html += '<th>차종분류코드</th><td>' + this.nvl(data.vhctyAsortCode) + '</td></tr>';
                html += '<tr><th>차종유형코드</th><td>' + this.nvl(data.vhctyTyCode) + '</td>';
                html += '<th>차종구분코드</th><td>' + this.nvl(data.vhctySeCode) + '</td></tr>';
                html += '<tr><th>최대적재량</th><td>' + this.nvl(data.mxmmLdg) + '</td>';
                html += '<th>차종분류명</th><td>' + this.nvl(data.vhctyAsortNm) + '</td></tr>';
                html += '<tr><th>차종유형명</th><td>' + this.nvl(data.vhctyTyNm) + '</td>';
                html += '<th>차종구분명</th><td>' + this.nvl(data.vhctySeNm) + '</td></tr>';
                html += '<tr><th>최초등록일자</th><td>' + this.nvl(data.frstRegistDe) + '</td>';
                html += '<th>형식명</th><td>' + this.nvl(data.fomNm) + '</td></tr>';
                html += '<tr><th>취득일자</th><td>' + this.nvl(data.acqsDe) + '</td>';
                html += '<th>취득종료일자</th><td>' + this.nvl(data.acqsEndDe) + '</td></tr>';
                html += '<tr><th>연식월</th><td>' + this.nvl(data.yblMd) + '</td>';
                html += '<th>이전등록일자</th><td>' + this.nvl(data.transrRegistDe) + '</td></tr>';
                html += '<tr><th>특정등록상태코드</th><td>' + this.nvl(data.spcfRegistSttusCode) + '</td>';
                html += '<th>색상명</th><td>' + this.nvl(data.colorNm) + '</td></tr>';
                html += '<tr><th>저당건수</th><td>' + this.nvl(data.mrtgCo) + '</td>';
                html += '<th>압류건수</th><td>' + this.nvl(data.seizrCo) + '</td></tr>';
                html += '<tr><th>압인건수</th><td>' + this.nvl(data.stmdCo) + '</td>';
                html += '<th>번호판보관여부</th><td>' + this.nvl(data.nmplCsdyAt) + '</td></tr>';
                html += '<tr><th>번호판보관반납일자</th><td>' + this.nvl(data.nmplCsdyRemnrDe) + '</td>';
                html += '<th>원산지구분코드</th><td>' + this.nvl(data.originSeCode) + '</td></tr>';
                html += '<tr><th>번호판규격코드</th><td>' + this.nvl(data.nmplStndrdCode) + '</td>';
                html += '<th>취득금액</th><td>' + this.nvl(data.acqsAmount) + '</td></tr>';
                html += '<tr><th>검사유효기간시작일자</th><td>' + this.nvl(data.insptValidPdBgnde) + '</td>';
                html += '<th>검사유효기간종료일자</th><td>' + this.nvl(data.insptValidPdEndde) + '</td></tr>';
                html += '<tr><th>화물차승차정원수</th><td>' + this.nvl(data.tkcarPscapCo) + '</td>';
                html += '<th>사양번호</th><td>' + this.nvl(data.spmnno) + '</td></tr>';
                html += '<tr><th>주행거리</th><td>' + this.nvl(data.trvlDstnc) + '</td>';
                html += '<th>최초등록신청번호</th><td>' + this.nvl(data.frstRegistRqrcno) + '</td></tr>';
                html += '<tr><th>자진말소예방공지일자</th><td>' + this.nvl(data.vlntErsrPrvntcNticeDe) + '</td>';
                html += '<th>등록기관명</th><td>' + this.nvl(data.registInsttNm) + '</td></tr>';
                html += '<tr><th>처리불가사유코드</th><td>' + this.nvl(data.processImprtyResnCode) + '</td>';
                html += '<th>처리불가사유상세</th><td>' + this.nvl(data.processImprtyResnDtls) + '</td></tr>';
                html += '<tr><th>차체길이</th><td>' + this.nvl(data.cbdLt) + '</td>';
                html += '<th>차체너비</th><td>' + this.nvl(data.cbdBt) + '</td></tr>';
                html += '<tr><th>차체높이</th><td>' + this.nvl(data.cbdHg) + '</td>';
                html += '<th>최초최대적재량</th><td>' + this.nvl(data.frstMxmmLdg) + '</td></tr>';
                html += '<tr><th>연료소비율</th><td>' + this.nvl(data.fuelCnsmpRt) + '</td>';
                html += '<th>전기복합연료소비율</th><td>' + this.nvl(data.elctyCmpndFuelCnsmpRt) + '</td></tr>';
                html += '</table>';
                html += '</div>';
                return html;
            },

            /**
             * 등록원부 조회 결과 표시
             */
            displayLedgerResult: function(data) {
                var html = this.getLedgerInfoHtml(data);
                $("#resultContent").html(html);
            },

            /**
             * 등록원부 조회 결과 HTML 생성
             */
            getLedgerInfoHtml: function(data) {
                var html = '<div class="result-section-title collapsible-title" data-target="#ledgerInfoContent">자동차 등록원부 정보<span class="collapse-btn">[접기]</span></div>';
                html += '<div id="ledgerInfoContent" class="collapsible-content">';
                html += '<table class="result-detail-table">';
                html += '<colgroup><col style="width:20%"><col style="width:30%"><col style="width:20%"><col style="width:30%"></colgroup>';
                html += this.getLedgerInfoTableRows(data);
                html += '</table>';
                html += '</div>';

                if (data.record && data.record.length > 0) {
                    html += '<div class="result-section-title collapsible-title" style="margin-top: 30px;" data-target="#ledgerHistoryContent">등록원부 변경 이력 (' + data.record.length + '건)<span class="collapse-btn">[접기]</span></div>';
                    html += '<div id="ledgerHistoryContent" class="collapsible-content">';
                    html += '<table class="result-history-table">';
                    html += '<thead>';
                    html += '<tr>';
                    html += '<th>번호</th><th>메인체크</th><th>변경작업구분코드</th><th>주번호</th><th>부번호</th><th>구분명</th>';
                    html += '<th>변경일자</th><th>원부그룹번호</th><th>원부개별번호</th><th>신청번호</th><th>차량관리번호</th>';
                    html += '<th>상세내역</th><th>상세일련번호</th><th>플래그</th>';
                    html += '</tr>';
                    html += '</thead>';
                    html += '<tbody>';

                    for (var i = 0; i < data.record.length; i++) {
                        var rec = data.record[i];
                        html += '<tr>';
                        html += '<td class="text-center">' + (i + 1) + '</td>';
                        html += '<td class="text-center">' + this.nvl(rec.mainchk) + '</td>';
                        html += '<td class="text-center">' + this.nvl(rec.changeJobSeCode) + '</td>';
                        html += '<td class="text-center">' + this.nvl(rec.mainno) + '</td>';
                        html += '<td class="text-center">' + this.nvl(rec.subno) + '</td>';
                        html += '<td class="text-center">' + this.nvl(rec.gubunNm) + '</td>';
                        html += '<td class="text-center">' + this.nvl(rec.changeDe) + '</td>';
                        html += '<td class="text-center">' + this.nvl(rec.ledgerGroupNo) + '</td>';
                        html += '<td class="text-center">' + this.nvl(rec.ledgerIndvdlzNo) + '</td>';
                        html += '<td class="text-center">' + this.nvl(rec.rqrcno) + '</td>';
                        html += '<td class="text-center">' + this.nvl(rec.vhmno) + '</td>';
                        html += '<td class="text-left">' + this.nvl(rec.dtls) + '</td>';
                        html += '<td class="text-center">' + this.nvl(rec.detailSn) + '</td>';
                        html += '<td class="text-center">' + this.nvl(rec.flag) + '</td>';
                        html += '</tr>';
                    }

                    html += '</tbody>';
                    html += '</table>';
                    html += '</div>';
                }
                return html;
            },

            /**
             * LedgerInfo 테이블 행 생성
             */
            getLedgerInfoTableRows: function(data) {
                var html = '';
                html += '<tr><th>연계결과코드</th><td>' + this.nvl(data.cntcResultCode) + '</td>';
                html += '<th>연계결과상세</th><td>' + this.nvl(data.cntcResultDtls) + '</td></tr>';
                html += '<tr><th>원부그룹번호</th><td>' + this.nvl(data.ledgerGroupNo) + '</td>';
                html += '<th>원부개별화번호</th><td>' + this.nvl(data.ledgerIndvdlzNo) + '</td></tr>';
                html += '<tr><th>차량관리번호</th><td>' + this.nvl(data.vhmno) + '</td>';
                html += '<th>차량번호</th><td>' + this.nvl(data.vhrno) + '</td></tr>';
                html += '<tr><th>차대번호</th><td>' + this.nvl(data.vin) + '</td>';
                html += '<th>차종분류코드</th><td>' + this.nvl(data.vhctyAsortCode) + '</td></tr>';
                html += '<tr><th>차종분류명</th><td>' + this.nvl(data.vhctyAsortNm) + '</td>';
                html += '<th>차명</th><td>' + this.nvl(data.cnm) + '</td></tr>';
                html += '<tr><th>색상코드</th><td>' + this.nvl(data.colorCode) + '</td>';
                html += '<th>색상명</th><td>' + this.nvl(data.colorNm) + '</td></tr>';
                html += '<tr><th>번호판규격코드</th><td>' + this.nvl(data.nmplStndrdCode) + '</td>';
                html += '<th>번호판규격명</th><td>' + this.nvl(data.nmplStndrdNm) + '</td></tr>';
                html += '<tr><th>용도구분코드</th><td>' + this.nvl(data.prposSeCode) + '</td>';
                html += '<th>용도구분명</th><td>' + this.nvl(data.prposSeNm) + '</td></tr>';
                html += '<tr><th>제작사명</th><td>' + this.nvl(data.mtrsFomNm) + '</td>';
                html += '<th>형식명</th><td>' + this.nvl(data.fomNm) + '</td></tr>';
                html += '<tr><th>취득금액</th><td>' + this.nvl(data.acqsAmount) + '</td>';
                html += '<th>등록상세코드</th><td>' + this.nvl(data.registDetailCode) + '</td></tr>';
                html += '<tr><th>등록상세명</th><td>' + this.nvl(data.registDetailNm) + '</td>';
                html += '<th>최초등록일자</th><td>' + this.nvl(data.frstRegistDe) + '</td></tr>';
                html += '<tr><th>자동차보험종료일자</th><td>' + this.nvl(data.caagEndde) + '</td>';
                html += '<th>생산년도</th><td>' + this.nvl(data.prye) + '</td></tr>';
                html += '<tr><th>사양번호1</th><td>' + this.nvl(data.spmnno1) + '</td>';
                html += '<th>사양번호2</th><td>' + this.nvl(data.spmnno2) + '</td></tr>';
                html += '<tr><th>연식월</th><td>' + this.nvl(data.yblMd) + '</td>';
                html += '<th>주행거리</th><td>' + this.nvl(data.trvlDstnc) + '</td></tr>';
                html += '<tr><th>검사유효기간시작일자</th><td>' + this.nvl(data.insptValidPdBgnde) + '</td>';
                html += '<th>검사유효기간종료일자</th><td>' + this.nvl(data.insptValidPdEndde) + '</td></tr>';
                html += '<tr><th>점검유효기간시작일자</th><td>' + this.nvl(data.chckValidPdBgnde) + '</td>';
                html += '<th>점검유효기간종료일자</th><td>' + this.nvl(data.chckValidPdEndde) + '</td></tr>';
                html += '<tr><th>등록신청구분명</th><td>' + this.nvl(data.registReqstSeNm) + '</td>';
                html += '<th>최초등록신청번호</th><td>' + this.nvl(data.frstRegistRqrcno) + '</td></tr>';
                html += '<tr><th>번호판보관반납일자</th><td>' + this.nvl(data.nmplCsdyRemnrDe) + '</td>';
                html += '<th>번호판보관여부</th><td>' + this.nvl(data.nmplCsdyAt) + '</td></tr>';
                html += '<tr><th>영업용사용기간</th><td>' + this.nvl(data.bssUsePd) + '</td>';
                html += '<th>직권말소예방공지일자</th><td>' + this.nvl(data.octhtErsrPrvntcNticeDe) + '</td></tr>';
                html += '<tr><th>말소등록일자</th><td>' + this.nvl(data.ersrRegistDe) + '</td>';
                html += '<th>말소등록구분코드</th><td>' + this.nvl(data.ersrRegistSeCode) + '</td></tr>';
                html += '<tr><th>말소등록구분명</th><td>' + this.nvl(data.ersrRegistSeNm) + '</td>';
                html += '<th>저당건수</th><td>' + this.nvl(data.mrtgcnt) + '</td></tr>';
                html += '<tr><th>차량건수</th><td>' + this.nvl(data.vhclecnt) + '</td>';
                html += '<th>압인건수</th><td>' + this.nvl(data.stmdcnt) + '</td></tr>';
                html += '<tr><th>주소1</th><td>' + this.nvl(data.adres1) + '</td>';
                html += '<th>주소명1</th><td>' + this.nvl(data.adresNm1) + '</td></tr>';
                html += '<tr><th>주소</th><td>' + this.nvl(data.adres) + '</td>';
                html += '<th>주소명</th><td>' + this.nvl(data.adresNm) + '</td></tr>';
                html += '<tr><th>개인법인여부</th><td>' + this.nvl(data.indvdlBsnmAt) + '</td>';
                html += '<th>전화번호</th><td>' + this.nvl(data.telno) + '</td></tr>';
                html += '<tr><th>소유자명</th><td>' + this.nvl(data.mberNm) + '</td>';
                html += '<th>소유자구분코드</th><td>' + this.nvl(data.mberSeCode) + '</td></tr>';
                html += '<tr><th>소유자구분번호</th><td>' + this.nvl(data.mberSeNo) + '</td>';
                html += '<th>면세대상자구분코드</th><td>' + this.nvl(data.taxxmptTrgterSeCode) + '</td></tr>';
                html += '<tr><th>면세대상자구분코드명</th><td>' + this.nvl(data.taxxmptTrgterSeCodeNm) + '</td>';
                html += '<th>건수사항</th><td>' + this.nvl(data.cntMatter) + '</td></tr>';
                html += '<tr><th>읍면동명</th><td>' + this.nvl(data.emdNm) + '</td>';
                html += '<th>예방건수</th><td>' + this.nvl(data.prvntccnt) + '</td></tr>';
                html += '<tr><th>수출이행여부확인일자</th><td>' + this.nvl(data.xportFlflAtSttemntDe) + '</td>';
                html += '<th>협력사신청번호</th><td>' + this.nvl(data.partnRqrcno) + '</td></tr>';
                return html;
            },

            /**
             * null 값 처리
             */
            nvl: function(value, defaultValue) {
                if (value === null || value === undefined || value === '') {
                    return defaultValue || '-';
                }
                return value;
            },

            /**
             * 이벤트 핸들러 설정
             */
            eventBindEvents: function() {
                var self = this;

                // 조회 구분 변경 이벤트
                $("#inqryType").on('change', function() {
                    self.onInqryTypeChange();
                });

                // 조회 버튼 클릭 이벤트
                $("#search_btn").on('click', function() {
                    self.executeSearch();
                });

                // 초기화 버튼 클릭 이벤트
                $("#reset_btn").on('click', function() {
                    // 기본정보 조회 필드 초기화
                    $("#levyStdde").val("${dateUtil:getCurrentDateTime('yyyy-MM-dd')}");
                    $("#vhrno").val("");
                    $("#vin").val("");
                    // 등록원부 조회 필드 초기화
                    $("#ledgerVhrno").val("");
                    $("#cpttrNm").val("");
                    $("#cpttrIhidnum").val("");
                    $("#cpttrLegaldongCode").val("");
                    $("#routeSeCode").val("3");
                    $("#detailExpression").val("1");
                    // 결과 영역 초기화
                    $("#resultContent").html('<div class="result-empty">조회 버튼을 클릭하여 차량 정보를 조회하세요.</div>');
                    $("#btnResultClose").hide();
                });

                // 결과 닫기 버튼 클릭 이벤트
                $("#btnResultClose").on('click', function() {
                    $("#resultContent").html('<div class="result-empty">조회 버튼을 클릭하여 차량 정보를 조회하세요.</div>');
                    $(this).hide();
                });

                // 엔터키 검색
                $("#vhrno, #vin, #ledgerVhrno, #cpttrNm, #cpttrIhidnum, #cpttrLegaldongCode").on('keypress', function(e) {
                    if (e.which === 13) {
                        e.preventDefault();
                        $("#search_btn").trigger('click');
                    }
                });

                // 섹션 접기/펼치기 이벤트
                $("#resultContent").on('click', '.collapsible-title', function() {
                    var targetId = $(this).data('target');
                    var $content = $(targetId);
                    var $btn = $(this).find('.collapse-btn');

                    $content.slideToggle('fast', function() {
                        if ($content.is(':visible')) {
                            $btn.text('[접기]');
                        } else {
                            $btn.text('[펼치기]');
                        }
                    });
                });
            },

            /**
             * 모듈 초기화
             */
            init: function() {
                console.log("차량 정보 조회 모듈 초기화");

                // 초기 필드 표시/숨김 설정
                this.onInqryTypeChange();

                // 이벤트 핸들러 설정
                this.eventBindEvents();
            }
        };

        // DOM 준비 완료 시 초기화
        $(document).ready(function() {
            VehicleInquiry.init();
        });

        // 전역 네임스페이스에 모듈 노출
        window.VehicleInquiry = VehicleInquiry;

    })(window, jQuery);
</script>
