<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 class="toolbar-element search"><i class="fa fa-search"></i><span>分類名稱</span><input id="keyword" type="search" class="form-control input-sm search" placeholder="" aria-controls="myTable"></span>
    </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 class="control-delete">刪除<input type="checkbox" class="checkbox-delete-all"></th>
        </tr>
    </thead>
</table>

<div class="form-footer">
    <a class="btn btn-footer reset" href="javascript:window.location.reload(true)">重設</a>
    <button class="btn btn-footer submit" type="button" id='btnSubmit'>確定刪除</button>
</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;
    $(document).ready(function () {
        table = $('#myTable').DataTable({
            "processing": true,
            "serverSide": true,
            "ajax": "api/product_category",
            "columns": [
                {"data": "id"},
                {"data": "name", "name": "分類名稱"},
                {"data": "create_time", "name": "創建日期"},
                {"data": "update_time", "name": "更新日期"},
                {"data": "status", "name": "啟用"},
                {"data": "details", "name": "詳情", "class": "control-details"},
                {"data": "delete", "name": "刪除", "class": "control-delete"},
            ],
            "order": [
                [0, "desc"],
            ],
            "columnDefs": [
                {
                    "targets": [0],
                    "visible": false,
                    "searchable": false,
                },
                {
                    "targets": [2, 3, 4],
                    "visible": true,
                    "searchable": false,
                    "orderable": true,
                },
                {
                    "targets": [5, 6],
                    "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) {
                $.each(ids, function (k, v) {
                    $('.checkbox-delete').each(function (i, e) {
                        if (v === $(e).attr('id')) {
                            $(e).prop('checked', true);
                            return false;
                        }
                    });
                });

                $('button[id^="details-"]').on('click', function (event) {
                    event.preventDefault();
                    var newForm = $('<form>', {
                        'action': '/product_category/edit',
                        'method': 'post',
                    }).append($('<input>', {
                        'name': 'id',
                        'value': this.id.replace('details-', ''),
                        'type': 'hidden'
                    }));
                    $(document.body).append(newForm);
                    newForm.submit();
                });
            },
        });
        $(".btn-create").on('click', function () {
            window.location.replace("/product_category/add");
            return false;
        });

        $('#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'));
		
		

    });

    var ids = [];
    $(document).on('click', '#btnSubmit', function () {
        if (ids.length > 0) {
            if (confirm('確定要刪除這(些)項目?')) {
                ids = ids.join();
//                console.log('ids:', ids);
//                return false;
                var newForm = $('<form>', {
                    'action':  '/product_category/delete',
                    'method': 'post',
                }).append($('<input>', {
                    'name': 'ids',
                    'value': ids,
                    'type': 'hidden'
                }));
                $(document.body).append(newForm);
                newForm.submit();
            }
        } else {
            alert('請選擇要刪除的項目。');
        }
    });

    $(document).on('change', '.checkbox-delete', function () {
        var id = $(this).attr('id');
        if (this.checked && ids.indexOf(id) === -1) {
            ids.push(id);
        } else {
            var idx = ids.indexOf(id);
            if (idx > -1) {
                ids.splice(idx, 1);
            }
            checkall = false;
            $('.checkbox-delete-all').prop('checked', false);
        }
        if (ids.length > 0) {
            $.each(ids, function (i, e) {
                if (e === id) {
                    $(this).prop('checked', true);
                }
            });
        }
    });

    var checkall = false;
	$(document).on('change','.checkbox-delete-all',function(){
		if(this.checked){
			 $('.checkbox-delete').each(function (i, e) {
				 if (!e.disabled){
				console.log("this is e's id" + e.id);
				ids.push(e.id);
				 }
            });
        }else{
			ids =[];
		}
		 checkall = this.checked;
		  $('.checkbox-delete').each(function (i, e) {
            if (!e.disabled) {
                $(this).prop('checked', checkall);
            }
        });
	});
	
	
	
	
	
	/*
    $(document).on('change', '.checkbox-delete-all', function () {
        if (this.checked) {
            getRemoteData(
                    "/api/product_category/getallids",
                    {},
                    getAllIdsOk,
                    getRemoteDataFail
                    );
        } else {
            ids = [];
        }
        checkall = this.checked;
        $('.checkbox-delete').each(function (i, e) {
            if (!e.disabled) {
                $(this).prop('checked', checkall);
            }
        });
    });
	*/
    function getAllIdsOk(Ids) {
        ids = Ids.slice();
    }


    $(document).on('input', '#keyword', function () { //onchange & onblur don't work
        table.search($(this).val().trim()).draw();
    });

    $(document).on('click', '.fa-search', function () {
        $('#keyword').trigger('input');
    });
</script>
