<div class="title">筆記管理</div>
<ul class="table-toolbar" style="text-align: left;">
    <li>
        <a class="toolbar-element btn btn-default btn-create"><i class="fa fa-plus-circle" style="margin-right: 8px;"></i>新增</a>
    </li>
    <li>
        <span>單元名稱：</span>
        <select id="unit" class="datatables-custom unitnames">            
        </select>
    </li>
    <li>
        <span>課程名稱：</span>
        <select id="name" class="datatables-custom coursenames">            
        </select>
    </li>
    <li>
        <span>課程主分類：</span>
        <select id="category" class="datatables-custom coursecategorynames">            
        </select>
    </li>
    <li>
        <span>課程次分類：</span>
        <select id="subcategory" class="datatables-custom subcoursecategorynames">            
        </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>
            <th>詳情</th>            
        </tr>
    </thead>
</table>
<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, unit = [], course = [], coursecategory = [], coursesubcategory = [];
    $(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/note",
            "columns": [
                {"data": "id"},
				{"data": "tenant_no", "name": "分校"},
                {"data": "note_name", "name": "筆記名稱"},
                {"data": "unit_name", "name": "單元名稱"},
                {"data": "category_name", "name": "課程主分類"},
                {"data": "subcategory_name", "name": "課程次分類"},
                {"data": "course_name", "name": "課程名稱"},
                {"data": "status", "name": "啟用"},
                {"data": "details", "name": "詳情", "class": "control-details"},
            ],
            "order": [
                [0, "desc"],
            ],
            "columnDefs": [
                {
                    "targets": [0],
                    "visible": false,
                    "searchable": false,
                },
                {
                    "targets": [2, 3, 4, 5, 6],
                    "visible": true,
                    "searchable": true,
                    "orderable": true,
                },
                {
                    "targets": [1, 7],
                    "visible": true,
                    "searchable": false,
                    "orderable": true,
                },
                {
                    "targets": [8],
                    "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) {
                $('.details').on('click', function (event) {
                    event.preventDefault();
                    var newForm = $('<form>', {
                        'action': '/note/edit',
                        'method': 'post',
                    }).append($('<input>', {
                        'name': 'id',
                        'value': $(this).data('id'),
                        'type': 'hidden'
                    }));
                    $(document.body).append(newForm);
                    newForm.submit();
                });
            },
        });
        $(".btn-create").on('click', function () {
            window.location.replace("/note/add");
            return false;
        });

        getRemoteData('/api/note/getfilteringdata', {
        	'tenantno': '<?=$tenantno;?>',
		}, 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);
            }
        });
        $('#name').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);
                $('#name').append(o);
            }
        });
        $('#category').empty().append('<option value="">---</option>');
        coursecategory = [];
        $.each(data['category'], function (k, v) {
            if (coursecategory.indexOf(v.name) === -1 && v.name !== '') {
                coursecategory.push(v.name);
                var o = new Option(v.name, v.name);
                $(o).html(v.name);
                $('#category').append(o);
            }
        });
        $('#subcategory').empty().append('<option value="">---</option>');
        coursesubcategory = [];
        $.each(data['subcategory'], function (k, v) {
            if (coursesubcategory.indexOf(v.name) === -1 && v.name !== '') {
                coursesubcategory.push(v.name);
                var o = new Option(v.name, v.name);
                $(o).html(v.name);
                $('#subcategory').append(o);
            }
        });
    }

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

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