<?= $this->extend('layouts/main') ?>

<?= $this->section('content') ?>
<style>
    th {
        font-size: 11px;
        text-align: center;
    }

    td {
        text-align: center;
    }

    #resultList tbody tr {
        cursor: pointer;
    }

    .blockUI {
        z-index: 1500 !important;
    }

    .ellipsis {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 180px;
    }

    .card-header {
        display: flex !important;
        align-items: center;
    }

    .card-header-tab {
        justify-content: flex-start !important;
    }

    .table-scroll {
        max-height: 300px;
        overflow-y: scroll;
    }

    .swal2-cancel {
        background-color: #ff0000 !important;
        color: #fff !important;
    }

    #excelList.dataTable {
        width: max-content !important;
    }

    table.dataTable td,
    table.dataTable th {
        white-space: nowrap;
    }
</style>

<h1>아파트 평면도 내역</h1>

<div class="col-md-12 col-xl-12">
    <div class="main-card mb-3 card">
        <div class="card-body">
            <ul class="nav nav-tabs">
                <li class="nav-item"><a data-bs-toggle="tab" href="#tab-eg10-0" class="active nav-link">검색</a></li>
                <li class="nav-item"><a data-bs-toggle="tab" href="#tab-eg10-1" class="nav-link">조직별 통계</a></li>
            </ul>
            <div class="tab-content">
                <div class="tab-pane active" id="tab-eg10-0" role="tabpanel">
                    <form id="frm_srch_info" method="get" onsubmit="return false;">

                        <!-- 카드 -->
                        <div class="mb-3">
                            <div class="">
                                <!-- 안내 -->
                                <div class="alert alert-warning py-2 mb-3">
                                    <small class="mb-0">
                                        단지코드/구분코드를 입력하면 <b>다른 조건은 무시</b>됩니다.
                                    </small>
                                </div>

                                <div class="row g-3 align-items-end">

                                    <!-- 지역구분 -->
                                    <div class="col-md-4">
                                        <label class="form-label mb-1">지역구분</label>
                                        <div class="row g-2">
                                            <div class="col-md-4">
                                                <select class="form-control" name="srcSido" id="srcSido">
                                                    <option value="">시/도</option>
                                                    <?php foreach ($sido as $s): ?>
                                                        <option value="<?= $s['region_cd'] ?>"><?= $s['region_nm'] ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-4">
                                                <select class="form-control" name="srcGugun" id="srcGugun">
                                                    <option value="">시/군/구</option>
                                                </select>
                                            </div>
                                            <div class="col-md-4">
                                                <select class="form-control" name="srcDong" id="srcDong">
                                                    <option value="">읍/면/동</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                    <!-- 단지코드 -->
                                    <div class="col-md-2">
                                        <label class="form-label mb-1">단지코드</label>
                                        <input type="text" class="form-control" name="hscp_no" id="hscp_no"
                                            onkeypress="hscp_no_enter(event)">
                                    </div>

                                    <!-- 사진코드 -->
                                    <div class="col-md-2">
                                        <label class="form-label mb-1">구분코드</label>
                                        <input type="text" class="form-control" name="part_no" id="part_no" value="" />
                                    </div>

                                    <!-- 단지명 -->
                                    <div class="col-md-2">
                                        <label class="form-label mb-1">단지명</label>
                                        <input type="text" class="form-control" name="rcpt_hscp_nm" id="rcpt_hscp_nm"
                                            placeholder="단지명">
                                    </div>
                                </div>
                                <div class="row g-3 align-items-end">
                                    <!-- 촬영일자 -->
                                    <div class="col-md-2">
                                        <label class="form-label mb-1">촬영일자</label>
                                        <div class="input-group">
                                            <input type="text" class="form-control" name="sdate" id="sdate" value=""
                                                placeholder="시작일">
                                            <span class="input-group-text">~</span>
                                            <input type="text" class="form-control" name="edate" id="edate" value=""
                                                placeholder="종료일">
                                        </div>
                                    </div>

                                    <!-- 방문담당 -->
                                    <div class="col-md-4">
                                        <label class="form-label mb-1">방문담당</label>
                                        <div class="row g-2">
                                            <div class="col-md-4">
                                                <select class="form-control" name="bonbu" id="bonbu">
                                                    <option value="">-본부-</option>
                                                    <?php foreach ($bonbu as $d): ?>
                                                        <option value="<?= $d['dept_sq'] ?>"><?= $d['dept_nm'] ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-4">
                                                <select class="form-control" name="team" id="team">
                                                    <option value="">-팀-</option>
                                                </select>
                                            </div>
                                            <div class="col-md-4">
                                                <select class="form-control" name="damdang" id="damdang">
                                                    <option value="">-담당자-</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="row g-3 align-items-end">
                                    <!-- 진행상태 -->
                                    <div class="col-md-6">
                                        <label class="form-label mb-1">진행상태</label>
                                        <div class="d-flex flex-wrap gap-2 align-items-center border rounded p-2">
                                            <div class="form-check me-2">
                                                <input class="form-check-input" type="checkbox" name="progress_stat_all"
                                                    value="Y" id="progress_stat_all"
                                                    onclick="progressStatAll(this, this.checked);">
                                                <label class="form-check-label" for="progress_stat_all">전체</label>
                                            </div>
                                            <?php foreach ($codes as $code): ?>
                                                <?php if ($code['category'] === "APT_GROUND_STEP"): ?>
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox" name="stat[]"
                                                            id="stat_<?= $code['cd'] ?>" value="<?= $code['cd'] ?>">
                                                        <label class="form-check-label"
                                                            for="stat_<?= $code['cd'] ?>"><?= $code['cd_nm'] ?></label>
                                                    </div>
                                                <?php endif; ?>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>

                                    <div class="col-md-1 d-grid">
                                        <label class="form-label mb-1 invisible">검색</label>
                                        <button type="button" class="btn btn-primary" id="btnSearch">
                                            <i class="pe-7s-search me-1"></i>검색
                                        </button>
                                    </div>

                                </div><!-- row -->
                            </div><!-- card-body -->
                        </div><!-- card -->
                    </form>
                </div>
                <div class="tab-pane" id="tab-eg10-1" role="tabpanel">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="card mb-3" style="max-width: 380px;">
                                <div class="card-body p-0">
                                    <div class="table-scroll">
                                        <table
                                            class="table table-sm table-hover table-striped mb-0 align-middle text-center">
                                            <thead class="table-light">
                                                <tr>
                                                    <th style="width:42px;">
                                                        <input class="form-check-input" type="checkbox" id="depChkAll">
                                                    </th>
                                                    <th>관할본부</th>
                                                    <th>방문담당</th>
                                                    <th style="width:90px;">배정건수</th>
                                                </tr>
                                            </thead>
                                            <tbody id="deptArea"></tbody>
                                        </table>
                                    </div>
                                </div>

                                <div class="card-footer d-flex justify-content-end gap-1">
                                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="printMap()">
                                        <i class="pe-7s-print"></i> 인쇄하기
                                    </button>
                                    <button type="button" class="btn btn-primary btn-sm" onclick="deptMap()">
                                        <i class="pe-7s-map-2"></i> 지도로 보기
                                    </button>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div class="card mb-3" style="max-width: 380px;">
                                <div class="card-body p-0">
                                    <div class="table-scroll">
                                        <table
                                            class="table table-sm table-hover table-striped mb-0 align-middle text-center">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>방문담당</th>
                                                    <th style="width:90px;">배정건수</th>
                                                </tr>
                                            </thead>
                                            <tbody id="statsArea"></tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>

