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

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

    #smsList tbody tr {
        cursor: pointer;
    }

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

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

<h1>SMS발송내역 관리</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" id="frm_srch_info" onsubmit="return false;">
                <!-- 소속본부 / 소속팀 -->
                <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="start_dt" name="start_dt" />
                        </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="end_dt" name="end_dt" />
                        </div>
                    </div>
                </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>
                    </select>
                </div>

                <div class="col-md-1">
                    <label class="form-label mb-1">검색어</label>
                    <input type="text" class="form-control" name="srchTxt" />
                </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 d-flex align-items-center">
            <h3 class="card-title mb-0">SMS발송내역 목록</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">엑셀다운로드</button>
            </div>
        </div>
        <div class="card-body">
            <table id="smsList" 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>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </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')
    let date = new Date()

    $(function () {

        $("#start_dt").val(dateFormat(date))
        $("#end_dt").val(dateFormat(date))

        let table = $('#smsList').DataTable({
            language: lang_kor,
            paging: true,
            searching: false,
            ordering: false,
            serverSide: true,
            ajax: {
                url: '/manage/sms/getSmsList',
                type: 'GET',
                beforeSend: function () {
                    blockUI.blockPage({
                        message: tpl
                    })
                },
                complete: function () {
                    blockUI.unblockPage()
                },
                data: function (d) {
                    d.start_dt = $("#frm_srch_info [name=start_dt]").val()
                    d.end_dt = $("#frm_srch_info [name=end_dt]").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] },
                { targets: 6, className: "ellipsis" }
            ],
            columns: [
                {
                    "data": null,
                    "width": "50px",
                    "render": function (data, type, row, meta) {
                        return meta.row + meta.settings._iDisplayStart + 1;
                    }
                },
                { data: 'send_name' },
                { data: 'dest_name' },
                { data: 'request_time' },
                { data: 'cate_nm' },
                { data: 'send_phone' },
                { data: 'dest_phone' },
                { data: 'status_nm' },
            ],
        });


        // 엑셀 다운로드 click
        $("#excel-download").on("click", function () {
            $.ajax({
                url: "/manage/sms/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);
                }
            });
        });


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

    });

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

        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}`;
    }


    function dateFormat(date) {
        let dateFormat2 = date.getFullYear() +
            '-' + ((date.getMonth() + 1) < 9 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1)) +
            '-' + ((date.getDate()) < 9 ? "0" + (date.getDate()) : (date.getDate()));
        return dateFormat2;
    }


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