<!-- <div class="form-group mas-col">
    <label for="student_centre_code" class="col-sm-2 control-label">分校名稱</label>
    <div class="col-sm-10">
        <select id="student_centre_code" name="student_centre_code" style="width: 100%" select2>
            <option value="-1">-- 請選擇分校 --</option>
            <?php foreach ($student_centres as $k => $v) : ?>
                <?php //TODO: id => student_id 
                echo sprintf(
                    '<option value="%s"%s>%s - %s</option>',
                    $v['code'],
                    $v['code'] == $student_centre_code ? ' selected' : '',
                    $v['code'],
                    $v['name']
                );
                ?>
            <?php endforeach; ?>
        </select>
    </div>
</div> -->
<div class="form-group mas-col">
    <label for="student_code" class="col-sm-2 control-label">學生編號</label>
    <div class="col-sm-4" style="border-right: 5px solid white;">
        <input type="text" class="form-control mas-input" id="student_code" name="student_code" value="" />
    </div>
    <label for="student_name" class="col-sm-2 control-label">學生名稱</label>
    <div class="col-sm-4">
        <input type="text" class="form-control mas-input" id="student_name" name="student_name" value="" />
    </div>
</div>
<div class="form-group" style="text-align: right;">
    <div style="margin-top: 10px"></div>
    <a class="btn btn-success" id='btnSearchStudent'>搜尋</a>
</div>
<br />
<div class="title align-left" style="font-size: 15px; padding: 0 15px;">學生資料</div>
<div id="studentTable-scroller" style="height: 400px;overflow-y: auto;">
    <table class="table table-bordered" id="studentTable">
        <thead class="thead-light" style="z-index: 30;">
            <tr>
                <th style="border-top: 0;position: sticky;top: -3px;background: white;z-index: 30000; width: 50px;">
                    <input class="checkbox-check-all" type="checkbox" style="position: relative; left: 10px; opacity: 1; background-color: rgb(253, 234, 236);">
                </th>
                <th style="border-top: 0;position: sticky;top: -3px;background: white;z-index: 30000;">學生編號</th>
                <th style="border-top: 0;position: sticky;top: -3px;background: white;z-index: 30000;">中文姓名</th>
                <th style="border-top: 0;position: sticky;top: -3px;background: white;z-index: 30000;">英文姓名</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td colspan="5" style="text-align:center">沒有任何搜尋結果</td>
            </tr>
        </tbody>
    </table>
</div>
<div class="form-group" style="text-align: right;">
    <div style="margin-top: 10px"></div>
    <a class="btn btn-success" id='btnSelectStudent'>選擇學生</a>
</div>
<div class="title align-left" style="font-size: 15px; padding: 0 15px;">已選擇學生列表</div>
<div id="selectedStudentTable-scroller" style="height: 400px;overflow-y: auto;">
    <table class="table table-bordered" id="selectedStudentTable">
        <thead class="thead-light" style="z-index: 30;">
            <tr>
                <th style="border-top: 0;position: sticky;top: -3px;background: white;z-index: 30000;">學生編號</th>
                <th style="border-top: 0;position: sticky;top: -3px;background: white;z-index: 30000;">中文姓名</th>
                <th style="border-top: 0;position: sticky;top: -3px;background: white;z-index: 30000;">英文姓名</th>
                <th style="border-top: 0;position: sticky;top: -3px;background: white;z-index: 30000;">動作</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td colspan="5" style="text-align:center">沒有任何記錄</td>
            </tr>
        </tbody>
    </table>
</div>