<div class="col-md-12 col-xl-12">
    <div class="main-card mb-3 card">
        <div class="card-header d-flex align-items-center">
            <div class="d-flex align-items-center flex-wrap" style="gap:8px; flex:1;">

                <select class="form-control form-control-sm" id="bonbu2" style="width:140px;">
                    <option value="">-본부-</option>
                    <?php foreach ($bonbu as $d): ?>
                        <option value="<?= $d['dept_sq'] ?>"><?= $d['dept_nm'] ?></option>
                    <?php endforeach; ?>
                </select>

                <select class="form-control form-control-sm" id="team2" style="width:160px;">
                    <option value="">-팀-</option>
                </select>

                <select class="form-control form-control-sm" id="damdang2" style="width:160px;">
                    <option value="">-담당자-</option>
                </select>

                <button type="button" class="btn btn-sm btn-outline-primary" id="btn_part_change">
                    배정변경
                </button>
            </div>

            <div class="ml-auto">
                <button class="btn btn-sm btn-outline-secondary" id="excel-upload">
                    <i class="fa fa-fw" aria-hidden="true" title="file-excel-o"></i> 엑셀업로드
                </button>

                <button class="btn btn-sm btn-outline-success" id="excel-download">
                    <i class="fa fa-fw" aria-hidden="true" title="file-excel-o"></i> 엑셀다운로드
                </button>
            </div>
        </div>

        <div class="card-body">
            <table id="resultList" class="table table-hover table-striped table-bordered">
                <thead>
                    <th class="text-center">
                        <input type="checkbox" class="form-check-input" name="chkAll" id="chkAll" />
                    </th>
                    <th>진행상태</th>
                    <th>구분코드</th>
                    <th>단지코드</th>
                    <th>주소</th>
                    <th>단지명</th>
                    <th>평형</th>
                    <th>방문팀</th>
                    <th>담당</th>
                    <th>업로드</th>
                    <th>미리보기</th>
                    <th>다운로드</th>
                </thead>
                <tbody>
                    <!-- 여기는 비워둠: AJAX로 채움 -->
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 지도팝업  -->
<?= $this->section('modals') ?>
<div class="modal fade" id="deptMapModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">지도보기</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-0">
                <div id="dialog-deptmap-content"></div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="uploadModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">파일 업로드</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-0">
                <form id="frm_file_info" method="post" enctype="multipart/form-data" onsubmit="return false;">
                    <input type="hidden" name="rcpt_no" value="">

                    <!-- 버튼 툴바 -->
                    <div class="d-flex justify-content-end gap-2 mb-3" style="padding: 16px 10px 0 0;">
                        <button type="button" class="btn btn-primary" id="uploadPick">
                            <i class="pe-7s-up-arrow"></i> 파일선택
                        </button>

                        <button type="button" class="btn btn-success" id="btnUpload">
                            <i class="pe-7s-up-arrow"></i> 파일업로드
                        </button>

                        <button type="button" class="btn btn-danger" id="btnRemove">
                            <i class="pe-7s-less"></i> 업로드취소
                        </button>
                    </div>

                    <!-- Dropzone 영역 -->
                    <div id="myDropzone" class="dropzone border rounded-3 p-4"
                        style="max-height: 400px;overflow-y: scroll;">
                        <div class="dz-message dz-message-fixed needsclick text-center">
                            <i class="pe-7s-upload mb-2" style="font-size:42px;"></i><br>
                            <strong class="fs-6">파일을 드래그하거나 클릭해서 추가하세요</strong><br>
                        </div>
                    </div>

                </form>
            </div>
        </div>
    </div>
