
var mainItemTable;
var mainItemRowID;
var mainItemRowPos;

var subItemTable;
var subItemRowID;
var subItemRowPos;
$(document).ready(function () {
    deptList();

    $('#subItemListNewBtn').on('click', function () {
        $("#clientSubItem_method").val('add');
        $('#clientSubItemModal').modal('toggle');
    });
    
    $('#maintItemNewModal').on('click', function () {
        $("#mainItem_method").val('add');
        $("#dept_uid").val($("#dept_select").val()).trigger('change');


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

    $('#mainItemDialogSaveBtn').on('click', function () {
        var method = $('#mainItem_method').val();
        var dept_uid = $("#dept_uid").val();
        var mainItem_uid = $('#mainItem_uid').val();
        var mainItem_name = $('#modal_mainItem_name').val();

        if (mainItem_name == "") {
            alert('請輸入主項目名稱');
            retur;
        }

        var formData = {
            method: method,
            dept_uid: dept_uid,
            mainItem_uid: mainItem_uid,
            mainItem_name: mainItem_name
        }

        $.ajax({
            url: "/AuthApi/addEditDelGetMainItem",
            type: "post",
            data: formData,
            success: function (data, textStatus, jqXHR) {
                if (data.ret == "yes") {
                    var obj = data.mainItems[0];

                    if (method == "add") {
                        mainItemTable.fnAddData(obj);
                    }

                    if (method == "edit") {
                        mainItemTable.fnUpdate(obj, mainItemRowPos);
                    }

    

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

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

    $('#clientSubItemSaveBtn').on('click', function () {
        var mainItem_uid = $('#subItemList_mainItem_uid').val();
        var subItem_uid = $('#clientSubItem_subItem_uid').val();
        var method = $('#clientSubItem_method').val();
        var subItem_name = $('#modal_subItem_name').val();
        var subItem_descript = $('#modal_subItem_descript').val();
        var subItem_price = $('#modal_subItem_price').val();
        var subItem_unitType = $('#modal_subItem_unitType').val();
        var dept_uid = $("#dept_select").val();

        var msg = '';

        if (subItem_name == '') {
            msg += '請輸入次項目名稱!\n';
        }

        if (subItem_price == '') {
            msg += '請輸入單價!\n';
        } else {
            if (subItem_price.isNumber() == false) {
                msg += '單價必須為數字!\n';
            }
        }

        if (subItem_unitType == '') {
            msg += '請輸入次項目的單位!\n';
        }

        if (msg != '') {
            alert(msg);
            return;
        }

        var formData = {
            mainItem_uid: mainItem_uid,
            subItem_uid: subItem_uid,
            method: method,
            subItem_name: subItem_name,
            subItem_descript: subItem_descript,
            subItem_price: subItem_price,
            subItem_unitType: subItem_unitType,
            dept_uid: dept_uid
        }

        $.ajax({
            url: "/AuthApi/addEditDelGetSubItem",
            type: "post",
            data: formData,
            success: function (data, textStatus, jqXHR) {
                if (data.ret == "yes") {
                    var obj = data.subItems[0];

                    if (method == "add") {
                        subItemTable.fnAddData(obj);
                    }

                    if (method == "edit") {
                        subItemTable.fnUpdate(obj, subItemRowPos);
                    }



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

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

    $('#search_btn').on('click', function () {
        $('#dt-responsive').DataTable().ajax.reload();
    });
});

function loadSubItemDataTable() {
    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 $('#dt-responsive-subItem').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: 25,
                buttons: [
                    //{
                    //    text: '休假設定',
                    //    action: function (e, dt, node, config) {
                    //        vacationBtnFun();

                    //    }
                    //},
                    //'excelHtml5'
                ],
                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,
                rowId: 'subItem_uid',
                deferRender: true,
                initComplete: function () {
                    subItemTable = $('#dt-responsive-subItem').dataTable();
                    $('#dt-responsive-subItem').on('click', 'a', function () {
                        buttonSubItemClick(this);
                    });

                    $('#dt-responsive-subItem').on('click', 'button', function () {
                        buttonSubItemClick(this);
                    });


                },
                order: [[0, 'desc']],
                info: true,
                search: "搜尋:",
                searching: true,
                columns: [
                    { data: 'subItem_name', className: 'align-top text-left', orderable: true, searchable: true },
                    { data: 'subItem_price', className: 'align-top text-right', orderable: true, searchable: true },
                    { data: 'subItem_unitType', className: 'align-top text-right', orderable: true, searchable: true },
                    { data: 'subItem_uid', className: 'align-top text-center', orderable: false, searchable: false }
                ],
                columnDefs: [
                    {
                        targets: 0,
                        className: 'align-middle text-left',
                        orderable: false,
                        searchable: true,
                        render: function render(data, type, row, meta) {

                            return row.subItem_name;
                            //return '<a href="javascript: void(0);" data-uid="' + row.subItem_uid + '" data-method="preview" >' + row.subItem_name + '</a>';

                        }
                    },
                    {
                        targets: 1,
                        className: 'align-middle text-right',
                        orderable: true,
                        searchable: true,
                        render: function render(data, type, row, meta) {

                            return thousands(row.subItem_price);
                            //return '<a href="javascript: void(0);" data-uid="' + row.subItem_uid + '" data-method="preview" >' + row.subItem_name + '</a>';

                        }
                    },
                    {
                        targets: 3,
                        className: 'align-middle text-center',
                        orderable: false,
                        searchable: false,
                        render: function render(data, type, row, meta) {
                            var ret = '';

                            ret += '<button type="button" data-uid="' + row.subItem_uid + '" data-method="edit" class="btn btn-sm btn-icon btn-secondary" ><i class="fa fa-pencil-alt"></i> <span class="sr-only">Edit</span></button>';
                            ret += '<button type="button" data-uid="' + row.subItem_uid + '" data-method="del" class="btn btn-sm btn-icon btn-secondary"><i class="far fa-trash-alt"></i> <span class="sr-only">Remove</span></button>';
                            return ret;
                        }
                    }

                ],
                responsive: {
                    details: {
                        display: $.fn.dataTable.Responsive.display.childRowImmediate,
                        type: ''
                    }
                }
            });
        },
        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();
}
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 $('#dt-responsive').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();

                    //    }
                    //},
                    //'excelHtml5'
                ],
                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: '/authApi/authMainItemList',
                    type: 'POST',
                    data: function (d) {
                        Object.assign(d, {
                            dept_uid: $('#dept_select').val()
                        });

                        return d;
                    },
                    dataSrc: 'mainItems'
                },
                rowId: 'mainItem_uid',
                deferRender: true,
                initComplete: function () {
                    mainItemTable = $('#dt-responsive').dataTable();
                    $('#dt-responsive').on('click', 'a', function () {
                        buttonClick(this);
                    });

                    $('#dt-responsive').on('click', 'button', function () {
                        buttonClick(this);
                    });


                },
                order: [[1, 'desc']],
                info: true,
                search: "搜尋:",
                searching: true,
                columns: [
                    { data: 'mainItem_name', className: 'align-top text-left', orderable: true, searchable: true },
                    { data: 'mainItem_uid', className: 'align-top text-center', orderable: false, searchable: false }
                ],
                columnDefs: [
                    {
                        targets: 0,
                        className: 'align-middle text-left',
                        orderable: false,
                        searchable: true,
                        render: function render(data, type, row, meta) {


                            return '<a href="javascript: void(0);" data-uid="' + row.mainItem_uid + '" data-method="preview" >' + row.mainItem_name + '</a>';

                        }
                    },
                    {
                        targets: 1,
                        orderable: false,
                        searchable: false,
                        render: function render(data, type, row, meta) {
                            var ret = '';

                            ret += '<button type="button" data-uid="' + row.mainItem_uid + '" data-method="edit" class="btn btn-sm btn-icon btn-secondary" ><i class="fa fa-pencil-alt"></i> <span class="sr-only">Edit</span></button>';
                            ret += '<button type="button" data-uid="' + row.mainItem_uid + '" data-method="del" class="btn btn-sm btn-icon btn-secondary"><i class="far fa-trash-alt"></i> <span class="sr-only">Remove</span></button>';
                            return ret;
                        }
                    }

                ],
                responsive: {
                    details: {
                        display: $.fn.dataTable.Responsive.display.childRowImmediate,
                        type: ''
                    }
                }
            });
        },
        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();
}
function deptList() {
    $.ajax({
        url: "/AuthApi/authDeptList",
        type: "post",
        data: null,
        success: function (data, textStatus, jqXHR) {
            if (data.ret == "yes") {
                var obj = data.depts;
                var items = "";
                $.each(obj, function (i, item) {


                    $("#dept_select").append($("<option>", {
                        value: item.dept_uid,
                        text: item.dept_name
                    }));


                });

                loadDataTable();
                loadSubItemDataTable();
            } else {
                alert(data.message);

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

function buttonSubItemClick(obj) {
    var type = obj.getAttribute('data-method');
    var uid = obj.getAttribute('data-uid');
    var dept_uid = $('#dept_select').val();
    var mainItem_uid = $('#subItemList_mainItem_uid').val();

    subItemRowID = $('#' + uid);

    subItemRowPos = subItemTable.fnGetPosition($('#' + uid)[0]);

    if (type == "edit") {
        var formData = {
            method: 'get',
            mainItem_uid: mainItem_uid,
            subItem_uid: uid,
            dept_uid: dept_uid
        }

        $.ajax({
            url: "/AuthApi/addEditDelGetSubItem",
            type: "post",
            data: formData,
            success: function (data, textStatus, jqXHR) {
                if (data.ret == "yes") {
                    var obj = data.subItems[0];

                    $("#clientSubItem_method").val('edit');
                    $("#clientSubItem_subItem_uid").val(obj.subItem_uid);
                    $("#modal_subItem_name").val(obj.subItem_name).trigger('change');

                    $("#modal_subItem_descript").val(obj.subItem_descript).trigger('change');
                    $("#modal_subItem_price").val(obj.subItem_price).trigger('change');
                    $("#modal_subItem_unitType").val(obj.subItem_unitType).trigger('change');

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

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


    }

    if (type == "del") {
        if (confirm('確定刪除此筆子項目資料? ')) {
           
            var formData = {
                method: 'del',
                mainItem_uid: mainItem_uid,
                subItem_uid: uid,
                dept_uid: dept_uid
            }

            $.ajax({
                    url: "/AuthApi/addEditDelGetSubItem",
                    type: "post",
                    data: formData,
                    success: function (data, textStatus, jqXHR) {
                        if (data.ret == "yes") {
                            var row = subItemTable.api().row(subItemRowID).remove().draw(false);
                            alert('刪除成功');

                        } else {
                            alert(data.message);

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

        }
    }
}
function buttonClick(obj) {

    var type = obj.getAttribute('data-method');
    var uid = obj.getAttribute('data-uid');
    var dept_uid = $('#dept_select').val();

    mainItemRowID = $('#' + uid);

    mainItemRowPos = mainItemTable.fnGetPosition($('#' + uid)[0]);

    if (type == "preview") {
        var mainItem_name = obj.innerText.trim();
        var formData = {
            dept_uid: dept_uid,
            mainItem_uid: uid
        }

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

                    $('#dt-responsive-subItem').dataTable().fnClearTable();
                    if (obj.length > 0) {

                        $('#dt-responsive-subItem').dataTable().fnAddData(obj);
                    }
                    $('#mainItemTitle').val(mainItem_name + ' 的子項目列表').trigger('change');

                    $('#subItemList_mainItem_uid').val(uid);
                    $('#clientSubItemListModal').modal('toggle');
                } else {
                    alert(data.message);

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

    if (type == "edit") {
        var formData = {
            method: 'get',
            mainItem_uid: uid,
            dept_uid: dept_uid
        }

        $.ajax({
            url: "/AuthApi/addEditDelGetMainItem",
            type: "post",
            data: formData,
            success: function (data, textStatus, jqXHR) {
                if (data.ret == "yes") {
                    var obj = data.mainItems[0];

                    $("#mainItem_method").val('edit');
                    $("#mainItem_uid").val(obj.mainItem_uid);
                    $("#dept_uid").val(obj.dept_uid).trigger('change');
                    $("#modal_mainItem_name").val(obj.mainItem_name).trigger('change');

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

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


    }

    if (type == "del") {
        if (confirm('確定刪除此筆資料? 所有子項目也會一併刪除~')) {
            if (confirm('再次確認是否刪除所有此項目與子項目?')) {
                var formData = {
                    method: 'del',
                    mainItem_uid: uid,
                    dept_uid: dept_uid
                }

                $.ajax({
                    url: "/AuthApi/addEditDelGetMainItem",
                    type: "post",
                    data: formData,
                    success: function (data, textStatus, jqXHR) {
                        if (data.ret == "yes") {
                            var row = mainItemTable.api().row(mainItemRowID).remove().draw(false);
                            alert('刪除成功');

                        } else {
                            alert(data.message);

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