var gridBuilderReceipt, gridBuilderEmploye;
var errorList = [];

$(document).ready(function () {
    $(".function-manual-save #cboFunctionType").lookupBuilder().onChanged(function (sender) {
        var code = Number(sender.getSelectedValue());
        var item = salaryFactorList.find(x => x.Code === code);
        if (!item)
            return;
        $("[data-name]").each(function () {
            if (item[$(this).attr("data-name")])
                $(this).removeAttr("hidden");
            else
                $(this).attr("hidden", "hidden");
        });
    });




    gridBuilderReceipt = $("#grdReceipt").gridBuilder();
    gridBuilderEmploye = $("#grdEmploye").gridBuilder();
    if (typeof initial === "function")
        initial();
});



var pageErrors = "";

function SaveHd_RevenueReload() {
    SaveHd_Revenue(true);
}


function refreshRevenueList() {
    grdDataList.PerformCallback();
}

function openModalRevenueEdit() {
    if (grdDataList.GetFocusedRowIndex() === -1)
        return;
    showLoading();
    grdDataList.GetRowValues(grdDataList.GetFocusedRowIndex(), 'Code', OnGetRowValuesRevenueUpdate);
}

function OnGetRowValuesRevenueUpdate(Value) {
    var src = "salary/FunctionManualSave?code=" + Value; /// typeOperation == 2 for update , typeRefresh == 1 for refresh grid
    var title = "ویرایش کارکرد";
    openInModal('', src, title, '870', '550')
}

function DeleteRevenue() {
    if (grdDataList.GetFocusedRowIndex() === -1)
        return;
    showLoading();
    grdDataList.GetRowValues(grdDataList.GetFocusedRowIndex(), 'Code', OnGetRowValuesRevenueDelete);
}

function OnGetRowValuesRevenueDelete(Value) {
    ajax({
        url: "SalaryApi/DeleteHd_Revenue",
        data: JSON.stringify({ codemain: Value }),
        success: function (result) {
            debugger;
            refreshRevenueList();
            showMsgModal(2, window.top.savedSuccessfully);
            closeTopModal();
        }
    });
}
function OnGetRowValuesDelWageReciptMulti(Value) {
    debugger;
    pageErrors = "";
    $("#progress").show();
    $('#spanCountAll').text(Value.length);
    if (Value.length > 0)
        delWageRecipt(Value, 0);
}
function delWageRecipt(value, i) {
    $('#spanCount').text(i + 1);
    $("#bar").width(Math.round(((i + 1) / value.length) * 100).toString() + "%");
    ajax({
        url: "SalaryApi/DeleteReciptSingle",
        async: false,
        loading: false,
        data: JSON.stringify({ code: value[i] }),
        success: function (result) {
            if (i + 1 < value.length) {
                delWageRecipt(value, i + 1);
            } else {
                RefreshReceiptList();
                if (pageErrors == "")
                    showMsgModal(2, window.top.savedSuccessfully);
                else
                    alert(pageErrors);
            }
        },
        error: function (request, error) {
            pageErrors += " خطا در فیش شماره: " + value[i] + ":" + request.responseText;
            if (i + 1 < value.length)
                delWageRecipt(value, i + 1);
            else {
                $("#progress").hide();
                alert(pageErrors);
            }


        },
        complete: function () {
            $("#progress").hide();
        }
    });
}


var errors = "";
var Code = "";
var CodePersonel = "";
var WorkShop = "";
var CostCenter = "";
function addWageRecipt(value, i) {
    $('#spanCount').text(i + 1);
    $("#bar").width(Math.round(((i + 1) / value.length) * 100).toString() + "%");
    Code = value[i][0];
    CodePersonel = value[i][1];
    WorkShop = value[i][2];
    CostCenter = value[i][3];
    YearMonth = CmbYear.GetValue() + CmbMonth.GetValue();
    ajax({
        url: "SalaryApi/AddWageReciptSingle",
        loading: false,
        data: JSON.stringify({ code: Code, codePersonel: CodePersonel, yearMonth: YearMonth, workShop: WorkShop, reciptType: 1 }),
        success: function (result) {
            if (!result)
                errors += "این کد به شماره" + " " + Code + " " + "با کد پرسنلی" + " " + CodePersonel + " " + "دارای ارور است";
        },
        complete: function () {
            if (i + 1 < value.length) {
                addWageRecipt(value, i + 1);
            }
            else {
                RefreshReceiptList();
                showMsgModal(2, window.top.savedSuccessfully);
            }
            $("#progress").hide();
        }
    });
}
function RefreshAllList(s, e) {
    RefreshReceiptList();
}
function RefreshReceiptList() {
    debugger;
    if ($('#grdEmployeList').length == 1)
        grdEmployeList.PerformCallback();
    grdSalaryList.PerformCallback();
}







async function getEventLookupCombo($combo, search, code) {
    var id = $combo.attr('id');
    var url = "";
    var data = null;
    var result;
    switch (id) {
        case "cboWorkshop":
            url = "SalaryApi/GetWorkShops";
            data = { search: search, pageNo: 1, selectedCode: code };
            break;
        case "cboCostCenter":
            url = "SalaryApi/GetCostCenters";
            data = { search: search, pageNo: 1, selectedCode: code };
            break;
        case "cboPersonnel":
            url = "SalaryApi/GetPersonnels";
            data = { search: search, pageNo: 1, selectedCode: code };
            break;
    }
    await ajax({
        url: url,
        data: data,
        success: function (retValue) {
            result = retValue;
        }
    });
    if (id === "cboCostCenter")
        result = result.concat({ "Code": -1, "Name": window.top.allCenters });
    if (id === "cboWorkshop")
        result = result.concat({ "Code": -1, "Name": window.top.allWorkshops });
    if (id === "cboPersonnel") {
        $.each(result, function () {
            this.Code = this.CorrespondenceCode;
            this.Name = this.FullName;
        });
    }
    $combo.lookupBuilder().bindData(result);
}

