<?= $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;">

                    <!-- 1줄 -->
                    <div class="row mb-3">
                        <!-- 관할조직 -->
                        <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="bonbu" id="bonbu">
                                        <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="dept_sq" id="dept_sq">
                                        <option value="">선택</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <!-- 유형 -->
                        <div class="col-md-1">
                            <label class="form-label mb-1">유형</label>
                            <select class="form-control" name="schDateGb">
                                <option value="1">예약일자</option>
                                <option value="2">등록일자</option>
                            </select>
                        </div>

                        <!-- 기준일자 -->
                        <div class="col-md-3">
                            <label class="form-label mb-1">기준일자</label>
                            <div class="row g-2">
                                <div class="col-5">
                                    <input type="date" class="form-control" id="sdate" name="sdate">
                                </div>
                                <div class="col-2 d-flex align-items-center justify-content-center">~</div>
                                <div class="col-5">
                                    <input type="date" class="form-control" id="edate" name="edate">
                                </div>
                            </div>
                        </div>

                        <!-- 지역검색 -->
                        <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>

                    <!-- 2줄 -->
                    <div class="row mb-3">
                        <!-- 검색유형 -->
                        <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>
                            </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 align-items-end">
                            <button type="button" class="btn btn-primary" id="btnSearch">검색</button>
                        </div>
                    </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">
                    <button class="mb-2 me-2 border-0 btn-transition btn btn-shadow btn-outline-success"
                        id="excel-download">
                        <i class="fa fa-fw" aria-hidden="true" title="file-excel-o"></i>엑셀다운로드
                    </button>
                </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>촬영후취소</th>
                            <th>촬영</th>
                            <th>검수지연</th>
                            <th>검수실패</th>
                            <th>검수완료</th>
                        </tr>
                    </thead>
                    <tbody>
                    </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');
    var teamArr = <?= json_encode($team, JSON_UNESCAPED_UNICODE); ?>;

    let date = new Date();

    $(function () {

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

            var dept_sq = e.target.value

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

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

        });

        $("#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":
                            $("#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;
                    }
                }
            });
        });


        let table = $('#userList').DataTable({
            language: lang_kor,
            processing: true,
            serverSide: false,
            ajax: {
                url: '/results/person/getUserList',
                type: 'GET',
                beforeSend: function () {
                    blockUI.blockPage({
                        message: tpl
                    })
                },
                complete: function () {
                    blockUI.unblockPage()
                },
                data: function (d) {
                    d.schDateGb = $("#frm_srch_info [name=schDateGb]").val()
                    d.sdate = $("#frm_srch_info [name=sdate]").val()
                    d.edate = $("#frm_srch_info [name=edate]").val()

                    d.bonbu = $("#frm_srch_info [name=bonbu]").val()
                    d.team = $("#frm_srch_info [name=dept_sq]").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, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] },
            ],
            columns: [
                {
                    "data": null,
                    "width": "50px",
                    "render": function (data, type, row, meta) {
                        return meta.row + meta.settings._iDisplayStart + 1;
                    }
                },
                { data: 'usr_id' },
                { data: 'usr_nm' },
                { data: 'rcpt_cnt' },
                { data: 'resv_cancel_cnt' },
                { data: 'resv_assign_cnt' },
                { data: 'prev_visit_cnt' },
                { data: 'next_visit_cnt' },
                { data: 'next_shoot_cnt' },
                { data: 'shoot_cnt' },
                { data: 'delay_confirm_cnt' },
                { data: 'fail_confirm_cnt' },
                { data: 'confirm_cnt' },
            ],
            // 옵션들 예시
            paging: true,
            searching: false,
            ordering: false,
            serverSide: true,
        });


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

            // myModal.show();

            location.href = '/article/receipt/lists?usr_id=' + row.usr_id;

        });

        // [검색] 버튼 눌렀을 때 다시 조회
        $('#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();
        });


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

            $.ajax({
                url: "/results/person/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 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: 80 },
            { wpx: 80 },
            { wpx: 80 },
            { wpx: 80 },
            { 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}`;
    }

    window.addEventListener("DOMContentLoaded", function () {
        // 오늘 날짜
        const today = new Date();

        // 이번 달 1일
        const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);

        // 이번 달 말일 (다음달 0일 = 이번달 말일)
        const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0);

        // yyyy-mm-dd 형태로 변환
        const toDate = (d) => d.toISOString().split("T")[0];

        document.getElementById("sdate").value = toDate(firstDay);
        document.getElementById("edate").value = toDate(lastDay);
    });

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