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

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

    #userList 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="srchLevel">
                            <option value="">선택</option>
                            <?php foreach ($userLevel as $level): ?>
                                <option value="<?= $level['cd'] ?>"><?= $level['cd_nm'] ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <!-- 소속본부 / 소속팀 -->
                    <div class="col-md-3">
                        <label class="form-label mb-1">소속본부 / 소속팀</label>
                        <div class="row g-2">
                            <div class="col-6">
                                <select class="form-control" name="srchBonbu" id="srchBonbu">
                                    <option value="">선택</option>
                                    <?php foreach ($bonbuList as $bonbu): ?>
                                        <option value="<?= $bonbu['dept_sq'] ?>"><?= $bonbu['dept_nm'] ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-6">
                                <select class="form-control" name="srchTeam" id="srchTeam">
                                    <option value="">선택</option>
                                </select>
                            </div>
                        </div>
                    </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">
                        <label class="form-label mb-1">검색유형</label>
                        <select class="form-control" name="srchType">
                            <option value="">선택</option>
                            <option value="1">사용자명</option>
                            <option value="2">사원번호</option>
                            <option value="3">직급</option>
                            <option value="4">연락처</option>
                            <option value="5">주소</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label mb-1">검색어</label>
                        <input type="text" class="form-control" name="srchTxt" placeholder="검색어 입력">

                    </div>

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

                    <!-- 엑셀 버튼 -->
                    <div class="col-md-2">
                        <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 d-flex align-items-center">
                <h3 class="card-title mb-0">사용자 목록</h3>

                <!-- 오른쪽 영역 -->
                <div class="ms-auto d-flex align-items-center gap-3">

                    <label class="mb-0 fw-semibold">
                        SMS인증여부 일괄변경
                    </label>

                    <div class="input-group input-group-sm" style="width: 200px;">
                        <select class="form-select" id="srcUseYn">
                            <option value="Y">사용</option>
                            <option value="N">미사용</option>
                        </select>
                        <button type="button" class="btn btn-primary" id="btnSmsSave">
                            저장
                        </button>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <table id="userList" 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>SMS인증여부</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="userModal" tabindex="-1" aria-labelledby="userModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="userModalLabel">사용자정보</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="frm_user_info" class="needs-validation" onsubmit="return false;" novalidate>
                    <input type="hidden" name="usr_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>
                                <input type="text" class="form-control" name="addUserNm" id="addUserNm" required>
                            </div>
                        </div>

                        <!-- 소속조직 -->
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="form-label">소속조직</label>
                                <select class="form-control" name="addUserDept" id="addUserDept" required>
                                    <option value="">선택</option>
                                    <?php foreach ($deptCode as $dept): ?>
                                        <option value="<?= $dept['dept_sq'] ?>"><?= $dept['dept_nm'] ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>

                        <!-- 사원번호 -->
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="form-label">사원번호</label>
                                <input type="text" class="form-control" name="addUserId" id="addUserId" readonly
                                    required>
                                <small id="idDupText" class="text-danger"></small>
                            </div>
                        </div>

                        <!-- 비밀번호 -->
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="form-label">비밀번호</label>
                                <input type="password" class="form-control" name="addUserPswd" id="addUserPswd">
                            </div>
                        </div>

                        <!-- 등급 -->
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="form-label">등급</label>
                                <select class="form-control" name="addUserLevel" id="addUserLevel" required>
                                    <option value="">선택</option>
                                    <?php foreach ($userLevel as $level): ?>
                                        <option value="<?= $level['cd'] ?>"><?= $level['cd_nm'] ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>

                        <!-- 직급 -->
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="form-label">직급</label>
                                <input type="text" class="form-control" name="addUserPosition" id="addUserPosition"
                                    required>
                            </div>
                        </div>

                        <!-- 연락처 -->
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="form-label">연락처</label>
                                <input type="text" class="form-control" name="addUserTel1" id="addUserTel1" required>
                            </div>
                        </div>

                        <!-- 연락처2 -->
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="form-label">연락처2</label>
                                <input type="text" class="form-control" name="addUserTel2" id="addUserTel2">
                            </div>
                        </div>

                        <!-- SMS 여부 -->
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="form-label">SMS 인증여부</label>
                                <select class="form-control" name="addSmsYn" id="addSmsYn">
                                    <option value="Y">예</option>
                                    <option value="N" selected>아니요</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="addUserAddr1" id="addUserAddr1">
                            </div>
                        </div>

                        <!-- 상세주소 -->
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="form-label">상세주소</label>
                                <input type="text" class="form-control" name="addUserAddr2" id="addUserAddr2">
                            </div>
                        </div>

                        <!-- 사용여부 -->
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="form-label">사용여부</label>
                                <select class="form-control" name="addUseYn" id="addUseYn">
                                    <option value="Y" selected>예</option>
                                    <option value="N">아니요</option>
                                </select>
                            </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-danger" id="userRemove">삭제</button>
                <button type="button" class="btn btn-primary" id="userSave">저장</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');
    var teamArr = <?= json_encode($teamList, JSON_UNESCAPED_UNICODE); ?>;

    let date = new Date();

    $(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 = $('#userList').DataTable({
            language: lang_kor,
            processing: true,
            serverSide: false,
            ajax: {
                url: '/manage/user/getUserList',
                type: 'GET',
                beforeSend: function () {
                    blockUI.blockPage({
                        message: tpl
                    })
                },
                complete: function () {
                    blockUI.unblockPage()
                },
                data: function (d) {
                    d.srchLevel = $("#frm_srch_info [name=srchLevel]").val()
                    d.srchBonbu = $("#frm_srch_info [name=srchBonbu]").val()
                    d.srchTeam = $("#frm_srch_info [name=srchTeam]").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: 'usr_id' },
                { data: 'usr_nm' },
                { data: 'level_nm' },
                { data: 'usr_position' },

                { data: 'usr_tel1' },
                { data: 'sms_auth_yn_nm' },
                { data: 'use_yn_nm' },
                { data: 'last_usr_pw_tm' },
            ],
            // 옵션들 예시
            paging: true,
            searching: false,
            ordering: false,
            serverSide: true,
        });


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

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

            $("#frm_user_info")[0].reset()

            $("#frm_user_info [name=usr_sq]").val(row.usr_sq)
            $("#frm_user_info [name=type]").val("update")

            $("#frm_user_info [name=addUserNm]").val(row.usr_nm)
            $("#frm_user_info [name=addUserDept]").val(row.dept_sq)
            $("#frm_user_info [name=addUserId]").val(row.usr_id)
            $("#frm_user_info [name=addUserId]").prop("readonly", true)

            $("#frm_user_info [name=addUserLevel]").val(row.usr_level)
            $("#frm_user_info [name=addUserPosition]").val(row.usr_position)
            $("#frm_user_info [name=addUserTel1]").val(row.usr_tel1)
            $("#frm_user_info [name=addUserTel2]").val(row.usr_tel2)
            $("#frm_user_info [name=addSmsYn]").val(row.sms_auth_yn)
            $("#frm_user_info [name=addUserAddr1]").val(row.usr_addr1)
            $("#frm_user_info [name=addUserAddr2]").val(row.usr_addr2)
            $("#frm_user_info [name=addUseYn]").val(row.use_yn)

            myModal.show();

        });

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


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

            $("#frm_user_info [name=usr_sq]").val("")
            $("#frm_user_info [name=type]").val("create")
            $("#frm_user_info [name=addUserId]").prop("readonly", false)

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

        // SMS 일괄저장
        $("#btnSmsSave").on("click", function () {

            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/user/saveSms',
                        contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
                        method: 'POST',
                        data: { 'useYn': $("#srcUseYn").val() },
                        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') {
                                userModalHide()
                                $("#btnSearch").trigger('click')
                                Swal.fire({
                                    title: '정상 처리되었습니다.',
                                    icon: "success"

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

        });


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

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

            let isValid = true;

            if (type === 'create') {
                if ($("#frm_user_info [name=addUserPswd]").val() == "") {
                    Swal.fire({
                        title: "비밀번호를 입력하세요",
                        icon: "error",
                        draggable: true
                    })
                    return

                }

            }

            // 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/user/save',
                        contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
                        method: 'POST',
                        data: $("#frm_user_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') {
                                userModalHide()
                                $("#btnSearch").trigger('click')
                                Swal.fire({
                                    title: '정상 처리되었습니다.',
                                    icon: "success"

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


        // 유저정보삭제
        $("#userRemove").on("click", function () {

            if ($("#frm_user_info [name=usr_sq]").val() == "") {
                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: '/manage/user/remove',
                        contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
                        method: 'POST',
                        data: $("#frm_user_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') {
                                userModalHide()
                                $("#btnSearch").trigger('click')
                                Swal.fire({
                                    title: '정상 처리되었습니다.',
                                    icon: "success"

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

        });

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

            console.log('excel start')

            $.ajax({
                url: "/manage/user/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 userModalHide() {
        const modalEl = document.getElementById('userModal');
        const modal = bootstrap.Modal.getInstance(modalEl); // 기존 인스턴스 가져오기

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


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

        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() ?>