<div class="title">練習管理</div>
<ul class="table-toolbar" style="text-align: left;">
    <li>
        &nbsp;
    </li>
    <li>
        <span>單元名稱：</span>
        <select id="unit" class="datatables-custom unitnames">            
        </select>
    </li>
    <li>
        <span>課程名稱：</span>
        <select id="course" class="datatables-custom coursenames">            
        </select>
    </li>
    <li>
        <span>老師名稱：</span>
        <select id="teacher" class="datatables-custom teachernames">            
        </select>
    </li>
</ul>
<table id="myTable" class="display table datatables" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>編號</th>
            <th>練習名稱</th>
            <th>練習日期</th>    
            <th>單元名稱</th>
            <th>課程名稱</th>
            <th>老師名稱</th>            
            <th>啟用</th>
            <th>詳情</th>
        </tr>
    </thead>
</table>

<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 id="modaltitle" class="modal-title">Modal Header</h4>
            </div>
            <div id="modalbody" class="modal-body">

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>

    </div>
</div>

<script>
    function getRemoteData(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 getRemoteDataFail() {
        alert("發生錯誤");
    }

    var table, course = [], unit = [], teacher = [];
    $(document).ready(function () {
        var li = $('#sidebar-menu li').filter(function (i) {
            return $(this).find('.menu-dropdown').find('.menu-text').text() === '練習管理';
        });
        li.addClass('active open');

        table = $('#myTable').DataTable({
            "processing": true,
            "serverSide": true,
            "ajax": "api/exercise",
            "columns": [
                {"data": "id"},
                {"data": "exercise_name", "name": "練習名稱"},
                {"data": "exercise_date", "name": "練習日期"},
                {"data": "unit_name", "name": "單元名稱"},
                {"data": "course_name", "name": "課程名稱"},
                {"data": "teacher_name", "name": "老師名稱"},               
                {"data": "status", "name": "啟用"},
                 {"data": "details", "name": "詳情", "class": "control-details"},
            ],
            "order": [
                [0, "desc"],
            ],
            "columnDefs": [
                {
                    "targets": [0],
                    "visible": false,
                    "searchable": false,
                },
                {
                    "targets": [1, 3, 4, 5],
                    "visible": true,
                    "searchable": true,
                    "orderable": true,
                },
                {
                    "targets": [2,6],
                    "visible": true,
                    "searchable": false,
                    "orderable": true,
                },
                {
                    "targets": [7],
                    "visible": true,
                    "searchable": false,
                    "orderable": false,
                },
            ],
            language: {
                "processing": "處理中...",
                "loadingRecords": "載入中...",
                "lengthMenu": "顯示數量 _MENU_ ",
                "zeroRecords": "沒有符合的結果",
                "info": "顯示 _START_-_END_（總數：_TOTAL_）",
                "infoEmpty": "0 項結果",
                "infoFiltered": "(從 _MAX_ 項結果中過濾)",
                "infoPostFix": "",
                "search": "搜尋:",
                "paginate": {
                    "first": "<<",
                    "previous": "<",
                    "next": ">",
                    "last": ">>"
                },
                "aria": {
                    "sortAscending": ": 升冪排列",
                    "sortDescending": ": 降冪排列"
                }
            },
            "pagingType": "four_button",
            "drawCallback": function (settings) {
            },
        });

        getRemoteData('/api/exercise/getfilteringdata', {}, getFilteringdataOk, getRemoteDataFail);

        $('#myTable_filter').hide();
        $('#myTable_info').parent('.col-sm-5').css({"float": "right", "text-align": "right"});
        $('.dataTables_length').wrap('<div class="row dataTables_footer"></div>').wrap('<div class="col-sm-7"></div>').after($('#myTable_paginate'));
        $('#myTable').after($('.dataTables_footer'));
    });

    function getFilteringdataOk(data) {
        $('#unit').empty().append('<option value="">---</option>');
        unit = [];
        $.each(data['unit'], function (k, v) {
            if (unit.indexOf(v.title) === -1 && v.title !== '') {
                unit.push(v.title);
                var o = new Option(v.title, v.title);
                $(o).html(v.title);
                $('#unit').append(o);
            }
        });
        $('#course').empty().append('<option value="">---</option>');
        course = [];
        $.each(data['course'], function (k, v) {
            if (course.indexOf(v.name) === -1 && v.name !== '') {
                course.push(v.name);
                var o = new Option(v.name, v.name);
                $(o).html(v.name);
                $('#course').append(o);
            }
        });
        $('#teacher').empty().append('<option value="">---</option>');
        teacher = [];
        $.each(data['teacher'], function (k, v) {
            if (teacher.indexOf(v.name) === -1 && v.name !== '') {
                teacher.push(v.name);
                var o = new Option(v.name, v.name);
                $(o).html(v.name);
                $('#teacher').append(o);
            }
        });
    }

    function exDetailSuccessful(data) {
        console.log('data:', data);
//         return false;
        var title = '';
        var html = '<ul>';
        $.each(data, function (i, d) {
            title = d.title;
            html += "<li>問題: <p>" + d.question + "</p><p>選擇: " + d.answer + "</p><p>答案: " + d.correct + "</p></li>";
            //   console.log('title:'+d.title);
        });
        html += "</ul>";
        $("#myModal").modal();
        $('#modaltitle').text('練習名稱: ' + title);
        $('#modalbody').html(html);
    }

    function detailPage(exId) {
//        alert('exid:'+exId);
//        return false;
        getRemoteData(
                '/api/exercise/detail',
                {'exId': exId},
                exDetailSuccessful,
                getRemoteDataFail
                );
    }

    $(document).on('click', '.details', function () {
        detailPage($(this).data('id'));
    });

    $(document).on('change', '.datatables-custom', function () {
        doFilter();
    });

    function doFilter() {
        var unit = $('#unit').val();
        var teacher = $('#teacher').val();
        var course = $('#course').val();
		let s = table.columns().search('');
		if (unit !== '') {
			s = s.columns(3).search(unit);
		}
		if (course !== '') {
			s = s.columns(4).search(course);
		}
		if (teacher !== '') {
			s = s.columns(5).search(teacher);
		}
		s.draw();
    }
</script>