</div>

<div class="modal" id="previewModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">미리보기</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-0">
                <img id="imgPreview" src="" alt="미리보기" width="100%" height="500px">
                <video id="vdoPreview" controls playsinline preload="metadata"
                    style="display: none;height: 500px;width: 100%;">
                    <source id="videoSource" src="" type="video/mp4">
                    브라우저가 video 태그를 지원하지 않습니다.
                </video>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="excelModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">엑셀 업로드</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>

            </div>
            <div class="modal-body">

                <!-- 업로드 영역 -->
                <div class="d-flex align-items-center gap-3 mb-3">
                    <input type="file" id="excel" class="form-control" accept=".xlsx,.xls,.csv"
                        style="max-width: 320px;">

                    <a href="/plugin/sample/sample_ground_apt.xlsx" download="아파트평면도_샘플양식"
                        class="btn btn-outline-secondary btn-sm">
                        샘플양식 다운로드
                    </a>
                </div>

                <!-- 안내 문구 -->
                <div class="alert alert-light py-2 mb-3">
                    <ul class="mb-0 small">
                        <li>엑셀 첫 행은 헤더로 인식됩니다.</li>
                        <li>컬럼 순서 및 개수는 샘플양식과 동일해야 합니다.</li>
                    </ul>
                </div>

                <!-- 테이블 영역 -->
                <div class="table-responsive">
                    <table id="excelList"
                        class="table table-sm table-hover table-striped table-bordered align-middle text-center mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>구분코드</th>
                                <th>단지코드</th>
                                <th>법정동코드</th>
                                <th>시/도</th>
                                <th>시/군/구</th>
                                <th>읍/면/동</th>
                                <th>상세주소</th>
                                <th>단지명</th>
                                <th>구분명</th>
                                <th>평수</th>
                                <th>총동수</th>
                                <th>경도</th>
                                <th>위도</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">닫기</button>
                <button type="button" class="btn btn-primary" id="btnExcelUpload">저장</button>
            </div>
        </div>
    </div>
