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

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

    /* 테이블 헤더 좌우 여백 조정 */
    #userList thead th {
        padding-left: 4px !important;
        padding-right: 4px !important;
    }

    td {
        text-align: center;
    }

    #userList tbody tr {
        cursor: pointer;
    }

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

    .swal2-cancel {
        background-color: #ff0000 !important;
        color: #fff !important;
    }

    /* PC에서 가로 스크롤이 잘리는 대표 구간들 강제 해제 */
    .main-card,
    .card,
    .card-body {
        overflow-x: visible !important;
    }

    /* 만약 레이아웃 wrapper가 숨기고 있으면 이것도 */
    .app-main__outer,
    .app-main__inner,
    .app-main {
        overflow-x: visible !important;
    }

    /* flex 환경에서 필수 */
    .app-main,
    .app-main__outer,
    .app-main__inner,
    .card,
    .card-body {
        min-width: 0;
    }

    /* 검색 영역 행마다 구분선 추가 */
    #frm_srch_info .row.g-3 {
        padding: 12px 0;
        border-bottom: 1px solid #e9ecef;
    }

    #frm_srch_info .row.g-3:last-child {
        border-bottom: none;
    }
</style>

<div class="col-md-12 col-xl-12">
    <div class="main-card mb-3 card">
        <div class="card-header bg-white border-bottom shadow-sm">
            <div class="d-flex flex-wrap align-items-center gap-3 card-header-tab">
                <div>
                    <h4 class="mb-0 fw-bold text-dark">현장확인인원별배정현황</h4>
                </div>
            </div>
        </div>
        <div class="card-body">
            <form id="frm_srch_info" onsubmit="return false;">

                <!-- 1줄 -->
                <div class="row g-3 mb-3">
                    <!-- 관할조직 -->
                    <div class="col-md-2">
                        <label class="form-label mb-1 text-sm fw-semibold text-muted">관할조직</label>
                        <div class="row g-2">
                            <div class="col-6">
                                <select class="form-control form-control-sm" 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 form-control-sm" name="dept_sq" id="dept_sq">
                                    <option value="">선택</option>
                                </select>
                            </div>
                        </div>
                    </div>

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

                    <!-- 기준일자 -->
                    <div class="col-md-3">
                        <label class="form-label mb-1 text-sm fw-semibold text-muted">기준일자</label>
                        <div class="row g-2">
                            <div class="col-5">
                                <input type="date" class="form-control form-control-sm" 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 form-control-sm" id="edate" name="edate">
                            </div>
                        </div>
                    </div>

                    <!-- 지역검색 -->
                    <div class="col-md-4">
                        <label class="form-label mb-1 text-sm fw-semibold text-muted">지역검색</label>
                        <div class="row g-2">
                            <div class="col-4">
                                <select class="form-control form-control-sm" 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 form-control-sm" name="srcGugun" id="srcGugun">
                                    <option value="">시/군/구</option>
                                </select>
                            </div>
                            <div class="col-4">
                                <select class="form-control form-control-sm" name="srcDong" id="srcDong">
                                    <option value="">읍/면/동</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 2줄 -->
                <div class="row g-3">
                    <!-- 검색유형 -->
                    <div class="col-md-1">
                        <label class="form-label mb-1 text-sm fw-semibold text-muted">검색유형</label>
                        <select class="form-control form-control-sm" 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 text-sm fw-semibold text-muted">검색어</label>
                        <input type="text" class="form-control form-control-sm" name="srchTxt" placeholder="검색어 입력">
                    </div>

                    <!-- 검색버튼 -->
                    <div class="col-md-1 d-flex align-items-end">
                        <button type="button" class="btn btn-primary btn-sm w-100" 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 bg-white border-bottom shadow-sm">
            <div class="d-flex flex-wrap align-items-center w-100 justify-content-between card-header-tab">
                <h4 class="mb-0 fw-bold text-dark">사용자 목록</h4>
                <div class="d-flex align-items-center gap-2 ms-auto">
                    <button class="btn btn-sm btn-outline-success" id="excel-download">
                        <i class="fa fa-fw" aria-hidden="true" title="file-excel-o"></i>
                        엑셀다운로드
                    </button>
                </div>
            </div>
        </div>
        <div class="card-body">
            <table id="userList" class="table table-hover table-striped table-bordered">
                <thead>
                    <tr>
                        <th rowspan="2">순번</th>
                        <th rowspan="2">아이디</th>
                        <th rowspan="2">이름</th>
                        <th colspan="5" style="text-align: center;">오전</th>
                        <th colspan="8" style="text-align: center;">오후</th>
                        <th rowspan="2">합계</th>
                    </tr>
                    <tr>
                        <th width="50">무관</th>
                        <th width="50">9</th>
                        <th width="50">10</th>
                        <th width="50">11</th>
                        <th width="50">12</th>

                        <th width="50">무관</th>
                        <th width="50">1</th>
                        <th width="50">2</th>
                        <th width="50">3</th>
                        <th width="50">4</th>
                        <th width="50">5</th>
                        <th width="50">6</th>
                        <th width="50">7</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');
    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: true,
            pageLength: 25,
            ajax: {
                url: '/results/assign/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()
                }
            },
            columnDefs: [
                { targets: '_all', defaultContent: "" },
                { className: 'text-center', targets: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] },
            ],
            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: 'AMETC' },
                { data: 'AM09' },
                { data: 'AM10' },
                { data: 'AM11' },
                { data: 'AM12' },
                { data: 'PMETC' },
                { data: 'PM01' },
                { data: 'PM02' },
                { data: 'PM03' },
                { data: 'PM04' },
                { data: 'PM05' },
                { data: 'PM06' },
                { data: 'PM07' },
                { data: 'TODAY' },
            ],
            paging: true,
            searching: false,
            ordering: false,
        });


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



            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/assign/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);
                    downloadExcelWithHeader(result.data);
                }
            });

        });

    });

    // 엑셀 다운로드
    function downloadExcelWithHeader(dataRows) {
        // 1) 헤더 (16컬럼)
        const header1 = [
            "아이디", "이름",
            "오전", "", "", "", "",
            "오후", "", "", "", "", "", "", "",
            "합계"
        ];

        const header2 = [
            "", "",
            "무관", "9", "10", "11", "12",
            "무관", "1", "2", "3", "4", "5", "6", "7",
            ""
        ];

        // 2) 바디 (16컬럼 정확히 맞춤)
        const body = dataRows.map(r => ([
            r.usr_id,
            r.usr_nm,
            r.AMETC, r.AM09, r.AM10, r.AM11, r.AM12,
            r.PMETC, r.PM01, r.PM02, r.PM03, r.PM04, r.PM05, r.PM06, r.PM07,
            r.TODAY
        ]));

        const aoa = [header1, header2, ...body];

        // 3) 시트 생성
        const ws = XLSX.utils.aoa_to_sheet(aoa);

        // 4) 병합(colspan / rowspan)
        ws["!merges"] = [
            // 아이디, 이름 (rowspan 2)
            { s: { r: 0, c: 0 }, e: { r: 1, c: 0 } }, // A1:A2
            { s: { r: 0, c: 1 }, e: { r: 1, c: 1 } }, // B1:B2

            // 오전 (colspan 5)
            { s: { r: 0, c: 2 }, e: { r: 0, c: 6 } }, // C1:G1

            // 오후 (colspan 8)
            { s: { r: 0, c: 7 }, e: { r: 0, c: 14 } }, // H1:O1

            // 합계 (rowspan 2)
            { s: { r: 0, c: 15 }, e: { r: 1, c: 15 } }, // P1:P2
        ];

        ws['!cols'] = [
            { wpx: 80 },  // A: 아이디
            { wpx: 100 }, // B: 이름
            { wpx: 50 },  // C: 오전-무관
            { wpx: 50 },  // D: 오전-9
            { wpx: 50 },  // E: 오전-10
            { wpx: 50 },  // F: 오전-11
            { wpx: 50 },  // G: 오전-12
            { wpx: 50 },  // H: 오후-무관
            { wpx: 50 },  // I: 오후-1
            { wpx: 50 },  // J: 오후-2
            { wpx: 50 },  // K: 오후-3
            { wpx: 50 },  // L: 오후-4
            { wpx: 50 },  // M: 오후-5
            { wpx: 50 },  // N: 오후-6
            { wpx: 50 },  // O: 오후-7
            { wpx: 60 },  // P: 합계
        ];

        // 6) 저장
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

        XLSX.writeFile(
            wb,
            "현장확인인원별배정현황" + getDateTimeString() + ".xlsx"
        );
    }



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