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

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

    #svcList 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-4">
                        <label class="form-label mb-1">지역검색</label>
                        <div class="row g-2">
                            <div class="col-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-4">
                                <select class="form-control" name="srcGugun" id="srcGugun">
                                    <option value="">시/군/구</option>
                                </select>
                            </div>
                            <div class="col-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>
                        <div class="row g-2">
                            <div class="col-6">
                                <select class="form-control" name="srcUserbonbu" id="srcUserbonbu">
                                    <option value="">선택</option>
                                    <?php foreach ($bonbu as $d): ?>
                                        <option value="<?= $d['dept_sq'] ?>"><?= $d['dept_nm'] ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-6">
                                <select class="form-control" name="srcUserteam" id="srcUserteam">
                                    <option value="">선택</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-1">
                        <label class="form-label mb-1">지정 유무</label>
                        <select class="form-control" name="positionYn">
                            <option value="">선택</option>
                            <option value="Y">지정</option>
                            <option value="N">미지정</option>
                        </select>
                    </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="svcList" class="table table-hover table-striped table-bordered">
                    <thead>
                        <tr>
                            <th></th>
                            <th>지역코드</th>
                            <th>지역</th>
                            <th>관할조직</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- 여기는 비워둠: AJAX로 채움 -->
                    </tbody>
                </table>
            </div>
            <div class="card-footer d-flex gap-2">
                <button type="button" class="btn btn-light" id="btnAllSave">
                    일괄저장
                </button>

                <button type="button" class="btn btn-primary" id="btnSave">
                    저장
                </button>
            </div>
        </div>
    </div>
</div>