</div>
<?= $this->endSection() ?>

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css" />
<link href="https://unpkg.com/dropzone@6.0.0-beta.1/dist/dropzone.css" rel="stylesheet" type="text/css" />
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script defer src="/architectui/assets/js/datatable.kor.js"></script>
<script src="https://unpkg.com/dropzone@6.0.0-beta.1/dist/dropzone-min.js"></script>
<script type="text/javascript" src="https://oapi.map.naver.com/openapi/v3/maps.js?ncpKeyId=dtounkwjc5"></script>
<script type="text/javascript">

    // const tpl = document.querySelector('.my-loader-template')
    let date = new Date();
    const bonbuArr = <?= json_encode($bonbu, JSON_UNESCAPED_UNICODE); ?>;
    const teamArr = <?= json_encode($team, JSON_UNESCAPED_UNICODE); ?>;
    const userArr = <?= json_encode($user, JSON_UNESCAPED_UNICODE); ?>;

    var table;

    $(function () {

        $("#bonbu").on("change", function (e) {

            const value = e.target.value

            $("#dept_sq").empty()

            var str = "<option value=''>선택</option>"
            if (teamArr != null) {

                for (var i = 0; i < teamArr.length; i++) {
                    if (value === teamArr[i].pdept_sq) {
                        str += "<option value='" + teamArr[i].dept_sq + "'>" + teamArr[i].dept_nm + "</option>"
                    }
                }
            }

            $("#dept_sq").append(str)

        });

        $("#srcSido, #srcGugun, #srcSido2, #srcGugun2").on("change", function (e) {

            const targetId = this.id;

            const isSecond = this.id.endsWith("2");

            const params = {
                srcSido: isSecond
                    ? $("#srcSido2").val()
                    : $("#frm_srch_info [name=srcSido]").val(),

                srcGugun: isSecond
                    ? $("#srcGugun2").val()
                    : $("#frm_srch_info [name=srcGugun]").val(),
            };


            $.ajax({
                url: "/manage/areas/getAreaList",
                method: "POST",
                dataType: "json",
                data: params,
                beforeSend: function () {
                    blockUI.blockPage({
                        message: tpl
                    })
                },
                complete: function () {
                    blockUI.unblockPage()
                },
                success: function (result) {

                    switch (targetId) {
                        case "srcSido":
                            $("#srcGugun").empty()
                            var str = "";
                            str += "<option value=''>시/군/구</option>";

                            if (result.length > 0) {
                                for (var i = 0; i < result.length; i++) {
                                    str += "<option value='" + result[i]['region_cd'] + "'>" + result[i].region_nm + "</option>";
                                }
                            }

                            $("#srcGugun").append(str);
                            break;

                        case "srcGugun":
                            $("#srcDong").empty()
                            var str = "";
                            str += "<option value=''>읍/면/동</option>";

                            if (result.length > 0) {
                                for (var i = 0; i < result.length; i++) {
                                    str += "<option value='" + result[i]['region_cd'] + "'>" + result[i].region_nm + "</option>";
                                }
                            }

                            $("#srcDong").append(str);
                            break;
                    }
                }
            });
        });


        $("#bonbu, #team, #bonbu2, #team2").on("change", function (e) {
            const targetId = this.id;


            var str = "";
            if (targetId === "bonbu" || targetId === "bonbu2") {
                const dept_sq = $("#" + targetId).val();

                str += `<option value="">-팀-</option>`;
                if (teamArr.length > 0) {
                    for (var i = 0; i < teamArr.length; i++) {

                        // 이 팀이 현재 본부에 속한 팀인지 체크
                        if (String(teamArr[i].pdept_sq) === String(dept_sq)) {
                            str += `
                                <option value="${teamArr[i].dept_sq}">${teamArr[i].dept_nm}</option>
                            `;
                        }
                    }
                }

                if (targetId === "bonbu") {
                    $("#team").html(str);
                } else if (targetId === "bonbu2") {
                    $("#team2").html(str);
                }

            } else if (targetId === "team" || targetId === "team2") {
                const dept_sq = $("#" + targetId).val();

                str += `<option value="">-담당자-</option>`;
                if (userArr.length > 0) {
                    for (var i = 0; i < userArr.length; i++) {

                        // 이 팀이 현재 본부에 속한 팀인지 체크
                        if (String(userArr[i].dept_sq) === String(dept_sq)) {
                            str += `
                                <option value="${userArr[i].usr_id}">${userArr[i].usr_nm}</option>
                            `;
                        }
                    }
                }

                if (targetId === "team") {
                    $("#damdang").html(str);
                } else if (targetId === "team2") {
                    $("#damdang2").html(str);
                }
            }

        });


        table = $('#resultList').DataTable({
            language: lang_kor,

            serverSide: true,
            processing: true,
            ajax: {
                url: '/article/apt/ground/getAptLists',
                type: 'GET',
                beforeSend: function () {
                    blockUI.blockPage({
                        message: tpl
                    })
                },
                complete: function () {
                    blockUI.unblockPage()
                },
                data: function (d) {
                    d.hscp_no = $("#frm_srch_info [name=hscp_no]").val(); // 단지코드
                    d.part_no = $("#frm_srch_info [name=part_no]").val(); // 구분코드
                    d.srcSido = $("#frm_srch_info [name=srcSido]").val(); // 시|도
                    d.srcGugun = $("#frm_srch_info [name=srcGugun]").val(); // 시|군|구
                    d.srcDong = $("#frm_srch_info [name=srcDong]").val(); // 읍|면|동

                    d.rcpt_hscp_nm = $("#frm_srch_info [name=rcpt_hscp_nm]").val(); // 단지명
                    d.sdate = $("#frm_srch_info [name=sdate]").val(); // 시작일
                    d.edate = $("#frm_srch_info [name=edate]").val(); // 종료일

                    d.bonbu = $("#frm_srch_info [name=bonbu]").val(); // 본부
                    d.team = $("#frm_srch_info [name=team]").val(); // 팀
                    d.damdang = $("#frm_srch_info [name=damdang]").val(); // 담당

                    d.stat = $("#frm_srch_info input[name='stat[]']:checked")
                        .map(function () {
                            return this.value;
                        }).get(); // 진행상태

                    d.start = d.start || 0
                    d.length = d.length || 10
                },
                dataSrc: function (d) {
                    const deptList = d.widgets?.deptList;
                    const areaStats = d.widgets?.areaStats;

                    if (deptList.length > 0) {
                        var str = "";

                        for (var i = 0; i < deptList.length; i++) {
                            str += `
                                <tr>
                                    <td><input class="form-check-input depChk" type="checkbox" name="depChk[]" value="${deptList[i].dept_sq}"></td>
                                    <td>${deptList[i].bonbu_nm}</td>
                                    <td>${deptList[i].team_nm}</td>
                                    <td><span class="badge bg-primary">${deptList[i].cnt} 건</span></td>
                                </tr>
                                `;
                        }

                        $("#deptArea").html(str);
                    } else {
                        str = `
                                <tr>
                                    <td colspan="4">조회 가능한 데이터가 없습니다.</td>
                                </tr>
                                `;

                        $("#deptArea").html(str);
                    }


                    if (areaStats.length > 0) {
                        var str = "";

                        for (var i = 0; i < areaStats.length; i++) {
                            str += `
                                <tr>                                   
                                    <td>${areaStats[i].addr}</td>
                                    <td><span class="badge bg-warning">${areaStats[i].cnt} 건</span></td>
                                </tr>
                                `;
                        }

                        $("#statsArea").html(str);
                    } else {
                        str = `
                                <tr>
                                    <td colspan="2">조회 가능한 데이터가 없습니다.</td>
                                </tr>
                                `;

                        $("#statsArea").html(str);
                    }


                    return d.data;
                }
            },
            "columnDefs": [
                { className: 'text-center', targets: '_all' },
                { 'targets': '_all', "defaultContent": "" },
                // { 'className': 'text-center', 'targets': [0, 2, 3, 4] },
            ],
            columns: [
                { data: null, render: fn_chk_render, width: "50px", className: "dt-no-rowclick" },

                { data: 'apt_step', render: fn_stat_render, width: "80px", },
                { data: 'part_no', width: "80px" },
                { data: 'hscp_no', width: "100px" },
                { data: 'addr' },
                { data: 'rcpt_hscp_nm', width: "120px" },
                { data: 'pyeong_cnt', width: "80px" },
                { data: 'dept_nm', width: "80px" },
                { data: 'usr_nm', width: "50px" },
                { data: null, render: fn_btn_upload, className: "dt-no-rowclick" },
                { data: null, render: fn_btn_preview, width: "80px", className: "dt-no-rowclick" },
                { data: null, render: fn_btn_download, width: "80px", className: "dt-no-rowclick" },

            ],
            // 옵션들 예시
            paging: true,
            searching: false,
            ordering: false,
            serverSide: true,
        });

        $('#resultList tbody').on('click', 'tr', function (e) {
            if ($(e.target).closest('td.dt-no-rowclick').length) return;

            const rowData = table.row(this).data();
            if (!rowData) return;


            const rcpt_no = rowData.rcpt_no;
            const hscp_no = rowData.hscp_no;
            location.href = "<?= site_url('article/apt/ground/detail') ?>/" + rcpt_no + "/" + hscp_no;
        });

        $('#btnSearch').on('click', function () {
            table.ajax.reload()
        });

        // 엑셀업로드 click
        $("#excel-upload").on("click", function () {
            $("#excel").val("");
            $("#excelList").DataTable().clear().destroy();

            $("#excelModal").modal("show");

        });

        // 엑셀 업로드
        $("#excel").on("change", async function () {
            const file = this.files[0];
            if (!file) return;

            const bodyRows = await readExcelBodyOnly(file);
            renderExcelDataTable(bodyRows);

        });


        // 엑셀 업로드 저장
        $("#btnExcelUpload").on("click", function () {

            const dt = $("#excelList").DataTable();

            // 전체 row 데이터 (모든 페이지)
            const excelData = dt.rows().data().toArray();

            if (excelData.length === 0) {
                Swal.fire({
                    title: "업로드할 데이터가 없습니다.",
                    icon: "warning"
                });
                return;
            }

            const headers = [
                "구분코드", "단지코드", "법정동코드"
                , "시/도", "시/군/구", "읍/면/동", "상세주소"
                , "단지명", "구분명", "평수", "총동수", "경도", "위도"
            ];

            const errors = [];
            let hasError = false;
            for (let rowIdx = 0; rowIdx < excelData.length; rowIdx++) {
                const row = excelData[rowIdx];

                for (let colIdx = 0; colIdx < headers.length; colIdx++) {
                    const colName = headers[colIdx];
                    const val = row[colIdx];


                    if (val === undefined || val === null || String(val).trim() === "") {
                        Swal.fire({
                            title: `${rowIdx + 1}행 ${colName} 데이터 누락`,
                            icon: "warning"
                        });

                        hasError = true;
                        break;
                    }
                }

                if (hasError) break;
            }

            if (hasError) return;

            swal.fire({
                text: "저장 하시겠습니까?",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "예",
                cancelButtonText: "아니오",
                closeOnConfirm: false,
                closeOnCancel: true,
                confirmButtonColor: "#3085d6",
                cancelButtonColor: "#d33",
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: '/article/apt/ground/uploadExcel',
                        contentType: 'application/json;charset=UTF-8',
                        method: 'POST',
                        data: JSON.stringify({ datas: excelData }),
                        beforeSend: function () {
                            blockUI.blockPage({
                                message: tpl
                            })
                        },
                        complete: function () {
                            blockUI.unblockPage()
                        },
                        error: function (xhr, error, thrown) {
                            blockUI.unblockPage()
                            var msg = "";
                            if (xhr.responseText != null) {
                                msg = xhr.responseText
                            } else {
                                msg = "잠시후 다시 시도해 주세요."
                            }

                            Swal.fire({
                                title: msg,
                                icon: "error"
                            })
                        },
                        success: function (result) {

                            if (result.code == '0') {
                                $("#btnSearch").trigger('click')
                                $("#excelModal").modal("hide")
                                Swal.fire({
                                    title: '정상 처리되었습니다.',
                                    icon: "success"

                                })
                            } else {
                                Swal.fire({
                                    title: result.msg,
                                    icon: "error"
                                })
                            }
                        }
                    });
                }
            });


        });


        // 엑셀 다운로드 click
        $("#excel-download").on("click", function () {
            $.ajax({
                url: "/article/apt/ground/excel",
                method: "GET",
                dataType: "json",
                data: $("#frm_srch_info").serialize(),
                beforeSend: function () {
                    blockUI.blockPage({
                        message: tpl
                    })
                },
                complete: function () {
                    blockUI.unblockPage()
                },
                success: function (result) {
                    downloadExcel(result.data);
                }
            });
        });

        // 리스트 파일업로드
        $(document).on("click", ".btn-upload-photo", function (e) {
            e.stopPropagation();
            const row = $('#resultList').DataTable()
                .row($(this).closest('tr'))
                .data();

            $("#frm_file_info [name=rcpt_no]").val(row.rcpt_no);

            $("#uploadModal").modal("show");
        });

        // 미리보기
        $(document).on('click', '.btn-preview', function (e) {
            e.stopPropagation(); // 행 클릭 방지(2중 안전)
            fn_preview($(this).data('src'));
        });

        /**
         *  파일 Dropzone
         * */
        const dz = new Dropzone("#myDropzone", {
            url: "/article/apt/ground/uploadFile",
            method: "post",
            paramName: "file",
            autoProcessQueue: false,   // 자동 업로드 끄기
            uploadMultiple: false,
            parallelUploads: 1,
            maxFiles: 1,
            maxFilesize: 100,
            acceptedFiles: '.jpeg,.jpg,.JPEG,.JPG,.webp',
            addRemoveLinks: true,
            dictRemoveFile: "삭제",
            dictDefaultMessage: "파일을 여기에 드래그하거나 클릭해서 추가하세요",
            dictFallbackMessage: "브라우저가 드래그앤드롭을 지원하지 않습니다.",
            dictFileTooBig: "파일이 너무 큽니다 (최대 {{maxFilesize}}MB)",
            dictInvalidFileType: "허용되지 않은 파일 형식입니다.",
            dictResponseError: "서버 오류가 발생했습니다.",
            dictCancelUpload: "업로드 취소",
            dictRemoveFile: "삭제",
            dictMaxFilesExceeded: "더 이상 파일을 추가할 수 없습니다.",
            init: function () {
                this.on("addedfile", function (file) {

                    const ext = file.name.split('.').pop().toLowerCase();
                    // const isVideo = (ext === 'mp4' || ext === 'mpg');

                    // 동영상은 단일 업로드만 허용
                    if (this.files.length > 1) {
                        alert("파일은 1개만 업로드할 수 있습니다.");
                        this.removeFile(file);
                        return;
                    }

                    // 기존에 동영상이 있는데 다른 파일 추가 시 차단
                    // const hasVideo = this.files.some(f => {
                    //     const e = f.name.split('.').pop().toLowerCase();
                    //     return e === 'mp4' || e === 'mpg';
                    // });

                    // if (hasVideo && !isVideo) {
                    //     alert("동영상 업로드 시 다른 파일을 함께 업로드할 수 없습니다.");
                    //     this.removeFile(file);
                    // }
                });
            },
        });

        dz.on("addedfile", function (file) {
            const removeBtn = file.previewElement.querySelector(".dz-remove");

            if (removeBtn) {
                removeBtn.classList.add(
                    "btn",
                    "btn-sm",
                    "btn-outline-danger",
                    "mt-2"
                );
            }
        });


        let isFormDataAppended = false;
        let lastUploadResult = null;   // 응답 저장용
        let hadError = false;
        dz.on("sending", function (file, xhr, formData) {
            if (isFormDataAppended) return;

            formData.append("rcpt_no", $("#frm_file_info [name=rcpt_no]").val());

            isFormDataAppended = true;
        });

        dz.on("queuecomplete", function () {
            table.ajax.reload()
        });

        dz.on("successmultiple", function () {
            isFormDataAppended = false;
        });
        dz.on("errormultiple", function () {
            isFormDataAppended = false;
        });
        dz.on("canceledmultiple", function () {
            isFormDataAppended = false;
        });
        dz.on("processingmultiple", function () { });

        // 업로드파일 선택
        $("#uploadPick").on("click", function () {
            isFormDataAppended = false;
            dz.hiddenFileInput.click();
        });

        $("#btnUpload").on("click", function () {
            dz.processQueue(); // 업로드 실행
            isFormDataAppended = false;
        });

        $("#btnRemove").on("click", function () {
            const files = dz.getAcceptedFiles();

            if (files.length === 0) {
                alert("삭제할 파일이 없습니다.");
                return;
            }

            files.forEach(function (file) {
                dz.removeFile(file);
            });
        });


        $(document).on('change', '#chkAll', function () {
            const checked = this.checked;

            $(table.rows({ page: 'current' }).nodes())
                .find('input.row-chk')
                .prop('checked', checked);
        });

        $(document).on('change', '#resultList tbody input.row-chk', function () {
            const $rows = $(table.rows({ page: 'current' }).nodes());
            const total = $rows.find('input.row-chk').length;
            const checkedCnt = $rows.find('input.row-chk:checked').length;

            $('#chkAll').prop('checked', total > 0 && total === checkedCnt);
        });


        // 전체 선택
        $(document).on('change', '#depChkAll', function () {
            $('.depChk').prop('checked', this.checked);
        });

        // 개별 체크 시 전체 체크 동기화
        $(document).on('change', '.depChk', function () {
            const total = $('.depChk').length;
            const checked = $('.depChk:checked').length;
            $('#depChkAll').prop('checked', total === checked);
        });

        table.on('draw', function () {
            $('#chkAll').prop('checked', false);
        });


        // 배정변경 click
        $("#btn_part_change").on("click", function () {
            var arr = new Array();
            const b = $("#bonbu2").val();
            const t = $("#team2").val();
            const d = $("#damdang2").val();

            $('#resultList tbody .row-chk:checked').each(function () {
                const rowData = table.row($(this).closest('tr')).data();
                arr.push(rowData);
            });

            if (arr.length === 0) {
                Swal.fire({
                    title: "선택된 데이터가 없습니다.",
                    icon: "warning"
                });

                return;
            }

            if (t === "") {
                Swal.fire({
                    title: "팀을 선택해 주요.",
                    icon: "warning"
                });

                return;
            }

            if (d === "") {
                Swal.fire({
                    title: "담당자를 선택해 주세요.",
                    icon: "warning"
                });

                return;
            }


            swal.fire({
                text: "저장 하시겠습니까?",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "예",
                cancelButtonText: "아니오",
                closeOnConfirm: false,
                closeOnCancel: true,
                confirmButtonColor: "#3085d6",
                cancelButtonColor: "#d33",
            }).then((result) => {
                if (result.isConfirmed) {
                    const param = {
                        'bonbu': b,
                        'team': t,
                        'usr_id': d,
                        'rows': JSON.stringify(arr),
                    };

                    $.ajax({
                        url: '/article/apt/ground/chgAptDamdang',
                        contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
                        method: 'POST',
                        data: param,
                        beforeSend: function () {
                            blockUI.blockPage({
                                message: tpl
                            })
                        },
                        complete: function () {
                            blockUI.unblockPage()
                        },
                        error: function (xhr, error, thrown) {
                            blockUI.unblockPage()
                            var msg = "";
                            if (xhr.responseText != null) {
                                msg = xhr.responseText
                            } else {
                                msg = "잠시후 다시 시도해 주세요."
                            }

                            Swal.fire({
                                title: msg,
                                icon: "error"
                            })
                        },
                        success: function (result) {

                            if (result.code == '0') {
                                $("#btnSearch").trigger('click')
                                Swal.fire({
                                    title: '정상 처리되었습니다.',
                                    icon: "success"

                                })
                            } else {
                                Swal.fire({
                                    title: result.msg,
                                    icon: "error"
                                })
                            }
                        }
                    });
                }
            });

        });

    });

    async function readExcelBodyOnly(file) {
        const data = await file.arrayBuffer();
        const wb = XLSX.read(data, { type: "array" });
        const ws = wb.Sheets[wb.SheetNames[0]];

        const rows2d = XLSX.utils.sheet_to_json(ws, {
            header: 1,
            defval: "",
            raw: false
        });

        // 첫 줄(엑셀 헤더) 제거 + 빈 행 제거
        return rows2d
            .slice(1)
            .filter(r => r.some(v => String(v).trim() !== ""));
    }

    function renderExcelDataTable(data2d) {
        // 이미 DataTable이 있으면 파괴 후 재생성(컬럼 구조가 바뀔 수 있으니)
        if ($.fn.DataTable.isDataTable("#excelList")) {
            $("#excelList").DataTable().clear().destroy();
        }

        excelTbl = $("#excelList").DataTable({
            language: lang_kor,
            columnDefs: [
                { className: 'text-center dt-nowrap', targets: '_all' },
            ],
            data: data2d,
            searching: false,
            ordering: false,
            destroy: true,
            deferRender: true,
            pageLength: 10,
            lengthMenu: [10, 25, 50, 100],
            scrollX: true,
            autoWidth: true,
        });
    }

    function hscp_no_enter(event) {
        if (event.keyCode == 13) {
            table.ajax.reload()
        }
    }


    function fn_chk_render(data, type, row, meta) {
        const rowIndex = meta.row;
        var str = "";

        str = `<input class="form-check-input row-chk" type="checkbox" id="row_${rowIndex}" value="Y">`;


        return str;
    }

    function fn_stat_render(data, type, row) {
        var str = "";

        switch (row.apt_step) {
            case 'S01':
                str = '미촬영';
                break;

            case 'S02':
                str = '사진촬영';
                break;

            case 'S03':
                str = '영상촬영';
                break;

            case 'S04':
                str = '촬영완료';
                break;

            case 'S05':
                str = '검수완료';
                break;

            case 'S06':
                str = '전송완료 ';
                break;
        }

        return str;
    }

    // 다운로드 btn
    function fn_btn_upload(data, type, row) {
        var str = "";

        str = `
            <button class="btn btn-sm btn-outline-focus btn-upload-photo" type="button">
                <i class="fa fa-fw" aria-hidden="true" title="Copy to use file-image-o"></i> 파일 업로드
            </button>
            `;

        return str;
    }

    // 미리보기 btn
    function fn_btn_preview(data, type, row) {
        if (row.pho_no == null) return '';

        let src = (row.cloud_upload_yn == "Y")
            ? '<?= NCLOUD_OBJECT_STORAGE_URL ?>' + row.file_path + row.filenm_up
            : row.file_path + row.filenm_up;

        return `
                <button type="button" class="btn btn-sm btn-link p-0 btn-preview" data-src="${src}">
                미리보기
                </button>
                `;
    }

    // 다운로드 btn
    function fn_btn_download(data, type, row) {

        var str = "";

        if (row.pho_no != null) {
            var src = "";
            if (row.cloud_upload_yn == "Y") {
                src = '<?= NCLOUD_OBJECT_STORAGE_URL ?>' + '' + row.file_path + '' + row.filenm_up;
            } else {
                src = row.file_path + '' + row.filenm_up;
            }

            str = `<a href="${src}" download="${row.filenm}">다운로드</a>`;
        }



        return str;
    }

    // 체크된 row 확인
    function getCheckedRowsData() {
        const checkedData = [];

        $('#resultList tbody input.row-chk:checked').each(function () {
            const tr = $(this).closest('tr');
            const rowData = table.row(tr).data();
            checkedData.push(rowData);
        });

        return checkedData;
    }

    // 단지정보저장
    function fn_save_info(row, idx) {

        const target = $("#video_target_" + idx).val();
        console.log(target)
        if (target == "") {
            Swal.fire({
                title: "영상대상을 선택해 주세요.",
                icon: "warning"
            })

            return;
        }


        swal.fire({
            text: "저장 하시겠습니까?",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "예",
            cancelButtonText: "아니오",
            closeOnConfirm: false,
            closeOnCancel: true,
            confirmButtonColor: "#3085d6",
            cancelButtonColor: "#d33",
        }).then((result) => {
            if (result.isConfirmed) {
                const param = {
                    'video_target': target,
                    'memo': $("#memo_" + idx).val(),
                    'rcpt_no': row.rcpt_no
                };

                $.ajax({
                    url: '/article/apt/saveAptMemo',
                    contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
                    method: 'POST',
                    data: param,
                    beforeSend: function () {
                        blockUI.blockPage({
                            message: tpl
                        })
                    },
                    complete: function () {
                        blockUI.unblockPage()
                    },
                    error: function (xhr, error, thrown) {
                        blockUI.unblockPage()
                        var msg = "";
                        if (xhr.responseText != null) {
                            msg = xhr.responseText
                        } else {
                            msg = "잠시후 다시 시도해 주세요."
                        }

                        Swal.fire({
                            title: msg,
                            icon: "error"
                        })
                    },
                    success: function (result) {

                        if (result.code == '0') {
                            $("#btnSearch").trigger('click')
                            Swal.fire({
                                title: '정상 처리되었습니다.',
                                icon: "success"

                            })
                        } else {
                            Swal.fire({
                                title: result.msg,
                                icon: "error"
                            })
                        }
                    }
                });
            }
        });
    }


    // 인쇄하기
    function printMap() {

        var data = $('input[name="depChk[]"]').serialize();
        var usr_id = $('input[name="usr_id"]').serialize();

        if (data == '') {
            alert('팀을 선택해주세요');
            return;
        }

        var url = '/article/apt/ground/print?' + data;
        window.open(url, '', '');
    }

    function deptMap() {
        const data = $('input[name="depChk[]"]:checked').serialize();

        if (!data) {
            alert('팀을 선택해주세요');
            return;
        }

        const url = '/article/apt/ground/print?' + data;

        $('#dialog-deptmap-content').html(
            `<iframe style="border:0;width:100%;height:650px;" src="${url}"></iframe>`
        );

        const modal = new bootstrap.Modal(document.getElementById('deptMapModal'));
        modal.show();
    }

    // 엑셀 다운로드
    function downloadExcel(data) {
        const ws = XLSX.utils.json_to_sheet(data);
        ws['!cols'] = [
            { wpx: 80 },
            { wpx: 80 },
            { wpx: 80 },
            { wpx: 80 },
            { wpx: 80 },
            { wpx: 80 },
            { wpx: 80 },
            { wpx: 80 },
            { wpx: 80 },
            { wpx: 80 },
            { wpx: 80 },
            { wpx: 80 },
            { wpx: 80 },
            { wpx: 80 },
        ];

        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

        const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });

        const blob = new Blob([wbout], { type: 'application/octet-stream' });

        const link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.download = "아파트_평면도_내역" + getDateTimeString() + ".xlsx";
        link.click();
        URL.revokeObjectURL(link.href);
    }


    function getDateTimeString() {
        const d = new Date();
        const yyyy = d.getFullYear();
        const mm = String(d.getMonth() + 1).padStart(2, '0');
        const dd = String(d.getDate()).padStart(2, '0');
        const hh = String(d.getHours()).padStart(2, '0');
        const mi = String(d.getMinutes()).padStart(2, '0');
        const ss = String(d.getSeconds()).padStart(2, '0');
        return `${yyyy}${mm}${dd}${hh}${mi}${ss}`;
    }

    function extractCode(code) {

        var codeArr = new Array();

        if (codes.length) {

            for (var i = 0; i < codes.length; i++) {

                if (code === codes[i].category) {
                    codeArr.push(codes[i]);
                }

            }

        }

        return codeArr;
    }


    // 이미지 프리뷰
    function fn_preview(src) {
        const $img = $('#imgPreview');

        // 이미지 표시
        $img.attr('src', src).show();

        $('#previewTitle').text('이미지 미리보기');


        const modal = new bootstrap.Modal(document.getElementById('previewModal'));
        modal.show();
    }
</script>
<?= $this->endSection() ?>