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

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

    #deptList 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-1">
                        <label class="form-label mb-1">조직구분</label>
                        <select class="form-control" name="srchDepth">
                            <option value="">선택</option>
                            <option value="1">본부</option>
                            <option value="2">팀</option>
                        </select>
                    </div>

                    <div class="col-md-2">
                        <label class="form-label mb-1">조직명칭</label>
                        <input type="text" class="form-control" name="srcDeptNm">
                    </div>

                    <div class="col-md-2">
                        <label class="form-label mb-1">총괄팀장</label>
                        <input type="text" class="form-control" name="srcDeptHead">
                    </div>

                    <div class="col-md-1">
                        <label class="form-label mb-1">사용여부</label>
                        <select class="form-control" name="useYn">
                            <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="deptList" 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>
                            <th>수정일자</th>
                            <th>수정자</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- 여기는 비워둠: AJAX로 채움 -->
                    </tbody>
                </table>
            </div>
            <div class="card-footer">
                <button type="button" class="btn btn-primary" id="addUser">
                    등록
                </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_dept_info" class="needs-validation" onsubmit="return false;" novalidate>
                    <input type="hidden" name="dept_sq" />
                    <input type="hidden" name="pdept_sq" />
                    <input type="hidden" name="type" value="create" />
                    <div class="row">

                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="form-label">조직구분</label>
                                <select class="form-control" name="addDepth" id="addDepth" required>
                                    <option value="">선택</option>
                                    <option value="1">본부</option>
                                    <option value="2">팀</option>
                                </select>
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="form-label">상위조직</label>
                                <select class="form-control" name="addPdept" id="addPdept" required>
                                    <option value="">선택</option>
                                </select>
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="form-label">조직명칭</label>
                                <input type="text" class="form-control" name="addDeptNm" id="addDeptNm" required>
                            </div>
                        </div>

                        <div class="col-md-8">
                            <div class="form-group">
                                <label class="form-label">총괄팀장</label>

                                <div class="row g-2">
                                    <div class="col-md-5">
                                        <input type="text" class="form-control" name="addDeptHeadNm" id="addDeptHeadNm"
                                            readonly required>
                                    </div>
                                    <div class="col-md-5">
                                        <input type="text" class="form-control" name="addDeptHead" id="addDeptHead"
                                            readonly required>
                                    </div>
                                    <div class="col-md-2 d-grid">
                                        <button type="button" class="btn btn-info w-100"
                                            onclick="fUsrDupIdChk();">찾기</button>
                                    </div>
                                </div>

                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="form-label">사용여부</label>
                                <select class="form-control" name="addUseYn" id="addUseYn" required>
                                    <option value="">선택</option>
                                    <option value="Y" selected>사용</option>
                                    <option value="N">미사용</option>
                                </select>
                            </div>
                        </div>

                        <div class="col-md-12">
                            <div class="form-group">
                                <label class="form-label">부서설명</label>
                                <input type="text" class="form-control" name="addDeptDesc" id="addDeptDesc">
                            </div>
                        </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="deptSave">저장</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 = $('#deptList').DataTable({
            language: lang_kor,
            processing: true,
            serverSide: false,
            ajax: {
                url: '/manage/dept/getDeptList',
                type: 'GET',
                beforeSend: function () {
                    blockUI.blockPage({
                        message: tpl
                    })
                },
                complete: function () {
                    blockUI.unblockPage()
                },
                data: function (d) {
                    d.srchDepth = $("#frm_srch_info [name=srchDepth]").val()
                    d.srcDeptNm = $("#frm_srch_info [name=srcDeptNm]").val()
                    d.srcDeptHead = $("#frm_srch_info [name=srcDeptHead]").val()
                    d.useYn = $("#frm_srch_info [name=useYn]").val()

                    d.srchType = $("#frm_srch_info [name=srchType]").val()
                    d.srchTxt = $("#frm_srch_info [name=srchTxt]").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: 'pdept_nm' },
                { data: 'dept_nm' },
                { data: 'dept_head_nm' },
                { data: 'use_yn_nm' },
                { data: 'depth_nm' },
                { data: 'insert_tm' },
                { data: 'insert_usr' },
                { data: 'update_tm' },
                { data: 'update_usr' },
            ],
            // 옵션들 예시
            paging: true,
            searching: false,
            ordering: false,
            serverSide: true,
        });


        $('#deptList 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_dept_info")[0].reset()

            $("#frm_dept_info [name=dept_sq]").val(row.dept_sq)
            $("#frm_dept_info [name=pdept_sq]").val(row.pdept_sq)
            $("#frm_dept_info [name=type]").val("update")
            $("#frm_dept_info [name=addDeptNm]").val(row.dept_nm)
            $("#frm_dept_info [name=addDeptHeadNm]").val(row.dept_head_nm)
            $("#frm_dept_info [name=addDeptHead]").val(row.dept_head)
            $("#frm_dept_info [name=addUseYn]").val(row.use_yn)
            $("#frm_dept_info [name=addDeptDesc]").val(row.dept_desc)


            var pdept_sq = row.pdept_sq
            $("#frm_dept_info [name=addDepth]").val(pdept_sq)



            var str = "";
            str += "<option value=''>선택</option>"

            if (pdept_sq === "1") {
                str += "<option value='1' selected>컨펌스</option>"

                $("#addPdept").empty()
                $("#addPdept").append(str)
            } else if (pdept_sq === "2") {

                $.ajax({
                    url: '/manage/dept/getPdept',
                    contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
                    method: 'GET',
                    data: $("#frm_dept_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) {
                        const data = result.data;

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

                        $("#addPdept").empty()
                        $("#addPdept").append(str)
                    }
                });

            }

            myModal.show();

        });

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


        // 상위조직 검색 - onchange
        $("#addDepth").on("change", function (e) {

            var val = e.target.value

            var str = "";
            str += "<option value=''>선택</option>"

            if (val === "1") {
                str += "<option value='1'>컨펌스</option>"

                $("#addPdept").empty()
                $("#addPdept").append(str)
            } else {

                $.ajax({
                    url: '/manage/dept/getPdept',
                    contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
                    method: 'GET',
                    data: $("#frm_dept_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) {
                        const data = result.data;

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


                            }
                        }

                        $("#addPdept").empty()
                        $("#addPdept").append(str)
                    }
                });

            }

        });

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

            $("#frm_dept_info [name=dept_sq]").val("")
            $("#frm_dept_info [name=pdept_sq]").val("")
            $("#frm_dept_info [name=type]").val("create")
            $("#frm_dept_info [name=addUserId]").prop("readonly", false)

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


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

            const form = document.getElementById('frm_dept_info');
            const type = $("#frm_dept_info [name=type]").val();

            let isValid = true;

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

            if (!isValid) {
                form.classList.add('was-validated');
                return;
            }

            if ($("#frm_dept_info [name=addDeptHeadNm]").val() == "" || $("#frm_dept_info [name=addDeptHead]").val() == "") {
                Swal.fire({
                    title: "총괄팀장 정보 누락",
                    icon: "error"
                })
                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/dept/saveDept',
                        contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
                        method: 'POST',
                        data: $("#frm_dept_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"
                                })
                            }
                        }
                    });
                }
            })
        });



    });


    // 총괄팀장 찾기
    function fUsrDupIdChk() {
        // var paramstr = $("#paramstr").val();
        window.open('/manage/dept/getchkuser', 'get', 'width=600,height=800');
    }

    // 응답 유저 정보 입력
    function setSelectedUser(id, name, usrSq) {
        $("#frm_dept_info [name=addDeptHeadNm]").val(name);
        $("#frm_dept_info [name=addDeptHead]").val(usrSq);
    }


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

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

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