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

<?= $this->section('content') ?>
<style>
    . th {
        padding: 0 10px;
        height: 27px;
        border: solid 1px #d8d9de;
        background-color: #eff0f4;
        letter-spacing: -1px;
        font-weight: normal;
        color: #5a5f69;
        text-align: left;
    }

    .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;
    }

    #aptList tbody tr {
        cursor: pointer;
    }

    #aptList tbody tr:hover td {
        background-color: #9DC4E6;
    }

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

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

    .dropzone {
        min-height: 260px;
        background-color: #fafbfc;
    }

    .dropzone:hover {
        background-color: #f4f6f8;
    }

    #myDropzone {
        position: relative;
        padding-top: 110px;
        /* 메시지 영역 높이만큼 */
    }

    #uploadModal .modal-dialog {
        max-width: 1140px;
        /* modal-xl */
    }

    #uploadModal .modal-content {
        height: 450px;
        max-height: 450px;
    }
</style>

<div class="col-md-12 col-xl-12">
    <div class="col-lg-12">

        <div class="main-card mb-3 card">
            <div class="card-body">
                <h5 class="card-title">단지 정보</h5>
                <table class="table table-bordered table-sm  apt-info-table">
                    <colgroup>
                        <col width="100" />
                        <col width="300" />
                        <col width="100" />
                        <col width="300" />
                    </colgroup>

                    <tr>
                        <th>단지코드</th>
                        <td><?= esc($apt['hscp_no'] ?? '') ?></td>
                        <th>구분코드</th>
                        <td><?= esc($apt['part_no'] ?? '') ?></td>
                    </tr>
                    <tr>
                        <th>주소</th>
                        <td><?= esc($apt['addr'] ?? '') ?></td>
                        <th>지번</th>
                        <td><?= esc($apt['addr2'] ?? '') ?></td>
                    </tr>
                    <tr>
                        <th>단지명</th>
                        <td><?= esc($apt['rcpt_hscp_nm'] ?? '') ?></td>
                        <th>평형</th>
                        <td><?= esc($apt['pyeong_cnt'] ?? '') ?></td>
                    </tr>
                    <tr>
                        <th>단지유형</th>
                        <td><?= esc($apt['apt_cate_nm'] ?? '') ?></td>
                        <th>메모</th>
                        <td>
                            <div class="row g-2 align-items-center">
                                <div class="col-md-9">
                                    <input class="form-control" type="text" id="memo"
                                        value="<?= esc($apt['memo'] ?? '') ?>" />
                                </div>
                                <div class="col-md-3 text-end">
                                    <button type="button" class="btn btn-outline-focus"
                                        onclick="saveMemo('<?= esc($apt['rcpt_no'] ?? '') ?>')">저장</button>
                                </div>
                            </div>
                        </td>
                    </tr>
                </table>
            </div>
        </div>

        <div class="main-card mb-3 card">
            <div class="card-body">
                <h5 class="card-title">담당자 정보</h5>
                <table class="table table-bordered table-sm  apt-info-table">
                    <colgroup>
                        <col width="10%" />
                        <col width="auto" />
                        <col width="10%" />
                        <col width="auto" />
                        <col width="10%" />
                        <col width="auto" />
                        <col width="15%" />
                    </colgroup>
                    <tr>
                        <th style="text-align:center">관할본부</th>
                        <td style="text-align:center">
                            <select class="form-select" name="bonbu" id="bonbu">
                                <option value="">선택</option>
                                <?php foreach (($bonbu ?? []) as $d): ?>
                                    <option value="<?= esc($d['dept_sq']) ?>" <?= (string) ($apt['bonbu'] ?? '') === (string) $d['dept_sq'] ? 'selected' : '' ?>>
                                        <?= esc($d['dept_nm']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </td>

                        <th style="text-align:center">담당팀</th>
                        <td style="text-align:center">
                            <select class="form-select" name="team" id="team">
                                <option value="">선택</option>
                                <?php foreach (($team ?? []) as $d): ?>
                                    <?php if ((string) ($apt['bonbu'] ?? '') === (string) ($d['pdept_sq'] ?? '')): ?>
                                        <option value="<?= esc($d['dept_sq']) ?>" <?= (string) ($apt['dept_sq'] ?? '') === (string) $d['dept_sq'] ? 'selected' : '' ?>>
                                            <?= esc($d['dept_nm']) ?>
                                        </option>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </select>
                        </td>

                        <th style="text-align:center">담당자</th>
                        <td style="text-align:center">
                            <select class="form-select" name="user" id="user">
                                <option value="">선택</option>
                                <?php foreach (($user ?? []) as $d): ?>
                                    <?php if ((string) ($apt['dept_sq'] ?? '') === (string) ($d['dept_sq'] ?? '')): ?>
                                        <option value="<?= esc($d['usr_id']) ?>" <?= (string) ($apt['charger'] ?? '') === (string) $d['usr_id'] ? 'selected' : '' ?>>
                                            <?= esc($d['usr_nm']) ?>
                                        </option>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </select>
                        </td>

                        <td style="text-align:center">
                            <button type="button" class="btn btn-sm btn-outline-focus"
                                onclick="saveKeeper('<?= esc($apt['rcpt_no'] ?? '') ?>')">저장</button>
                        </td>
                    </tr>
                </table>
            </div>
        </div>

        <div class="main-card mb-3 card">
            <div class="card-body">
                <h5 class="card-title">단지 상태 정보</h5>
                <table class="table table-bordered table-sm  apt-info-table">
                    <colgroup>
                        <col width="20%" />
                        <col width="20%" />
                        <col width="20%" />
                        <col width="20%" />
                        <col width="20%" />
                    </colgroup>
                    <tr>
                        <th rowspan="2" style="text-align:center">상태내역</th>
                        <th style="text-align:center">미촬영</th>
                        <th style="text-align:center">수급불가</th>
                        <th style="text-align:center">촬영</th>
                        <th style="text-align:center">전송완료</th>
                    </tr>
                    <tr>
                        <td style="text-align:center; height: 50px;">
                            <b></b>
                        </td>
                        <td style="text-align:center;color: #ff0000;">
                            <b>
                                <?php if (in_array($apt['apt_step'], ['S02'])) {
                                    echo $apt['supply_no_tm'];
                                } ?>
                            </b>
                        </td>
                        <td style="text-align:center;color: #ff0000;">
                            <b>
                                <?php if (in_array($apt['apt_step'], ['S03', 'S04'])) {
                                    echo $apt['insert_tm'];
                                } ?>
                            </b>
                        </td>
                        <td style="text-align:center;color: #ff0000;">
                            <b>
                                <?php if (in_array($apt['apt_step'], ['S04'])) {
                                    echo $apt['send_end_tm'];
                                } ?>
                            </b>
                        </td>
                    </tr>
                    <tr>
                        <th style="text-align:center">상태 변경</th>
                        <td style="text-align:center">
                            <button class="btn btn-sm btn-outline-primary"
                                onclick="statusChange('<?= esc($apt['rcpt_no'] ?? '') ?>', 'phoX')">
                                미촬영
                            </button>
                        </td>
                        <td style="text-align:center">
                            <button class="btn btn-sm btn-outline-primary"
                                onclick="statusChange('<?= esc($apt['rcpt_no'] ?? '') ?>', 'suppN')">
                                수급불가
                            </button>
                        </td>
                        <td style="text-align:center">
                            <button class="btn btn-sm btn-outline-primary"
                                onclick="statusChange('<?= esc($apt['rcpt_no'] ?? '') ?>', 'phoY')">
                                촬영
                            </button>
                        </td>
                        <td style="text-align:center">
                            <button class="btn btn-sm btn-outline-primary"
                                onclick="statusChange('<?= esc($apt['rcpt_no'] ?? '') ?>', 'sendE')">
                                전송완료
                            </button>
                        </td>
                    </tr>
                </table>
            </div>
        </div>

        <div class="main-card mb-3 card">
            <div class="card-body">
                <h5 class="card-title">단지 위치</h5>
                <table class="table table-bordered table-sm apt-info-table">
                    <colgroup>
                        <col width="25%">
                        <col width="45%">
                        <col width="30%">
                    </colgroup>

                    <tr>
                        <td colspan="2" style="padding:5px;">
                            <div id="mapArea" style="width:100%;height:250px;"></div>
                        </td>

                        <td rowspan="2" style="vertical-align: top; padding:10px;">
                            <h5 class="mb-2">단지 특이사항</h5>

                            <textarea name="note" id="note" class="form-control mb-2"
                                style="height: 220px;resize: none;"><?= esc($apt['note'] ?? '') ?></textarea>

                            <div class="d-flex align-items-center">
                                <div class="ms-auto">
                                    <button class="btn btn-sm btn-primary"
                                        onclick="saveNote('<?= esc($apt['rcpt_no'] ?? '') ?>')">
                                        저장
                                    </button>
                                </div>
                            </div>
                        </td>
                    </tr>

                    <tr>
                        <th class="text-center align-middle">지도 좌표 수정</th>
                        <td>
                            <div class="d-flex align-items-center gap-2 flex-wrap">
                                <span>위도</span>
                                <input type="text" id="rcpt_y" name="rcpt_y" class="form-control form-control-sm"
                                    style="width:120px;" value="<?= esc($apt['rcpt_y'] ?? '') ?>">

                                <span>경도</span>
                                <input type="text" id="rcpt_x" name="rcpt_x" class="form-control form-control-sm"
                                    style="width:120px;" value="<?= esc($apt['rcpt_x'] ?? '') ?>">

                                <button class="btn btn-sm btn-outline-secondary ms-auto"
                                    onclick="saveCoordinate('<?= esc($apt['rcpt_no'] ?? '') ?>')">
                                    저장
                                </button>
                            </div>
                        </td>
                    </tr>
                </table>
            </div>
        </div>

        <div class="main-card mb-3 card">
            <div class="card-body">
                <h5 class="card-title">동일 단지 정보</h5>
                <table class="table table-bordered table-sm apt-info-table" id="aptList">
                    <tr>
                        <th style="text-align:center">진행상태</th>
                        <th style="text-align:center">구분코드</th>
                        <th style="text-align:center">단지코드</th>
                        <th style="text-align:center">주소</th>
                        <th style="text-align:center">단지명</th>
                        <th style="text-align:center">평형</th>
                        <th style="text-align:center">방문팀</th>
                        <th style="text-align:center">담당</th>
                        <th style="text-align:center">촬영일자</th>
                        <th style="text-align:center">업로드</th>
                        <th style="text-align:center">미리보기</th>
                        <th style="text-align:center">다운로드</th>
                    </tr>
                    <tbody>
                        <?php if (empty($rdata)): ?>
                            <tr>
                                <td colspan="12" style="text-align: center;height: 50px;">동일단지 데이터가 없습니다.</td>
                            </tr>
                        <?php else: ?>
                            <?php
                            foreach ($rdata as $row):
                                switch ($row['apt_step']) {
                                    case "S01":
                                        $status = '미촬영';
                                        break;
                                    case "S02":
                                        $status = '수급불가';
                                        break;
                                    case "S03":
                                        $status = '촬영';
                                        break;
                                    case "S04":
                                        $status = '전송완료';
                                        break;
                                    default:
                                        $status = '미촬영';
                                        break;
                                }

                                ?>
                                <tr data-rcpt-no="<?= $row['rcpt_no'] ?>" data-hscp-no="<?= $row['hscp_no'] ?>"
                                    onmouseover="this.style.backgroundColor='#9DC4E6'"
                                    onmouseout="this.style.backgroundColor=''">
                                    <td style="text-align:center"><?= $status ?></td>
                                    <td style="text-align:center"><?= $row['part_no'] ?></td>
                                    <td style="text-align:center"><?= $row['hscp_no'] ?></td>
                                    <td style="text-align:center"><?= $row['addr'] ?></td>
                                    <td style="text-align:center"><?= $row['rcpt_hscp_nm'] ?></td>
                                    <td style="text-align:center"><?= $row['pyeong_cnt'] ?></td>
                                    <td style="text-align:center"><?= $row['dept_nm'] ?></td>
                                    <td style="text-align:center"><?= $row['usr_nm'] ?></td>
                                    <td style="text-align:center"><?= $row['insert_tm'] ?></td>
                                    <td class="dt-no-rowclick" style="text-align:center">
                                        <button class="btn btn-sm btn-outline-focus btn-upload-photo" type="button"
                                            onclick="openListModal('<?= esc($apt['rcpt_no'] ?? '') ?>')">
                                            <i class="fa fa-fw" aria-hidden="true" title="Copy to use file-image-o"></i> 파일 업로드
                                        </button>
                                    </td>
                                    <td class="dt-no-rowclick" style="text-align:center">
                                        <?php
                                        $link = (string) ($row['file_path'] ?? '') . (string) ($row['filenm_up'] ?? '');

                                        if (($row['cloud_upload_yn'] ?? '') === 'Y') {
                                            $link = NCLOUD_OBJECT_STORAGE_URL . $link;
                                        }
                                        ?>
                                        <?php if (!empty($row['pho_no'])): ?>
                                            <button type="button" class="btn btn-sm btn-link p-0 btn-preview"
                                                data-src="<?= $link ?>">
                                                미리보기
                                            </button>
                                        <?php endif; ?>
                                    </td>
                                    <td class="dt-no-rowclick" style="text-align:center">
                                        <?php if (!empty($row['pho_no'])): ?>
                                            <a href="<?= $link ?>" download="<?= $row['filenm'] ?>">다운로드</a>
                                        <?php endif; ?>
                                    </td>

                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="main-card mb-3 card">
            <div class="card-body">
                <h5 class="card-title">평면도 정보</h5>
                <table class="table table-bordered table-sm apt-info-table">
                    <colgroup>
                        <col width="10%" />
                        <col width="80%" />
                        <col width="10%" />
                    </colgroup>
                    <tr>
                        <th rowspan="2" style="text-align: center;">평면도</th>
                        <th>
                            <?php if (!empty($apt['pho_no'])):
                                $link = (string) ($apt['file_path'] ?? '') . (string) ($apt['filenm_up'] ?? '');
                                $thumb = (string) ($apt['file_path'] ?? '') . (string) ($apt['thumb_nm'] ?? '');
                                $fileNm = $apt['filenm'] ?? '';

                                if (($apt['cloud_upload_yn'] ?? '') === 'Y') {
                                    $link = NCLOUD_OBJECT_STORAGE_URL . $link;
                                    $thumb = NCLOUD_OBJECT_STORAGE_URL . $thumb;
                                }
                                ?>
                                <a href="javascript:fn_preview('<?= $link ?>')">
                                    <img src="<?= $thumb ?>" alt="비디오" height="150px" style="padding: 3px;"></a>
                            <?php else: ?>
                                <img src="/plugin/img/photo.gif" alt="비디오" height="150px" style="padding: 3px;">

                            <?php endif; ?>
                        </th>
                        <th style="text-align: center;">
                            <button class="btn btn-sm btn-outline-secondary ms-auto" onclick="openUploadModal();">
                                <i class="fa fa-fw" aria-hidden="true" title="Copy to use file-image-o"></i> 파일 업로드
                            </button>
                        </th>
                    </tr>
                </table>
            </div>
        </div>

        <div class="main-card mb-3 card">
            <div class="card-body ">
                <h5 class="card-title">정보변경 이력</h5>
                <div class="table-scroll">
                    <table class="table table-bordered table-sm tbl_basic2 apt-info-table">
                        <tr>
                            <th width="90" style="text-align: center;">진행상태</th>
                            <th width="150" style="text-align: center;">변경내용</th>
                            <th width="90" style="text-align: center;">처리자(ID)</th>
                            <th width="120" style="text-align: center;">처리일시</th>
                            <th style="text-align: center;">세부내용</th>
                        </tr>
                        <?php if (!empty($history)) { ?>
                            <?php foreach ($history as $h) { ?>
                                <tr>
                                    <td style="text-align: center;"><?= $h['apt_step_nm'] ?></td>
                                    <td style="text-align: center;"><?= $h['changed_type_nm'] ?></td>
                                    <td style="text-align: center;"><?= $h['charged_id'] ?></td>
                                    <td style="text-align: center;"><?= $h['changed_tm'] ?></td>
                                    <?php
                                    if ($h['changed_type'] == 'D' || $h['changed_type'] == 'H' || $h['changed_type'] == 'A') {
                                        ?>
                                        <td><?= $h['changed_detail'] ?></td>
                                        <?php
                                    } else {
                                        ?>
                                        <td><?= $h['changed_detail_nm'] ?></td>
                                    </tr>
                                    <?php
                                    } ?>

                            <?php } ?>
                        <?php } ?>
                    </table>
                </div>
            </div>
        </div>

    </div>
</div>


<?= $this->section('modals') ?>
<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>
<?= $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 bonbuArr = <?= json_encode($bonbu ?? [], JSON_UNESCAPED_UNICODE); ?>;
    const teamArr = <?= json_encode($team ?? [], JSON_UNESCAPED_UNICODE); ?>;
    const userArr = <?= json_encode($user ?? [], JSON_UNESCAPED_UNICODE); ?>;

    var map, marker;
    const lat = parseFloat("<?= esc($apt['rcpt_y'] ?? '0') ?>");
    const lng = parseFloat("<?= esc($apt['rcpt_x'] ?? '0') ?>");

    $(function () {

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

            if (targetId === "bonbu") {
                const dept_sq = $("#bonbu").val();

                str += `<option value="">선택</option>`;
                $("#user").html(`<option value="">선택</option>`);

                if (teamArr.length > 0) {
                    for (let 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>`;
                        }
                    }
                }
                $("#team").html(str);

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

                str += `<option value="">선택</option>`;
                if (userArr.length > 0) {
                    for (let i = 0; i < userArr.length; i++) {
                        if (String(userArr[i].dept_sq) === String(dept_sq)) {
                            // ✅ PHP select가 usr_id를 쓰므로 JS도 usr_id로 통일
                            str += `<option value="${userArr[i].usr_id}">${userArr[i].usr_nm}</option>`;
                        }
                    }
                }
                $("#user").html(str);
            }
        });


        map = new naver.maps.Map('mapArea', {
            center: new naver.maps.LatLng(lat, lng),
            useStyleMap: true,
            zoom: 17,
            minZoom: 10,
            mapTypeControl: true,
            mapTypeControlOptions: {
                style: naver.maps.MapTypeControlStyle.BUTTON,
                position: naver.maps.Position.TOP_LEFT
            },
            zoomControl: true,
            zoomControlOptions: {
                position: naver.maps.Position.TOP_RIGHT
            }
        });

        marker = new naver.maps.Marker({
            position: new naver.maps.LatLng(lat, lng),
            map: map
        });


        // 지도 클릭 이벤트
        naver.maps.Event.addListener(map, 'click', function (e) {

            const clickLat = e.coord.lat();
            const clickLng = e.coord.lng();

            // 마커 위치 이동
            marker.setPosition(e.coord);

            // 콘솔 출력
            console.log('위도:', clickLat, '경도:', clickLng);

            // input에 값 넣기 (선택)
            $('#rcpt_x').val(clickLng); // 경도
            $('#rcpt_y').val(clickLat); // 위도
        });

        /**
         *  파일 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 () {
            location.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);
            });
        });


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

            // const rowData = table.row(this).data();

            const rcpt_no = $(this).data('rcpt-no');
            const hscp_no = $(this).data('hscp-no');

            if (!rcpt_no || !hscp_no) return;

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


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

    });

    // 담당자 저장
    function saveKeeper(rcpt_no) {
        if ($("#bonbu").val() == "") {
            Swal.fire({
                title: "본부를 선택해 주세요.",
                icon: "warning",
                draggable: true
            });
            return;
        }

        if ($("#team").val() == "") {
            Swal.fire({
                title: "담당팀을 선택해 주세요.",
                icon: "warning",
                draggable: true
            });
            return;
        }

        if ($("#user").val() == "") {
            Swal.fire({
                title: "담담자를 선택해 주세요.",
                icon: "warning",
                draggable: true
            });
            return;
        }


        swal.fire({
            text: "저장 하시겠습니까?",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "예",
            cancelButtonText: "아니오",
            closeOnConfirm: false,
            closeOnCancel: true,
            confirmButtonColor: "#3085d6",
            cancelButtonColor: "#d33",
        }).then((result) => {
            if (result.isConfirmed) {
                var params = {
                    'rcpt_no': rcpt_no,
                    'bonbu': $("#bonbu").val(),
                    'team': $("#team").val(),
                    'user': $("#user").val(),
                };

                callAjax("/article/apt/ground/saveKeeper", params, fn_result);
            }
        });
    }


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

                $.ajax({
                    url: '/article/apt/ground/saveMemo',
                    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') {
                            Swal.fire({
                                title: '정상 처리되었습니다.',
                                icon: "success"
                            });

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

    }

    // 단지상태변경
    function statusChange(rcpt_no, type) {
        swal.fire({
            text: "정보를 변경 하시겠습니까?",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "예",
            cancelButtonText: "아니오",
            closeOnConfirm: false,
            closeOnCancel: true,
            confirmButtonColor: "#3085d6",
            cancelButtonColor: "#d33",
        }).then((result) => {
            if (result.isConfirmed) {
                const param = {
                    'rcpt_no': rcpt_no,
                    'type': type,
                };

                $.ajax({
                    url: '/article/apt/ground/statusChange',
                    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') {
                            Swal.fire({
                                title: '정상 처리되었습니다.',
                                icon: "success"
                            });

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

    // 단지 특이사항 저장
    function saveNote(rcpt_no) {
        swal.fire({
            text: "저장 하시겠습니까?",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "예",
            cancelButtonText: "아니오",
            closeOnConfirm: false,
            closeOnCancel: true,
            confirmButtonColor: "#3085d6",
            cancelButtonColor: "#d33",
        }).then((result) => {
            if (result.isConfirmed) {
                var params = {
                    'rcpt_no': rcpt_no,
                    'note': $("#note").val(),
                };

                callAjax("/article/apt/ground/saveNote", params, fn_result);
            }
        });
    }

    // 동일단지 업로드
    function openListModal(rcpt_no) {
        if (rcpt_no === null) return;
        $("#frm_file_info [name=rcpt_no]").val(rcpt_no);

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


    // 업로드 모달 open
    function openUploadModal() {
        const modal = new bootstrap.Modal(document.getElementById('uploadModal'));
        modal.show();
    }

    // 미리보기
    function fn_preview(src) {
        const $img = $('#imgPreview');

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

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


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



    function callAjax(target, params, callback) {
        $.ajax({
            url: target,
            method: "POST",
            dataType: "json",
            data: params,
            beforeSend: function () {
                blockUI.blockPage({
                    message: tpl
                })
            },
            complete: function () {
                blockUI.unblockPage()
            },
            success: function (result) {
                callback(result);
            }
        });
    }


    function fn_result(result) {
        if (result.code == '0') {
            Swal.fire({
                title: "정상 처리되었습니다.",
                icon: "success",
                draggable: true
            })


            setTimeout(() => {
                location.reload();
            }, 1000);
        } else {
            Swal.fire({
                title: result.msg,
                icon: "error",
                draggable: true
            })
        }
    }

</script>
<?= $this->endSection() ?>