<?= $this->section('modals') ?>
<div class="modal fade" id="regionModal" tabindex="-1" aria-labelledby="regionModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="regionModalLabel">관할조직 일괄저장</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="frm_region_info" class="needs-validation" onsubmit="return false;" novalidate>
                    <input type="hidden" name="type" value="create">
                    <!-- 1 row -->
                    <div class="row mb-3">
                        <div class="col-md-4">
                            <label class="form-label">소속본부</label>
                            <select id="mBonbu" class="form-select" required>
                                <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">
                            <label class="form-label">소속팀</label>
                            <select id="mTeam" class="form-select" required>
                                <option value="">팀 선택</option>
                            </select>
                        </div>

                        <div class="col-md-4">
                            <label class="form-label">담당자</label>
                            <select id="mUser" class="form-select" required>
                                <option value="">담당자 선택</option>
                            </select>
                        </div>
                    </div>
                </form>

                <div><small>현재 그리드의 데이터를 일괄 저장합니다.</small></div>
            </div>
            <div class="modal-footer d-flex gap-2">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">닫기</button>
                <button type="button" class="btn btn-primary" id="allSave">저장</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');

    const bonbuArr = <?= json_encode($bonbu, JSON_UNESCAPED_UNICODE); ?>;
    const teamArr = <?= json_encode($team, JSON_UNESCAPED_UNICODE); ?>;
    const userArr = <?= json_encode($user, JSON_UNESCAPED_UNICODE); ?>;

    $(function () {

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

            const targetId = this.id;

            $.ajax({
                url: "/manage/areas/getAreaList",
                method: "POST",
                dataType: "json",
                data: {
                    'srcSido': $("#frm_srch_info [name=srcSido]").val(),
                    'srcGugun': $("#frm_srch_info [name=srcGugun]").val(),
                },
                beforeSend: function () {
                    blockUI.blockPage({
                        message: tpl
                    })
                },
                complete: function () {
                    blockUI.unblockPage()
                },
                success: function (result) {

                    switch (targetId) {
                        case "srcSido":
                            console.log(result)
                            $("#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;
                    }
                }
            });
        });

        $("#mBonbu, #mTeam").on("change", function (e) {
            const targetId = this.id;

            var str = "";
            if (targetId === "mBonbu") {
                const dept_sq = $("#mBonbu").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>
                            `;
                        }
                    }
                }

                $("#mTeam").html(str);

            } else if (targetId === "mTeam") {
                const dept_sq = $("#mTeam").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_sq}">${userArr[i].usr_nm}</option>
                            `;
                        }
                    }
                }

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

        });


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

            const value = e.target.value

            $("#srcUserteam").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>"
                    }
                }
            }

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

        });


        let table = $('#svcList').DataTable({
            language: lang_kor,
            processing: true,
            serverSide: false,
            ajax: {
                url: '/manage/areas/getSvcArea',
                type: 'GET',
                beforeSend: function () {
                    blockUI.blockPage({
                        message: tpl
                    })
                },
                complete: function () {
                    blockUI.unblockPage()
                },
                data: function (d) {
                    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.srcUserbonbu = $("#frm_srch_info [name=srcUserbonbu]").val()
                    d.srcUserteam = $("#frm_srch_info [name=srcUserteam]").val()
                    d.positionYn = $("#frm_srch_info [name=positionYn]").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: 'region_cd', "width": "150px" },
                { data: 'region_nm' },
                { data: null, "render": fn_region_render },
            ],
            // 옵션들 예시
            paging: true,
            searching: false,
            ordering: false,
            serverSide: true,
        });


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

            // const modalEl = document.getElementById('regionModal');
            // const myModal = new bootstrap.Modal(modalEl);
            // myModal.show();

        });

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

        // 본부선택 onchage
        $('#svcList').on('change', '.bonbu', function () {
            const bonbu = $(this).val();
            const rowIdx = $(this).data('index')

            if (!bonbu) return;

            fn_team_render(bonbu, rowIdx)

        });

        // 팀선택 onchage
        $('#svcList').on('change', '.team', function () {
            const team = $(this).val();
            const rowIdx = $(this).data('index')

            if (!team) return;

            fn_user_render(team, rowIdx)

        });

        // 지역관리 일괄저장 modal
        $("#btnAllSave").on("click", function () {

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


        });

        // 지역관리정보저장
        $("#btnSave").on("click", function () {
            let rows = table.rows().data().toArray();

            if (rows.length == 0) return;

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

                var bonbu = $("#bonbu-" + i).val();
                var team = $("#team-" + i).val();
                var user = $("#user-" + i).val();

                if (bonbu == "") {
                    Swal.fire({
                        title: (i + 1) + "행 본부 데이터 누락",
                        icon: "error"
                    });
                    return;
                }

                if (team == "") {
                    Swal.fire({
                        title: (i + 1) + "행 팀 데이터 누락",
                        icon: "error"
                    });
                    return;
                }

                if (user == "") {
                    Swal.fire({
                        title: (i + 1) + "행 담당자 데이터 누락",
                        icon: "error"
                    });
                    return;
                }

                rows[i].bonbu = $("#bonbu-" + i).val();
                rows[i].team = $("#team-" + i).val();
                rows[i].user = $("#user-" + i).val();

            }

            swal.fire({
                text: "저장 하시겠습니까?",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "예",
                cancelButtonText: "아니오",
                confirmButtonColor: "#3085d6",
                cancelButtonColor: "#ff0000",
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: '/manage/areas/saveRegion',
                        contentType: 'application/json; charset=UTF-8',
                        method: 'POST',
                        data: JSON.stringify(rows),
                        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) {
                            blockUI.unblockPage()
                            if (result.code == '0') {
                                $("#btnSearch").trigger('click')
                                Swal.fire({
                                    title: '정상 처리되었습니다.',
                                    icon: "success"

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


        // 지역관리 일괄저장
        $("#allSave").on("click", function () {

            let rows = table.rows().data().toArray();

            if (rows.length == 0) return;

            var bonbu = $("#mBonbu").val();
            var team = $("#mTeam").val();
            var user = $("#mUser").val();

            if (bonbu == "") {
                Swal.fire({
                    title: "본부 데이터 누락",
                    icon: "error"
                });
                return;
            }

            if (team == "") {
                Swal.fire({
                    title: "팀 데이터 누락",
                    icon: "error"
                });
                return;
            }

            if (user == "") {
                Swal.fire({
                    title: "담당자 데이터 누락",
                    icon: "error"
                });
                return;
            }

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

                rows[i].bonbu = bonbu;
                rows[i].team = team;
                rows[i].user = user;

            }

            swal.fire({
                text: "저장 하시겠습니까?",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "예",
                cancelButtonText: "아니오",
                confirmButtonColor: "#3085d6",
                cancelButtonColor: "#ff0000",
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: '/manage/areas/saveAllRegion',
                        contentType: 'application/json; charset=UTF-8',
                        method: 'POST',
                        data: JSON.stringify(rows),
                        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) {
                            blockUI.unblockPage()
                            if (result.code == '0') {
                                regionModalHide()
                                $("#btnSearch").trigger('click')
                                Swal.fire({
                                    title: '정상 처리되었습니다.',
                                    icon: "success"

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


    });

    // 관할조직 render
    function fn_region_render(data, type, row, meta) {

        var str = ""

        str += `
            <div class="d-flex gap-1">
                <div class="flex-fill">                    
               `;

        str += `<select class="form-control bonbu" id="bonbu-${meta.row}" data-index="${meta.row}">`;
        str += `<option value="">본부 선택</option>`;
        if (bonbuArr.length > 0) {
            for (var i = 0; i < bonbuArr.length; i++) {
                var selected = ""
                if (bonbuArr[i].dept_sq === row.pdept_sq) selected = "selected"

                str += `
                    <option value="${bonbuArr[i].dept_sq}" ${selected}>${bonbuArr[i].dept_nm}</option>
                `;
            }
        }
        str += `</select></div>`;

        str += `<div class="flex-fill">`;
        str += `<select class="form-control team" id="team-${meta.row}" data-index="${meta.row}">`;
        str += `<option value="">팀 선택</option>`;
        const currentBonbuSq = row.pdept_sq;   // 현재 행에서 선택된 본부 sq

        if (teamArr.length > 0) {
            for (var i = 0; i < teamArr.length; i++) {

                // 이 팀이 현재 본부에 속한 팀인지 체크
                if (String(teamArr[i].pdept_sq) === String(currentBonbuSq)) {

                    var selected = "";
                    if (teamArr[i].dept_sq === row.dept_sq) selected = "selected";

                    str += `
                <option value="${teamArr[i].dept_sq}" ${selected}>${teamArr[i].dept_nm}</option>
            `;
                }
            }
        }
        str += `</select></div>`;


        str += `<div class="flex-fill">`;
        str += `<select class="form-control team-user" id="user-${meta.row}">`;
        str += `<option value="">담당자 선택</option>`;
        if (userArr.length > 0) {
            for (var i = 0; i < userArr.length; i++) {
                if (userArr[i].dept_sq == row.dept_sq) {
                    var selected = ""
                    if (userArr[i].usr_sq === row.usr_sq) selected = "selected"

                    str += `
                    <option value="${userArr[i].usr_sq}" ${selected}>${userArr[i].usr_nm}</option>
                `;
                }

            }
        }
        str += `</select></div>`;




        str += `</div></div>`;

        return str
    }

    // 팀 render
    function fn_team_render(dept_sq, idx) {
        str = `<option value="">팀 선택`;
        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>`;
                }
            }
        }

        $("#team-" + idx).html(str)
        fn_user_render("", idx)
    }

    // 유저 render
    function fn_user_render(dept_sq, idx) {
        str = `<option value="">담당자 선택`;
        if (dept_sq != "") {
            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_sq}">${userArr[i].usr_nm}</option>`;
                    }
                }
            }
        }

        $("#user-" + idx).html(str)
    }

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

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



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