var barTable;
var barRowID;
var barPos;

$(document).ready(function () {
    loadDataTable();

    function addBtnFun() {
        $("#bar_name").val('').trigger('change');
        $("#bar_code").val('').trigger('change');
        $("#bar_method").val('add');

        barTable = $('#myTable').dataTable();

        $('#myModal').modal('toggle');
    }

    $("#saveBtn").click(function () {
        var bar_uid = $("#bar_uid").val();
        var bar_name = $("#bar_name").val();
        var bar_code = $("#bar_code").val();
        var bar_area = $("#bar_area").val();
        var method = $("#bar_method").val();

        var err_msg = "";

        if (bar_name == "") {
            err_msg = "請輸入Bar名稱!";
        }

        if (bar_code == "") {
            err_msg = "請輸入Bar代碼!";
        }


        if (err_msg != "") {
            alert(err_msg);
            return;
        }

        var formData = {
            method: method,
            bar_uid: bar_uid,
            bar_name: bar_name,
            bar_code: bar_code
        }

        $.ajax({
            url: "/BackEndApi/barGetAddEditDel",
            type: "POST",
            data: formData,
            success: function (data, textStatus, jqXHR) {
                if (data.ret == "yes") {
                    alert('儲存完成');

                    var obj = data.data;

                    if (method == "add") {

                        barTable.fnAddData(obj);
                    } else {
   
                        barTable.fnUpdate(obj, barPos);
                    }

                    

                    $('#myModal').modal('toggle');
                } else {
                    alert(data.message);
                    if (data.err_code == "9999") {
                        location.href = "login.aspx?isLogout=true";
                    }
                }

            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert('網路或伺服器發生錯誤，請稍後重試!');
            }
        });
    });

    function buttonClick(obj) {
        var type = obj.getAttribute('data-method');
        var uid = obj.getAttribute('data-uid');

        barTable = $('#myTable').dataTable();
        barRowID = $('#' + uid);
        
        barPos = barTable.fnGetPosition($('#' + uid)[0]);

        if (type == "del") {
            if (confirm('確定刪除此筆資料?')) {
                var formData = {
                    method: "del",
                    bar_uid: uid
                }

                $.ajax({
                    url: "/BackEndApi/barGetAddEditDel",
                    type: "POST",
                    data: formData,
                    success: function (data, textStatus, jqXHR) {
                        if (data.ret == "yes") {

                            var row = barTable.api().row(barRowID).remove().draw(false);
                            alert('刪除成功');
                        } else {
                            alert(data.message);

                            if (data.err_code == "9999") {
                                location.href = "/BackEnd/Index";
                            }
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert('網路或伺服器發生錯誤，請稍後重試!');
                    }
                });
            }
        }

        if (type == "edit") {
            $("#bar_uid").val(uid);
            $("#bar_method").val(type);

            var formData = {
                method: "get",
                bar_uid: uid
            }

            $.ajax({
                url: "/BackEndApi/barGetAddEditDel",
                type: "post",
                data: formData,
                success: function (data, textStatus, jqXHR) {
                    if (data.ret == "yes") {
                        var obj = data.data;

                        $("#bar_name").val(obj.bar_name).trigger('change');
                        $("#bar_code").val(obj.bar_code).trigger('change');
                        $("#bar_area").val(obj.bar_area);

                        $('#myModal').modal('toggle');
                    } else {
                        alert(data.message);

                        if (data.err_code == "9999") {
                            location.href = "/BackEnd/Index";
                        }
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert('網路或伺服器發生錯誤，請稍後重試!');
                }
            });
        }

    }

    function loadDataTable() {
        var dataTables = {
            init: function init() {

                this.bindUIActions();
            },
            bindUIActions: function bindUIActions() {

                // event handlers
                this.table = this.handleDataTables();

                // add buttons
                this.table.buttons().container().appendTo('#dt-buttons').unwrap();
            },
            handleDataTables: function handleDataTables() {
                //$('#myTable').append("<tfoot><tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr></tfoot>");
                return $('#myTable').DataTable({
                    dom: '<\'text-muted\'Bif>\n        <\'table-responsive\'trl>\n        <\'mt-4\'p>',
                    lengthChange: true,
                    lengthMenu: [[25, 50, 100, -1], [25, 50, 100, "All"]],
                    pageLength: 50,
                    buttons: [
                        //{
                        //    text: '休假設定',
                        //    action: function (e, dt, node, config) {
                        //        vacationBtnFun();

                        //    }
                        //},
                        {
                            text: '新增酒吧',
                            action: function (e, dt, node, config) {
                                addBtnFun();

                            }
                        }
                    ],
                    language: {
                        paginate: {
                            previous: '<i class="fa fa-lg fa-angle-left"></i>',
                            next: '<i class="fa fa-lg fa-angle-right"></i>'
                        },
                        buttons: {
                            copyTitle: 'Data copied',
                            copyKeys: 'Use your keyboard or menu to select the copy command'
                        }
                    },
                    autoWidth: false,
                    ajax: {
                        url: '/BackEndApi/barList',
                        type: 'POST',
                        data: function (d) {
                            Object.assign(d, {
                                ticket_type: ''
                            });

                            return d;
                        },
                        dataSrc: 'bars'
                    },
                    rowId: 'bar_uid',
                    deferRender: true,
                    initComplete: function () {
                        $('#myTable').on('click', 'a', function () {
                            buttonClick(this);
                        });

                        $('#myTable').on('click', 'input[name="selectedRow[]"]', function () {
                            checkboxClick(this);
                        });
                    },
                    order: [[3, 'asc']],
                    info: true,
                    search: "搜尋:",
                    searching: true,
                    columns: [{ data: 'bar_code', className: 'align-middle', orderable: false, searchable: false }, { data: 'bar_area', className: 'align-middle text-left', orderable: true, searchable: false }, { data: 'bar_name', className: 'align-middle text-left', orderable: false, searchable: true }, { data: 'bar_uid', className: 'align-middle text-center', orderable: false, searchable: false }],
                    columnDefs: [
                        {
                            targets: 3,
                            orderable: false,
                            searchable: false,
                            render: function render(data, type, row, meta) {
                                var editRet = '<a class="btn btn-sm btn-secondary" href="javascript: void(0);" data-method="edit" data-uid="' + row.bar_uid + '" ><i class="fa fa-pencil-alt"></i></a>          <a  class="btn btn-sm btn-secondary"  href="javascript: void(0);" data-method="del" data-uid="' + row.bar_uid + '" ><i class="far fa-trash-alt"></i></a>';


                                return editRet;
                            }
                        }
                        
                    ],

                });
            },
            handleSearchRecords: function handleSearchRecords() {
                var self = this;

                $('#table-search, #filterBy').on('keyup change focus', function (e) {
                    var filterBy = $('#filterBy').val();
                    var hasFilter = filterBy !== '';
                    var value = $('#table-search').val();

                    self.table.search('').columns().search('').draw();

                    if (hasFilter) {
                        self.table.columns(filterBy).search(value).draw();
                    } else {
                        self.table.search(value).draw();
                    }

                });
            }
        }

        dataTables.init();
    }
});