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

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

    #scomplexList tbody tr {
        cursor: pointer;
    }

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

    .swal2-cancel {
        background-color: #ff0000 !important;
        color: #fff !important;
    }
</style>

<h1>특이단지 관리</h1>

<div class="row">
    <div class="col-md-12 col-xl-12">
        <div class="main-card mb-3 card">
            <div class="card-body">
                <form class="row g-3 align-items-end" id="frm_srch_info" onsubmit="return false;">

                    <!-- 1행 -->
                    <div class="col-md-2">
                        <label class="form-label">단지명</label>
                        <input type="text" class="form-control" name="name" placeholder="단지명 입력">
                    </div>

                    <div class="col-md-2">
                        <label class="form-label">사용 승인/종료일</label>
                        <div class="row g-2">
                            <div class="col-5">
                                <input type="date" class="form-control" name="apporval_date">
                            </div>
                            <div class="col-2 text-center" style="line-height: 35px;">~</div>
                            <div class="col-5">
                                <input type="date" class="form-control" name="end_date">
                            </div>
                        </div>
                    </div>

                    <div class="col-md-2">
                        <label class="form-label">매물 종류</label>
                        <select class="form-control" name="cd">
                            <option value="">선택</option>
                            <?php foreach ($code as $c): ?>
                                <option value="<?= $c['cd'] ?>"><?= $c['cd_nm'] ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <!-- 2행 -->
                    <div class="col-md-1">
                        <label class="form-label">단지코드</label>
                        <input type="text" class="form-control" name="code">
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">단지주소</label>
                        <input type="text" class="form-control" name="address">
                    </div>

                    <!-- 버튼 -->
                    <div class="col-md-1 d-grid">
                        <button type="button" class="btn btn-primary" id="btnSearch">
                            검색
                        </button>
                    </div>

                    <div class="col-md-1 d-grid">
                        <button type="button" class="btn btn-outline-success" id="btnExcel">
                            <i class="fa fas fa-file-excel-o"></i> 엑셀 다운로드
                        </button>
                    </div>

                </form>

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


    <div class="col-md-12 col-xl-12">
        <div class="main-card mb-3 card">
            <div class="card-header">조직 관리</div>
            <div class="card-body">
                <table id="scomplexList" class="table table-hover table-striped table-bordered">
                    <thead>
                        <tr>
                            <th></th>
                            <th>등록일자</th>
                            <th>단지코드</th>
                            <th>단지명</th>
                            <th>단지주소</th>
                            <th>매물종류</th>
                            <th>승인일자</th>
                            <th>종료일자</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- 여기는 비워둠: AJAX로 채움 -->
                    </tbody>
                </table>
            </div>
            <div class="card-footer">
                <button type="button" class="btn btn-primary" id="addPhone">
                    등록
                </button>
            </div>
        </div>
    </div>
</div>

<?= $this->section('modals') ?>
<div class="modal fade" id="deptModal" tabindex="-1" aria-labelledby="deptModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="deptModalLabel">특이단지 정보</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="frm_scomplex_info" class="needs-validation" onsubmit="return false;" novalidate>
                    <input type="hidden" name="type" value="create" />
                    <input type="hidden" name="sm_seq" />
                    <div class="row g-3">
                        <!-- 단지명 -->
                        <div class="col-md-4">
                            <label for="name" class="form-label mb-1">단지명</label>
                            <input type="text" class="form-control" name="sm_name" id="sm_name" required>
                        </div>

                        <!-- 사용승인일 -->
                        <div class="col-md-4">
                            <label for="apporval_date" class="form-label mb-1">사용승인일</label>
                            <input type="date" class="form-control date_picker" name="sm_apporval_date"
                                id="sm_apporval_date" required>
                        </div>

                        <!-- 승인종료일 -->
                        <div class="col-md-4">
                            <label for="end_date" class="form-label mb-1">승인종료일</label>
                            <input type="date" class="form-control date_picker" name="sm_end_date" id="sm_end_date"
                                required>
                        </div>

                        <!-- 단지코드 -->
                        <div class="col-md-4">
                            <label for="code" class="form-label mb-1">단지코드</label>
                            <input type="text" class="form-control" name="sm_code" id="sm_code" required>
                        </div>

                        <!-- 단지주소 -->
                        <div class="col-6">
                            <label for="address" class="form-label mb-1">단지주소</label>
                            <input type="text" class="form-control" name="sm_address" id="sm_address" required>
                        </div>

                        <!-- 매물 종류 -->
                        <div class="col-md-2">
                            <label for="cd" class="form-label mb-1">매물 종류</label>
                            <select class="form-control" name="codes" id="codes" required>
                                <option value="">-매물종류-</option>
                                <?php foreach ($code as $c): ?>
                                    <option value="<?= $c['cd'] ?>"><?= $c['cd_nm'] ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-12">
                            <label for="address" class="form-label mb-1">메모</label>
                            <textarea name="sm_memo" id="sm_memo" class="form-control" rows="2"></textarea>
                        </div>
                    </div>

                </form>
            </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="phoneSave">저장</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" />
