<%@ 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="integrated">자동차 통합 조회 (기본+등록원부)</option>
                        <option value="basic">자동차 기본사항 조회 (단독)</option>
                        <option value="ledger">자동차 등록원부(갑) 조회 (단독)</option>
                    </select>
                </li>
                <li class="th"><span class="essential">*</span> 차량번호</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 basicField" style="display: inline;">부과기준일</li>
                <li class="basicField" style="display: inline;">
                    <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 basicField" style="display: inline;">차대번호</li>
                <li class="basicField" style="display: inline;">
                    <input type="text" id="vin" name="vin" class="input" style="width: 200px;" placeholder="예: KMHAB812345678901" maxlength="17" autocomplete="off"/>
                </li>
                <li class="th ledgerField" style="display: none;">민원인성명</li>
                <li class="ledgerField" style="display: none;">
                    <input type="text" id="cpttrNm" name="cpttrNm" class="input" style="width: 150px;" placeholder="민원인성명" autocomplete="off"/>
                </li>
                <li class="th ledgerField" style="display: none;">민원인주민번호</li>
                <li class="ledgerField" style="display: none;">
                    <input type="text" id="cpttrIhidnum" name="cpttrIhidnum" class="input" style="width: 200px;" placeholder="민원인주민번호" maxlength="13" autocomplete="off"/>
                </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>
                <li><button type="button" id="sample1_btn" class="newbtnss bg3" style="margin-left: 5px;">샘플1 (기본정보+등록원부)</button></li>
                <li><button type="button" id="sample2_btn" class="newbtnss bg3" style="margin-left: 5px;">샘플2 (등록원부)</button></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 = {

            /**
             * 샘플 데이터 1: 통합 조회 (기본정보 + 등록원부)
             */
            getSampleData1: function() {
                return {
                    vhrno: "12가3456",
                    basicInfo: {
                        prye: "2021",
                        registDe: "20210315",
                        ersrRegistSeCode: "",
                        ersrRegistSeNm: "정상",
                        ersrRegistDe: "",
                        registDetailCode: "01",
                        dsplvl: "2497",
                        useStrnghldLegaldongCode: "1168010100",
                        useStrnghldAdstrdCode: "1168010100",
                        useStrnghldMntn: "0",
                        useStrnghldLnbr: "123",
                        useStrnghldHo: "1002",
                        useStrnghldAdresNm: "역삼동",
                        useStrnghldRoadNmCode: "116804100001",
                        usgsrhldUndgrndBuldSeCode: "0",
                        useStrnghldBuldMainNo: "123",
                        useStrnghldBuldSubNo: "0",
                        usgsrhldAdresFull: "서울특별시 강남구 테헤란로 123 (역삼동)",
                        mberSeCode: "01",
                        mberNm: "홍길동",
                        mberSeNo: "800101-1234567",
                        telno: "010-1234-5678",
                        ownerLegaldongCode: "1168010100",
                        ownerAdstrdCode: "1168010100",
                        ownerMntn: "0",
                        ownerLnbr: "123",
                        ownerHo: "1002",
                        ownerAdresNm: "역삼동",
                        ownerRoadNmCode: "116804100001",
                        ownerUndgrndBuldSeCode: "0",
                        ownerBuldMainNo: "123",
                        ownerBuldSubNo: "0",
                        ownerAdresFull: "서울특별시 강남구 테헤란로 123 (역삼동) 101동 1002호",
                        aftrVhrno: "",
                        useFuelCode: "G",
                        prposSeCode: "B",
                        mtrsFomNm: "G2.5 GDI",
                        frntVhrno: "",
                        vhrno: "12가3456",
                        vin: "KMHCT41CBEU123456",
                        cnm: "쏘나타 DN8 2.5 가솔린",
                        vhcleTotWt: "1755",
                        caagEndde: "20341231",
                        changeDe: "20240301",
                        vhctyAsortCode: "A01",
                        vhctyTyCode: "M02",
                        vhctySeCode: "S01",
                        mxmmLdg: "",
                        vhctyAsortNm: "승용",
                        vhctyTyNm: "중형",
                        vhctySeNm: "승용차",
                        frstRegistDe: "20210315",
                        fomNm: "DN8",
                        acqsDe: "20210310",
                        acqsEndDe: "",
                        yblMd: "202102",
                        transrRegistDe: "",
                        spcfRegistSttusCode: "",
                        colorNm: "검정",
                        mrtgCo: "0",
                        seizrCo: "0",
                        stmdCo: "0",
                        nmplCsdyAt: "N",
                        nmplCsdyRemnrDe: "",
                        originSeCode: "01",
                        nmplStndrdCode: "01",
                        acqsAmount: "28500000",
                        insptValidPdBgnde: "20240301",
                        insptValidPdEndde: "20250228",
                        useStrnghldGrcCode: "06234",
                        tkcarPscapCo: "5",
                        spmnno: "DN82021001",
                        trvlDstnc: "45320",
                        frstRegistRqrcno: "2021031500001",
                        vlntErsrPrvntcNticeDe: "",
                        registInsttNm: "서울강남구청",
                        processImprtyResnCode: "",
                        processImprtyResnDtls: "",
                        cbdLt: "4900",
                        cbdBt: "1860",
                        cbdHg: "1445",
                        frstMxmmLdg: "",
                        fuelCnsmpRt: "11.2",
                        elctyCmpndFuelCnsmpRt: ""
                    },
                    ledgerInfo: {
                        cntcResultCode: "00",
                        cntcResultDtls: "정상",
                        ledgerGroupNo: "1234567890",
                        ledgerIndvdlzNo: "001",
                        vhmno: "V202103150001",
                        vhrno: "12가3456",
                        vin: "KMHCT41CBEU123456",
                        vhctyAsortCode: "A01",
                        vhctyAsortNm: "승용",
                        cnm: "쏘나타 DN8 2.5 가솔린",
                        colorCode: "01",
                        colorNm: "검정",
                        nmplStndrdCode: "01",
                        nmplStndrdNm: "일반(소형)",
                        prposSeCode: "B",
                        prposSeNm: "비사업용",
                        mtrsFomNm: "G2.5 GDI",
                        fomNm: "DN8",
                        acqsAmount: "28500000",
                        registDetailCode: "01",
                        registDetailNm: "신규등록",
                        frstRegistDe: "20210315",
                        caagEndde: "20341231",
                        prye: "2021",
                        spmnno1: "DN82021001",
                        spmnno2: "",
                        yblMd: "20210201",
                        trvlDstnc: "45320",
                        insptValidPdBgnde: "20240301",
                        insptValidPdEndde: "20250228",
                        chckValidPdBgnde: "20231101",
                        chckValidPdEndde: "20241031",
                        registReqstSeNm: "신규등록",
                        frstRegistRqrcno: "2021031500001",
                        nmplCsdyRemnrDe: "",
                        nmplCsdyAt: "N",
                        bssUsePd: "",
                        octhtErsrPrvntcNticeDe: "",
                        ersrRegistDe: "",
                        ersrRegistSeCode: "",
                        ersrRegistSeNm: "정상",
                        mrtgcnt: "0",
                        vhclecnt: "0",
                        stmdcnt: "0",
                        adres1: "11000",
                        adresNm1: "서울특별시 강남구 테헤란로 123 (역삼동)",
                        adres: "11000",
                        adresNm: "서울특별시 강남구 테헤란로 123 (역삼동) 101동 1002호",
                        indvdlBsnmAt: "1",
                        telno: "010-1234-5678",
                        mberNm: "홍길동",
                        mberSeCode: "01",
                        mberSeNo: "800101-1234567",
                        taxxmptTrgterSeCode: "",
                        taxxmptTrgterSeCodeNm: "",
                        cntMatter: "",
                        emdNm: "역삼동",
                        prvntccnt: "0",
                        xportFlflAtSttemntDe: "",
                        partnRqrcno: "",
                        record: [
                            {
                                mainchk: "Y",
                                changeJobSeCode: "01",
                                mainno: "001",
                                subno: "001",
                                dtls: "신규등록 - 차량번호: 12가3456, 소유자: 홍길동",
                                rqrcno: "2021031500001",
                                vhmno: "V202103150001",
                                ledgerGroupNo: "1234567890",
                                ledgerIndvdlzNo: "001",
                                gubunNm: "신규",
                                changeDe: "20210315",
                                detailSn: "001",
                                flag: "N"
                            },
                            {
                                mainchk: "N",
                                changeJobSeCode: "02",
                                mainno: "001",
                                subno: "002",
                                dtls: "주소변경 - 이전: 서울특별시 강남구 역삼동 123 -> 변경: 서울특별시 강남구 테헤란로 123",
                                rqrcno: "2022012000001",
                                vhmno: "V202103150001",
                                ledgerGroupNo: "1234567890",
                                ledgerIndvdlzNo: "001",
                                gubunNm: "변경",
                                changeDe: "20220120",
                                detailSn: "002",
                                flag: "N"
                            }
                        ]
                    }
                };
            },

            /**
             * 샘플 데이터 2: 등록원부 조회 (변경 이력 포함)
             */
            getSampleData2: function() {
                return {
                    cntcResultCode: "00",
                    cntcResultDtls: "정상",
                    ledgerGroupNo: "9876543210",
                    ledgerIndvdlzNo: "002",
                    vhmno: "V201909200002",
                    vhrno: "34나5678",
                    vin: "KNAGT811ABV567890",
                    vhctyAsortCode: "A01",
                    vhctyAsortNm: "승용",
                    cnm: "K5 DL3 2.0 가솔린",
                    colorCode: "02",
                    colorNm: "흰색",
                    nmplStndrdCode: "02",
                    nmplStndrdNm: "일반(중형)",
                    prposSeCode: "B",
                    prposSeNm: "비사업용",
                    mtrsFomNm: "G2.0 MPI",
                    fomNm: "DL3",
                    acqsAmount: "22000000",
                    registDetailCode: "01",
                    registDetailNm: "신규등록",
                    frstRegistDe: "20190920",
                    caagEndde: "20321231",
                    prye: "2019",
                    spmnno1: "DL32019002",
                    spmnno2: "LPG2021001",
                    yblMd: "20190801",
                    trvlDstnc: "89540",
                    insptValidPdBgnde: "20240801",
                    insptValidPdEndde: "20250731",
                    chckValidPdBgnde: "20230901",
                    chckValidPdEndde: "20240831",
                    registReqstSeNm: "신규등록",
                    frstRegistRqrcno: "2019092000002",
                    nmplCsdyRemnrDe: "",
                    nmplCsdyAt: "N",
                    bssUsePd: "",
                    octhtErsrPrvntcNticeDe: "",
                    ersrRegistDe: "",
                    ersrRegistSeCode: "",
                    ersrRegistSeNm: "정상",
                    mrtgcnt: "0",
                    vhclecnt: "0",
                    stmdcnt: "1",
                    adres1: "26000",
                    adresNm1: "부산광역시 해운대구 센텀중앙로 78 (우동)",
                    adres: "26000",
                    adresNm: "부산광역시 해운대구 센텀중앙로 78 (우동) 201동 505호",
                    indvdlBsnmAt: "1",
                    telno: "010-9876-5432",
                    mberNm: "김철수",
                    mberSeCode: "01",
                    mberSeNo: "750515-1234567",
                    taxxmptTrgterSeCode: "",
                    taxxmptTrgterSeCodeNm: "",
                    cntMatter: "",
                    emdNm: "우동",
                    prvntccnt: "0",
                    xportFlflAtSttemntDe: "",
                    partnRqrcno: "",
                    record: [
                        {
                            mainchk: "Y",
                            changeJobSeCode: "01",
                            mainno: "001",
                            subno: "001",
                            dtls: "신규등록 - 차량번호: 34나5678, 소유자: 김철수",
                            rqrcno: "2019092000002",
                            vhmno: "V201909200002",
                            ledgerGroupNo: "9876543210",
                            ledgerIndvdlzNo: "002",
                            gubunNm: "신규",
                            changeDe: "20190920",
                            detailSn: "001",
                            flag: "N"
                        },
                        {
                            mainchk: "N",
                            changeJobSeCode: "02",
                            mainno: "001",
                            subno: "002",
                            dtls: "주소변경 - 이전: 부산광역시 해운대구 해운대로 100 -> 변경: 부산광역시 해운대구 센텀중앙로 78",
                            rqrcno: "2020011500001",
                            vhmno: "V201909200002",
                            ledgerGroupNo: "9876543210",
                            ledgerIndvdlzNo: "002",
                            gubunNm: "변경",
                            changeDe: "20200115",
                            detailSn: "002",
                            flag: "N"
                        },
                        {
                            mainchk: "N",
                            changeJobSeCode: "02",
                            mainno: "001",
                            subno: "003",
                            dtls: "구조변경 - LPG 겸용 엔진으로 변경",
                            rqrcno: "2021063000003",
                            vhmno: "V201909200002",
                            ledgerGroupNo: "9876543210",
                            ledgerIndvdlzNo: "002",
                            gubunNm: "변경",
                            changeDe: "20210630",
                            detailSn: "003",
                            flag: "N"
                        },
                        {
                            mainchk: "N",
                            changeJobSeCode: "02",
                            mainno: "001",
                            subno: "004",
                            dtls: "전화번호 변경 - 이전: 010-1111-2222 -> 변경: 010-9876-5432",
                            rqrcno: "2022031000004",
                            vhmno: "V201909200002",
                            ledgerGroupNo: "9876543210",
                            ledgerIndvdlzNo: "002",
                            gubunNm: "변경",
                            changeDe: "20220310",
                            detailSn: "004",
                            flag: "N"
                        },
                        {
                            mainchk: "N",
                            changeJobSeCode: "03",
                            mainno: "001",
                            subno: "005",
                            dtls: "정기검사 합격 - 검사유효기간: 20230815 ~ 20240814",
                            rqrcno: "",
                            vhmno: "V201909200002",
                            ledgerGroupNo: "9876543210",
                            ledgerIndvdlzNo: "002",
                            gubunNm: "검사",
                            changeDe: "20230815",
                            detailSn: "005",
                            flag: "N"
                        },
                        {
                            mainchk: "N",
                            changeJobSeCode: "03",
                            mainno: "001",
                            subno: "006",
                            dtls: "정기검사 합격 - 검사유효기간: 20240801 ~ 20250731",
                            rqrcno: "",
                            vhmno: "V201909200002",
                            ledgerGroupNo: "9876543210",
                            ledgerIndvdlzNo: "002",
                            gubunNm: "검사",
                            changeDe: "20240801",
                            detailSn: "006",
                            flag: "N"
                        }
                    ]
                };
            },

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

                // 모든 필드 초기화
                $(".basicField").hide();
                $(".ledgerField").hide();

                // 조회 구분에 따른 필드 표시
                if (inqryType === "integrated" || inqryType === "basic") {
                    $(".basicField").show();
                }

                if (inqryType === "ledger") {
                    $(".ledgerField").show();
                }
            },

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

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

                // 조회 타입에 따라 처리
                if (inqryType === "integrated") {
                    self.callIntegratedApi();
                } else if (inqryType === "basic") {
                    self.callBasicApi();
                } else if (inqryType === "ledger") {
                    self.callLedgerApi();
                }
            },

            /**
             * 통합 조회 API 호출
             */
            callIntegratedApi: 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/getIntegratedInfo.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.displayIntegratedResult(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 호출
             */
            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($("#vhrno").val());
                var cpttrNm = $.trim($("#cpttrNm").val());
                var cpttrIhidnum = $.trim($("#cpttrIhidnum").val());

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

                if (cpttrNm) {
                    params.CPTTR_NM = cpttrNm;
                }

                if (cpttrIhidnum) {
                    params.CPTTR_IHIDNUM = cpttrIhidnum;
                }

                $.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>');
                    }
                });
            },

            /**
             * 통합 조회 결과 표시
             */
            displayIntegratedResult: function(data) {
                if (!data || (!data.basicInfo && !data.ledgerInfo)) {
                    $("#resultContent").html('<div class="result-empty">조회된 데이터가 없습니다.</div>');
                    return;
                }

                var html = '';

                if (data.basicInfo) {
                    html += this.getBasicInfoHtml(data.basicInfo);
                }

                if (data.ledgerInfo) {
                    html += this.getLedgerInfoHtml(data.ledgerInfo);
                }

                $("#resultContent").html(html);
            },

            /**
             * 기본사항 조회 결과 표시
             */
            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() {
                    $("#vhrno").val("");
                    $("#levyStdde").val("${dateUtil:getCurrentDateTime('yyyy-MM-dd')}");
                    $("#vin").val("");
                    $("#cpttrNm").val("");
                    $("#cpttrIhidnum").val("");
                    $("#resultContent").html('<div class="result-empty">조회 버튼을 클릭하여 차량 정보를 조회하세요.</div>');
                    $("#btnResultClose").hide();
                });

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

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

                // 샘플1 버튼 클릭 이벤트 (기본정보 + 등록원부)
                $("#sample1_btn").on('click', function() {
                    console.log("샘플 데이터 1 로드 (기본정보 + 등록원부)");
                    var sampleData = self.getSampleData1();
                    self.displayIntegratedResult(sampleData);
                    $("#btnResultClose").show();
                });

                // 샘플2 버튼 클릭 이벤트 (등록원부 + 변경이력)
                $("#sample2_btn").on('click', function() {
                    console.log("샘플 데이터 2 로드 (등록원부 + 변경이력)");
                    var sampleData = self.getSampleData2();
                    self.displayLedgerResult(sampleData);
                    $("#btnResultClose").show();
                });

                // 섹션 접기/펼치기 이벤트
                $("#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>
