var mainItemTable;
var mainItemRowID;
var mainItemRowPos;

var subItemTable;
var subItemRowID;
var subItemRowPos;

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

    $('#subItemListNewBtn').on('click', function () {
        $("#clientSubItem_method").val('add');
        $('#clientSubItemModal').modal('toggle');
    });

    $('#maintItemNewModal').on('click', function () {
        $("#company_method").val('add');
        $('#mainItemModal').modal('toggle');
    });

    $('#mainItemDialogSaveBtn').on('click', function () {
        var method = $('#company_method').val();
        var company_uid = $('#company_uid').val();
        var company_name = $('#modal_company_name').val();
        var company_serialNo = $('#modal_company_serialNo').val();
        var company_address = $('#modal_company_address').val();
        var company_fax = $('#modal_company_fax').val();
        var company_tel = $('#modal_company_tel').val();

        if (company_name == "") {
            alert('請輸入公司名稱');
            retur;
        }

        var formData = {
            method: method,
            company_uid: company_uid,
            company_name: company_name,
            company_serialNo: company_serialNo,
            company_address: company_address,
            company_tel: company_tel,
            company_fax: company_fax
        }

        $.ajax({
            url: "/Api/addEditDelGetCompany",
            type: "post",
            data: formData,
            success: function (data, textStatus, jqXHR) {
                if (data.ret == "yes") {
                    var obj = data.companys[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 contactPerson_uid = $('#clientSubItem_contactPerson_uid').val();
        var company_uid = $('#clientSubItem_company_uid').val();
        var method = $('#clientSubItem_method').val();
        var contactPerson_name = $('#modal_contactPerson_name').val();
        var contactPerson_email = $('#modal_contactPerson_email').val();
        var contactPerson_tel = $('#modal_contactPerson_tel').val();
        var contactPerson_fax = $('#modal_contactPerson_fax').val();
        
        var msg = '';

        if (contactPerson_name == '') {
            msg += '請輸入窗口姓名!\n';
        }

        if (contactPerson_tel == '') {
            msg += '請輸入窗口電話!\n';
        }

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

        var formData = {
            company_uid: company_uid,
            contactPerson_uid: contactPerson_uid,
            method: method,
            contactPerson_name: contactPerson_name,
            contactPerson_email: contactPerson_email,
            contactPerson_tel: contactPerson_tel,
            contactPerson_fax: contactPerson_fax
        }

        $.ajax({
            url: "/Api/addEditDelGetContactPerson",
            type: "post",
            data: formData,
            success: function (data, textStatus, jqXHR) {
                if (data.ret == "yes") {
                    var obj = data.contactPersons[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('網路或伺服器發生錯誤，請稍後重試!');
            }
        });
    });
});

function buttonSubItemClick(obj) {
    var type = obj.getAttribute('data-method');
    var uid = obj.getAttribute('data-uid');
    var company_uid = $('#clientSubItem_company_uid').val();

    subItemRowID = $('#' + uid);

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

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

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

                    $("#clientSubItem_method").val('edit');
                    $("#clientSubItem_contactPerson_uid").val(obj.contactPerson_uid);
                    $("#modal_contactPerson_name").val(obj.contactPerson_name).trigger('change');

                    $("#modal_contactPerson_email").val(obj.contactPerson_email).trigger('change');
                    $("#modal_contactPerson_tel").val(obj.contactPerson_tel).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',
                company_uid: company_uid,
                contactPerson_uid: uid
            }

            $.ajax({
                url: "/Api/addEditDelGetContactPerson",
                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');

    mainItemRowID = $('#' + uid);

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

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

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


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

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

                    $('#clientSubItem_company_uid').val(uid);
                    $('#subItemList_company_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',
            company_uid: uid
        }

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

                    $("#company_method").val('edit');
                    $("#company_uid").val(obj.company_uid);
                    $("#modal_company_name").val(obj.company_name).trigger('change');
                    $("#modal_company_serialNo").val(obj.company_serialNo).trigger('change');
                    $("#modal_company_address").val(obj.company_address).trigger('change');
                    $("#modal_company_tel").val(obj.company_tel).trigger('change');
                    $("#modal_company_fax").val(obj.company_fax).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',
                    company_uid: uid
                }

                $.ajax({
                    url: "/Api/addEditDelGetCompany",
                    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('網路或伺服器發生錯誤，請稍後重試!');
                    }
                });
            }

        }
    }
}
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: '/Api/companyList',
                    type: 'POST',
                    data: function (d) {
                        Object.assign(d, {
                            dept_uid: ''
                        });

                        return d;
                    },
                    dataSrc: 'companys'
                },
                rowId: 'company_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: 'company_name', className: 'align-top text-left', orderable: true, searchable: true },
                    { data: 'company_serialNo', className: 'align-top text-center', orderable: false, searchable: true },
                    { data: 'company_tel', className: 'align-top text-center', orderable: false, searchable: true },
                    { data: 'company_address', className: 'align-top text-center', orderable: false, searchable: true }
                ],
                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.company_uid + '" data-method="preview" >' + row.company_name + '</a>';

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

                            ret += '<button type="button" data-uid="' + row.company_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.company_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 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: 'contactPerson_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: 'contactPerson_name', className: 'align-top text-left', orderable: true, searchable: true },
                    { data: 'contactPerson_email', className: 'align-top text-right', orderable: true, searchable: true },
                    { data: 'contactPerson_tel', className: 'align-top text-right', orderable: true, searchable: true },
                    { data: 'contactPerson_fax', className: 'align-top text-right', orderable: true, searchable: true },
                    { data: 'contactPerson_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.contactPerson_name;
                            //return '<a href="javascript: void(0);" data-uid="' + row.subItem_uid + '" data-method="preview" >' + row.subItem_name + '</a>';

                        }
                    },   
                    {
                        targets: 4,
                        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.contactPerson_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.contactPerson_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();
}