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

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

    td {
        text-align: center;
    }

    #smsList tbody tr {
        cursor: pointer;
    }

    .blockUI {
        z-index: 1500 !important;
    }

    .ellipsis {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 180px;
    }
</style>

<h1>현장확인조직별실적</h1>

<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" method="post" id="frm_srch_info">
                <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
                                $selected = "";
                                foreach ($bonbu as $d): ?>
                                    <?php if ($pBonbu === $d['dept_sq']):
                                        $selected = "selected";
                                    else:
                                        $selected = "";
                                    endif; ?>
                                    <option value="<?= $d['dept_sq'] ?>" <?= $selected; ?>><?= $d['dept_nm'] ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-6">
                            <select class="form-control" name="dept_sq" id="dept_sq">
                                <?php if (!empty($pBonbu)): ?>
                                    <option value="">선택</option>
                                    <?php foreach ($team as $t): ?>
                                        <?php
                                        $selected2 = "";
                                        if ($t['pdept_sq'] === $pBonbu): ?>
                                            <?php if ($pDeptSq === $t['dept_sq']):
                                                $selected2 = "selected";
                                            else:
                                                $selected2 = "";
                                            endif; ?>
                                            <option value="<?= $t['dept_sq'] ?>" <?= $selected2 ?>><?= $t['dept_nm'] ?></option>
                                        <?php endif; ?>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <option value="">선택</option>
                                <?php endif; ?>
                            </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" <?= $schDateGb == '1' ? 'selected' : '' ?>>예약일자</option>
                        <option value="2" <?= $schDateGb == '2' ? 'selected' : '' ?>>등록일자</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" value="<?= $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" value="<?= $edate ?>" />
                        </div>
                    </div>
                </div>

                <div class="col-md-1 d-grid">
                    <button type="submit" 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 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">
            <div class="row">
                <table class="table table-hover table-striped table-bordered">
                    <!-- <caption>조직별 실적</caption> -->
                    <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>
                        <?php
                        if (!empty($st_list)) {
                            $nRow = 1;
                            foreach ($st_list as $row) {

                                $pars = [];
                                if ($row['depth'] == '1') {
                                    $rowPars = array_merge($pars, array('bonbu' => $row['dept_sq']));
                                } else {
                                    $rowPars = array_merge($pars, array('bonbu' => $row['pdept_sq'], 'dept_sq' => $row['dept_sq']));
                                }

                                echo '<tr onmouseover="this.className=\'highlight\'" onmouseout="this.className=\'normal\'"  style="cursor:pointer" onclick="tr_onclick(\'' . make_query_string($rowPars) . '\');">';
                                echo '<td>' . $nRow . '</td>';
                                echo '<td style="text-align:left">' . str_replace(' ', '&nbsp;', $row['dept_nm']) . '</td>';
                                echo '<td>' . $row['region_cnt'] . '</td>';
                                echo '<td>' . (empty($row['rcpt_cnt']) ? '-' : $row['rcpt_cnt']) . '</td>';
                                echo '<td>' . (empty($row['resv_cancel_cnt']) ? '-' : $row['resv_cancel_cnt']) . '</td>';
                                echo '<td>' . (empty($row['resv_assign_cnt']) ? '-' : $row['resv_assign_cnt']) . '</td>';
                                echo '<td>' . (empty($row['prev_visit_cnt']) ? '-' : $row['prev_visit_cnt']) . '</td>';
                                echo '<td>' . (empty($row['next_visit_cnt']) ? '-' : $row['next_visit_cnt']) . '</td>';
                                echo '<td>' . (empty($row['next_shoot_cnt']) ? '-' : $row['next_shoot_cnt']) . '</td>';
                                echo '<td>' . (empty($row['shoot_cnt']) ? '-' : $row['shoot_cnt']) . '</td>';
                                echo '<td>' . (empty($row['delay_confirm_cnt']) ? '-' : $row['delay_confirm_cnt']) . '</td>';
                                echo '<td>' . (empty($row['fail_confirm_cnt']) ? '-' : $row['fail_confirm_cnt']) . '</td>';
                                echo '<td>' . (empty($row['confirm_cnt']) ? '-' : $row['confirm_cnt']) . '</td>';
                                echo '</tr>';
                                $nRow++;
                            }
                        } else {
                            echo "<tr><td colspan='13'>조회된 결과가 없습니다.</td></tr>";
                        }
                        ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>


<script type="text/javascript">

    // const tpl = document.querySelector('.my-loader-template')
    let date = new Date()
    const teamArr = <?= json_encode($team, JSON_UNESCAPED_UNICODE); ?>;

    $(function () {

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

            const value = e.target.value

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

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

        });


        // 엑셀 다운로드 click
        $("#excel-download").on("click", function () {
            $.ajax({
                url: "/results/dept/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 tr_onclick(pars) {
        location.href = '/article/receipt/lists' + pars;
    }

    // 엑셀 다운로드
    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() ?>