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

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

    #aptList 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 align-items-end" id="frm_srch_info" onsubmit="return false;">

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

                    <!-- 검색 버튼 -->
                    <div class="col-md-1 d-grid">
                        <button type="button" class="btn btn-primary" id="btnSearch">
                            검색
                        </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="aptList" class="table table-hover table-striped table-bordered">
                    <thead>
                        <tr>
                            <th>순번</th>
                            <th>단지코드</th>
                            <th>단지구역명</th>
                            <th>단지코드변경</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- 여기는 비워둠: AJAX로 채움 -->
                    </tbody>
                </table>
            </div>

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

<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 = $('#aptList').DataTable({
            language: lang_kor,
            processing: true,
            ajax: {
                url: '/article/apt/delChgApt/getAptLists',
                type: 'GET',
                beforeSend: function () {
                    blockUI.blockPage({
                        message: tpl
                    })
                },
                complete: function () {
                    blockUI.unblockPage()
                },
                data: function (d) {
                    d.hscpNo = $("#frm_srch_info [name=hscpNo]").val()

                    d.start = d.start || 0
                    d.length = d.length || 10
                }
            },
            "columnDefs": [
                { 'targets': '_all', "defaultContent": "" },
                { className: 'text-center', targets: '_all' },
            ],
            columns: [
                {
                    "data": null,
                    "width": "50px",
                    "render": function (data, type, row, meta) {
                        return meta.row + meta.settings._iDisplayStart + 1;
                    }
                },
                { data: 'hscp_no' },
                { data: 'rcpt_hscp_nm' },
                { data: null, render: fn_chg_render },
                { data: null, render: fn_del_render },
            ],
            // 옵션들 예시
            paging: true,
            searching: false,
            ordering: false,
            serverSide: true,
        });


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

    });


    // 단지코드명변경 redner
    function fn_chg_render(data, type, row) {
        var str = "";
        str += `<div class="d-flex gap-1">`;
        str += `<div class="flex-fill"><input type="text" class="form-control" id="hscpNo_${row.hscp_no}"></div>`;
        str += `<div class="flex-fill"><button type="button" class="btn btn-primary" onclick="fn_hscp_save('${row.hscp_no}', '${row.rcpt_no}');">저장</button></div>`;
        str += `</div>`;

        return str;
    }

    // 단지코드삭제 render
    function fn_del_render(data, type, row) {
        var str = "";

        str += `<button type = "button" class="btn btn-danger" id="btnDelete" onclick="fn_hscp_delete('${row.rcpt_no}');">삭제</button >`;

        return str;
    }

    function fn_hscp_save(hscpNo, rcptNo) {
        const hscpNo2 = $("#hscpNo_" + hscpNo).val();

        console.log(hscpNo)
        console.log(hscpNo2)

        if (hscpNo2 == "") {
            console.log("???")
            Swal.fire({
                title: '변경할 단지코드를 입력해 주세요.',
                icon: "warning"

            });
            return;
        }

        if (hscpNo === hscpNo2) {
            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) {
                $.ajax({
                    url: '/article/apt/delChgApt/chgAptHscp',
                    contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
                    method: 'POST',
                    data: { rcpt_no: rcptNo, hscp_no: hscpNo2 },
                    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"
                            })
                        }
                    }
                });
            }
        });
    }


    function fn_hscp_delete(rcptNo) {
        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/delChgApt/deleteAptHscp',
                    contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
                    method: 'POST',
                    data: { rcpt_no: rcptNo, hscp_no: hscpNo2 },
                    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"
                            })
                        }
                    }
                });
            }
        });
    }

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