<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 type="text/javascript">

    // const tpl = document.querySelector('.my-loader-template');


    $(function () {

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

            var dept_sq = e.target.value

            $("#srchTeam").empty()

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

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

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

        });


        let table = $('#scomplexList').DataTable({
            language: lang_kor,
            processing: true,
            serverSide: false,
            ajax: {
                url: '/manage/scomplex/getScomplexList',
                type: 'GET',
                beforeSend: function () {
                    blockUI.blockPage({
                        message: tpl
                    })
                },
                complete: function () {
                    blockUI.unblockPage()
                },
                data: function (d) {
                    d.name = $("#frm_srch_info [name=name]").val()
                    d.apporval_date = $("#frm_srch_info [name=apporval_date]").val()
                    d.end_date = $("#frm_srch_info [name=end_date]").val()
                    d.code = $("#frm_srch_info [name=code]").val()
                    d.cd = $("#frm_srch_info [name=cd]").val()
                    d.address = $("#frm_srch_info [name=address]").val()

                    d.start = d.start || 0
                    d.length = d.length || 10
                }
            },
            "columnDefs": [
                { 'targets': '_all', "defaultContent": "" },
                // { 'className': 'text-center', 'targets': [0, 2, 3, 4] },
            ],
            columns: [
                {
                    "data": null,
                    "width": "50px",
                    "render": function (data, type, row, meta) {
                        return meta.row + meta.settings._iDisplayStart + 1;
                    }
                },
                { data: 'insert_tm', "width": "150px" },
                { data: 'sm_code', "width": "70px" },
                { data: 'sm_name', "width": "200px" },
                { data: 'sm_address' },
                { data: 'cd_nm', "width": "80px" },
                { data: 'sm_apporval_date', "width": "80px" },
                { data: 'sm_end_date', "width": "80px" },
            ],
            // 옵션들 예시
            paging: true,
            searching: false,
            ordering: false,
            serverSide: true,
        });


        $('#scomplexList tbody').on('click', 'tr', function () {
            const row = table.row(this).data()
            if (!row) return

            const modalEl = document.getElementById('deptModal');
            const myModal = new bootstrap.Modal(modalEl);

            $("#frm_scomplex_info")[0].reset()
            $("#frm_scomplex_info [name=type]").val("update")

            $("#frm_scomplex_info [name=sm_seq]").val(row.sm_seq)
            $("#frm_scomplex_info [name=sm_name]").val(row.sm_name)
            $("#frm_scomplex_info [name=sm_code]").val(row.sm_code)
            $("#frm_scomplex_info [name=sm_address]").val(row.sm_address)
            $("#frm_scomplex_info [name=codes]").val(row.cd)
            $("#frm_scomplex_info [name=sm_apporval_date]").val(row.sm_apporval_date)
            $("#frm_scomplex_info [name=sm_end_date]").val(row.sm_end_date)
            $("#frm_scomplex_info [name=sm_memo]").val(row.sm_memo)


            myModal.show();

        });

        // [검색] 버튼 눌렀을 때 다시 조회
        $('#btnSearch').on('click', function () {
            table.ajax.reload()
        });

        // 유저 등록 모달
        $("#addPhone").on("click", function () {
            $("#frm_scomplex_info")[0].reset()

            $("#frm_scomplex_info [name=type]").val("create")
            $("#frm_scomplex_info [name=phone_number]").prop("readonly", false)

            const modalEl = document.getElementById('deptModal');
            const myModal = new bootstrap.Modal(modalEl);
            myModal.show();
        });


        // 유저정보저장
        $("#phoneSave").on("click", function () {

            const form = document.getElementById('frm_scomplex_info');

            let isValid = true;

            // Bootstrap5 기본 validation 적용
            if (!form.checkValidity()) {
                isValid = false;
            }

            if (!isValid) {
                form.classList.add('was-validated');
                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: '/manage/scomplex/saveScomplex',
                        contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
                        method: 'POST',
                        data: $("#frm_scomplex_info").serialize(),
                        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') {
                                deptModalHide()
                                $("#btnSearch").trigger('click')
                                Swal.fire({
                                    title: '정상 처리되었습니다.',
                                    icon: "success"

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


        // 엑셀다운 click
        $("#btnExcel").on("click", function () {

            $.ajax({
                url: "/manage/scomplex/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);
                }
            });

        });

    });

    function deptModalHide() {
        const modalEl = document.getElementById('deptModal');
        const modal = bootstrap.Modal.getInstance(modalEl); // 기존 인스턴스 가져오기

        if (modal) {
            modal.hide();
        }
    }

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

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

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