var gridSanadTypeBuilder;
var gridValueAddedBuilder;
var gridValueAddedNewBuilder;
var reportList;
var lang = "";
$(document).ready(function () {
    lang = window.top.$("#hfLanguage").val();
    gridSanadTypeBuilder = $("#gridSanadType").gridBuilder();
    gridValueAddedBuilder = $("#gridValueAdded").gridBuilder();
    gridValueAddedNewBuilder = $("#gridValueAddedNew").gridBuilder();

    gridSanadTypeBuilder.onDblClick(function () {
        var rowIndex = gridSanadTypeBuilder.getActiveRowIndex();
        if (rowIndex < 0) {
            showMsgModal(0, window.top.chooseItem);
            return;
        }
        openModal(gridSanadTypeBuilder.getCellValue(rowIndex, "Code"), 0);
    });
    gridSanadTypeBuilder.onExportClick(function () {
        loadGrid("gridSanadType", { exportExcel: true });
    });

    gridValueAddedBuilder.onDblClick(function (rowIndex) {
        var rowIndex = gridValueAddedBuilder.getActiveRowIndex();
        if (rowIndex < 0) {
            showMsgModal(0, window.top.chooseItem);
            return;
        }
        openModal(gridValueAddedBuilder.getCellValue(rowIndex, "Code"), 1);
    });
    gridValueAddedBuilder.onExportClick(function () {
        loadGrid("gridValueAdded", { exportExcel: true });
    });

    gridValueAddedNewBuilder.onDblClick(function (rowIndex) {
        var rowIndex = gridValueAddedNewBuilder.getActiveRowIndex();
        if (rowIndex < 0) {
            showMsgModal(0, window.top.chooseItem);
            return;
        }
        openModal(gridValueAddedNewBuilder.getCellValue(rowIndex, "Code"), 2);
    });
    gridValueAddedNewBuilder.onExportClick(function () {
        loadGrid("gridValueAddedNew", { exportExcel: true });
    });

    $(".sub").click(function () {
        var destinationId = $(this).attr('data-child');
        $(".page-div").hide();
        $("#" + destinationId).show();
        $(".sub-title").removeClass('selected-sub-title');
        $(this).addClass("selected-sub-title");
    });
    $(".main-title").click(function () {
        $('#btnDefult').show();
        $('.main-title').removeClass("selected-main-title")
        $(this).addClass("selected-main-title");
        $('#divContainer>div').hide();
        switch ($('.selected-main-title').attr('data-id')) {
            case '1':
                $('#divGeneral').show();
                break;
            case '2':
                $('#divFishPrinter').show();
                break;
            case '3':
                $('#divSanadType').show();
                break;
            case '4':
                $('#btnDefult').hide();
                $('#divValueAddedAll').show();
                break;
            case '5':
                $('#divAccount').show();
                break;
        }
    });
    $('.check').click(function () {
        var $lbl = $("#lbl" + $(this).attr("data-id"));
        if ($(this).prop('checked')) {
            $lbl.css('font-weight', '700');
            $lbl.text(window.top.active);
        }
        else {
            $lbl.css('font-weight', '100');
            $lbl.text(window.top.deActive);
        }
    });
    $('#AllowRoundingLimit').click(function () {
        if ($(this).prop('checked')) {
            $("#txtSaghfMablagh").prop('disabled', false);
        }
        else {
            $("#txtSaghfMablagh").val('0');
            $("#txtSaghfMablagh").prop('disabled', true);
        }
    });
    $('#CheckBox_ShowJomleh').click(function () {
        if ($(this).prop('checked')) {
            $("#JomlehTablighati").prop('disabled', false);
        }
        else {
            $("#JomlehTablighati").prop('disabled', true);
            $("#JomlehTablighati").val('');
        }
    });
    $('#CheckBox_ShowJomlehUp').click(function () {

        if ($(this).prop('checked')) {
            $("#JomlehTablighatiUp").prop('disabled', false);
        }
        else {
            $("#JomlehTablighatiUp").prop('disabled', true);
            $("#JomlehTablighatiUp").val('');
        }

    });
    initial();

});
function openModal(code, type) {
    var title;
    var url;
    switch (type) {
        case 0:
            title = code === -1 ? window.top.typesDocuments : window.top.typesDocuments;
            url = "Setting/DocumentTypeSave";
            break;
        case 1:
            title = code === -1 ? window.top.valueAdded : window.top.valueAdded;
            url = "General/ValueAddedSave";
            break;
        case 2:
            title = code === -1 ? window.top.newAddedValue : window.top.newAddedValue;
            url = "General/ValueAddedSaveNew";
            break;
    }
    openInModal('', url + (code > 0 ? "?code=" + code : ""), title, "700", "550", false);
}
function save() {
    showLoading();
    var model = [];
    var field;
    $(" [data-id]").each(function () {
        field = $(this).attr('data-id');
        if ($(this).hasClass("check")) {
            model.push({ Param: field, Value: ($(this).prop('checked') ? "1" : "0") });
        }
        else if ($(this).hasClass("system-lookup-control")) {
            var selectedValue = $(this).lookupBuilder().getSelectedValue();
            if (field === "DefaultCustomer")
                model.push({ Param: field, Value: $(this).lookupBuilder().getSelectedValue() || -1 });
            else
                model.push({ Param: "LinkHesab", Value: selectedValue || -1, Tozihat: $(this).attr("data-id") });
        }
        else if ($(this).hasClass("text-control")) {
            if (field === "RoundingLimit")
                model.push({ Param: field, Value: numberNonCommas($(this).val()) });
            else
                model.push({ Param: field, Value: $(this).val() });
        }
    });
    ajax({
        loading: true,
        url: "GeneralApi/SetConfigArray",
        data: { configList: model },
        success: function (result) {
            showMsgModal(2, window.top.settingsSaved);
            location.reload(true);
        }
    });
}
function refresh(type) {
    var gridBuilder = getGridBuilder(type);
    loadGrid(gridBuilder.container.attr("id"));
}
function getdefault() {
    //first page
    $('#divGeneral input[type="checkbox"]').prop('checked', false);
    $('#txtSaghfMablagh').val('0');

    //secend page
    $('#divFishPrinter input[type="checkbox"]').prop('checked', true);
    $('#SpinEdit_LeftPrint').val('5');
    $('#SpinEdit_RightPrint').val('5');
    $('#JomlehTablighati').val('');
    $('#JomlehTablighatiUp').val('');

    $('.switch').each(function () {
        var $lbl = $('#' + $($(this)).next().attr("id"));
        $lbl.text(window.top.deActive).css("font-weight", "100");
    });
}
function deleteRow(type) {
    var gridBuilder = getGridBuilder(type);
    var rowIndex = gridBuilder.getActiveRowIndex();
    if (rowIndex === -1) {
        showMsgModal(0, window.top.itemNotSelect);
        return;
    }
    if (confirm(window.top.deleteConfirm)) {
        var url;
        var code = gridBuilder.getCellValue(rowIndex, "Code");
        switch (type) {
            case 0:
                url = "SaleApi/DeleteDocumentType";
                break;
            case 1:
                url = "SaleApi/DeleteValueAdded";
                break;
            case 2:
                url = "SaleApi/DeleteTax";
                break;
        }

        ajax({
            loading: true,
            url: url,
            data: { code: code },
            success: function () {
                showMsgModal(2, window.top.deletedSuccessfully);
                loadGrid(gridBuilder.container.attr("id"));
            }
        });
    }
}
function edit(type) {
    var gridBuilder = getGridBuilder(type);
    gridBuilder.dblClick();
}
function getGridBuilder(type) {
    var gridBuilder;
    switch (type) {
        case 0:
            gridBuilder = gridSanadTypeBuilder;
            break;
        case 1:
            gridBuilder = gridValueAddedBuilder;
            break;
        case 2:
            gridBuilder = gridValueAddedNewBuilder;
            break;
    }
    return gridBuilder;
}
async function initial() {
    await loadGrid("gridSanadType");
    await loadGrid("gridValueAdded");
    await loadGrid("gridValueAddedNew");
    await getConfig();
}
async function loadGrid(gridId, objectParameter) {
    var url = "";
    var gridBuilder;
    switch (gridId) {
        case "gridSanadType":
            url = "SaleApi/GetDocumentTypeList";
            gridBuilder = gridSanadTypeBuilder;
            break;
        case "gridValueAdded":
            url = "SaleApi/GetValueAddedList";
            gridBuilder = gridValueAddedBuilder;
            break;
        case "gridValueAddedNew":
            url = "SaleApi/GetTaxList";
            gridBuilder = gridValueAddedNewBuilder;
            break;
    }

    var isExportExcel = objectParameter && objectParameter.exportExcel ? true : false;
    await ajax({
        url: url,
        gridBuilder: gridBuilder,
        data: {
            state: 1,
            filter: gridBuilder.getFilter(),
            sort: gridBuilder.getSortFields(),
            pageNo: isExportExcel ? -1 : gridBuilder.getCurrentPageNumber()
        },
        success: function (data) {
            if (isExportExcel) {
                exportExcel(data, gridBuilder.getColumns(), gridBuilder.getColumnsCaption());
            }
            else
                gridBuilder.loadData(data);
        }
    });
}
async function getConfig() {
    var nameList = ["AnbarAllowNegative", "AnbarAutoGateeSanad", "AllowRoundingLimit", "RoundingLimit", "AllowTakhfifKoliInTouchForm", "ShowHsSanad_Sl", "CheckBox_Shownamesh", "CheckBox_showArm", "CheckBox_ShowAddress", "CheckBox_ShowTel", "CheckBox_ShowTakhfif", "CheckBox_ShowJomleh", "CheckBox_ShowJomlehUp", "SpinEdit_LeftPrint", "SpinEdit_RightPrint", "JomlehTablighati", "JomlehTablighatiUp", "DefaultCustomer", "Takhfif_Moain", "Takhfif_Moain_In", "Maliyat_Moain", "Maliyat_Moain_In", "Avarez_Moain", "Avarez_Moain_In", "Rounding_Moein"];
    await ajax({
        url: "GeneralApi/GetConfigArray",
        data: { nameList: nameList },
        success: function (result) {
            loadData(result);
        }
    });
}
async function loadData(data) {
    for (var i = 0; i < data.length; i++) {
        var item = data[i];
        var $element = $("[data-id='" + item.Param + "']");
        if ($element.hasClass("check")) {
            var $lbl = $("#lbl" + item.Param);
            if (item.Value === "1") {
                $element.prop("checked", true);
                $lbl.css({ "font-weight": "700" });
            }
            else {
                switch (item.Param) {
                    case "AllowRoundingLimit":
                        $("#txtSaghfMablagh").prop("disabled", true);
                        break;
                    case "CheckBox_ShowJomleh":
                        if (item.Value === "0") {
                            $("#JomlehTablighati").prop('disabled', true);
                            $("#JomlehTablighati").val('');
                        }
                        break;
                    case "CheckBox_ShowJomlehUp":
                        if (item.Value === "0") {
                            $("#JomlehTablighatiUp").prop('disabled', true);
                            $("#JomlehTablighatiUp").val('');
                        }
                        break;
                }
                $lbl.text(window.top.deActive);
            }
        }
        else if ($element.hasClass("system-lookup-control")) {
            await $element.lookupBuilder().setSelectedValue(item.Value);
        }
        else
            $element.val(item.Value);
    }
    $("#divMain").show();
    closeLoading();
}
async function getEventLookupCombo($combo, search, code) {
    var level = $combo.parent().attr("data-level");
    var isReport = $combo.parent().attr("data-report");
    var id = $combo.attr("id");
    var url = "";
    var data;
    if (id === "cboDefaultCustomer") {
        url = "GeneralApi/GetCustomerList";
        data = { type: 4, pageNo: 1, selectedCode: code, search: search };
    }
    else if (level === "tafsilGroup") {
        url = "AccountingApi/GetTafsilGroupLinkedMoain";
        data = { moainCode: -1, search: search, selectedCode: code, pageNo: 1 };
    }
    else if (level === "moain") {
        url = "AccountingApi/GetMoainList";
        data = { checkActive: false, search: search, selectedCode: code, pageNo: 1 };
    }
    else {
        url = "SaleApi/GetSaleReportList";
        data = {};
    }

    if ((isReport && !reportList) || !isReport) {
        await ajax({
            url: url,
            data: data,
            success: function (result) {
                if (isReport)
                    reportList = result;
                $combo.lookupBuilder().bindData(result);
            }
        });
    }
    else
        $combo.lookupBuilder().bindData(reportList);

}