<script>
    function searchNoResults() {
        $('#studentTable-scroller').css('overflow-y', 'auto');
        $('#studentTable tbody').empty().append('<tr><td colspan="5" style="text-align:center">沒有任何搜尋結果</td></tr>');
    }

    function getRemoteData2(remote_url, data, callback, callbackFail) {
        $.ajax({
            //async: false,
            //timeout: 30000, //最長等候回應時間
            type: "GET", //提交類型
            url: remote_url, //提交地址
            data: data, //提交內容
            dataType: 'json', //返回數據類型
            success: function(data) { //請求完成並成功
                if (data.success) {
                    callback(data.data);
                } else {
                    callbackFail();
                }
            },
            error: function(data) { //請求返回錯誤信息
                callbackFail();
            },
            beforeSend: function(XHR) { //请求開始前执行
            },
            complete: function(XHR, status) { //请求完成后最终执行
            }
        });
    }

    function getRemoteDataFail2() {
        alert("發生錯誤");
        searchNoResults();
    }

    function searchStudent() {
        const studentCode = $('#student_code').val();
        const studentName = $('#student_name').val();
        const studentCentreCode = $('#student_centre_code option:selected').val();

        if (studentCode === "" && studentName === "" && studentCentreCode === "-1") {
            alert("未有輸入搜索資料");
            searchNoResults();
            return;
        }

        getRemoteData2(
            "/search_student", {
                'student_no': studentCode,
                'student_name': studentName,
                // 'student_centre_code': studentCentreCode
            },
            searchStudentSuccess,
            getRemoteDataFail2
        );
    }

    function searchStudentSuccess(data) {
        var row;
        if ((data.error == 1) || (data.result.length == 0)) {
            alert("找不到紀錄 !!");
            searchNoResults();
        } else {
            $('#studentTable-scroller').css('overflow-y', 'scroll');
            data.result.forEach(function(record) {
                row = '<tr>';
                row += '<td><input type="hidden" name="search_student_id" value="' + record.id + '"><input class="checkbox-check" type="checkbox" name="student_code" value="' + record.student_no + '" style="top: 0;" /></td>';
                row += '<td><span>' + (record.student_no ? record.student_no : '') + '</span></td>';
                row += '<td><span>' + (record.chi_name ? record.chi_name : '') + '</span></td>';
                row += '<td><span>' + (record.eng_name ? record.eng_name : '') + '</span></td>';
                row += '</tr>';
                //alert (JSON.stringify(record));
                $('#studentTable tbody').append(row);
            });
        }
    }

    $("#btnSearchStudent").on('click', function() {
        $('#studentTable tbody').empty();
        $('#studentTable-scroller').css('overflow-y', 'auto');
        searchStudent();
    });
</script>

<script>
    let emptySelectedStudents = true;

    $("#studentTable-scroller .checkbox-check-all").change(function() {
        if ($(this).is(":checked")) {
            $("#studentTable-scroller .checkbox-check").prop("checked", true);
        } else {
            $("#studentTable-scroller .checkbox-check").prop("checked", false);
        }
    });

    $("#btnSelectStudent").on('click', function() {
        new Promise(function(resolve, reject) {
            const checkedStudents = $('#studentTable-scroller .checkbox-check:checked');
            if (checkedStudents.length) {
                checkedStudents.each(function(index, element) {
                    const student_id = $(element).prev().val();
                    const tr = $(element).closest('tr');
                    const student_no = tr.find('td').eq(1).find('span').text();
                    const student_chi_name = tr.find('td').eq(2).find('span').text();
                    const student_eng_name = tr.find('td').eq(3).find('span').text();
                    if (!student_ids.includes(student_id)) {
                        student_ids.push(student_id);

                        if (emptySelectedStudents) {
                            emptySelectedStudents = false;
                            $('#selectedStudentTable tbody').empty();
                        }
                        $('#selectedStudentTable tbody').append(`<tr data-id="${student_id}"><td>${student_no}</td><td>${student_chi_name}</td><td>${student_eng_name}</td><td><a class="selected-student-delete clickable">刪除</a></td></tr>`);
                    }
                });
            }
            $("#studentTable-scroller .checkbox-check-all").prop("checked", false);
            $("#studentTable-scroller .checkbox-check").prop("checked", false);

            resolve();
        }).then(function() {
            $('.selected-student-delete').unbind('click').on('click', function() {
                console.log('selected student delete');
                // find the value
                const delete_student_id = $(this).closest('tr').data('id');

                // find the index of the value in the array and remove it by index
                let index = student_ids.indexOf(`${delete_student_id}`);
                console.log(delete_student_id);
                console.log(student_ids);
                console.log(index);
                if (index !== -1) {
                    student_ids.splice(index, 1);
                }
                $(this).closest('tr').remove();

                if (student_ids.length === 0) {
                    emptySelectedStudents = true;
                    $('#selectedStudentTable tbody').append('<tr><td colspan="5" style="text-align:center">沒有任何記錄</td></tr>');
                }
            });
        });
    });
</script>

<style>
    .checkbox-check {
        top: 0 !important;
        left: 10px !important;
        position: relative !important;
        opacity: 1 !important;
    }
</style>