var gridBuilderReceipt, gridBuilderEmploye;
var errorList = [];
var cancelOperation = false;
$(document).ready(function () {
    gridBuilderReceipt = $("#grdReceipt").gridBuilder();
    gridBuilderEmploye = $("#grdEmploye").gridBuilder();
    initial();
});
async function initial() {
    var currentYear = $("#hfCurrentYear").val();
    var currentMonth = $("#hfCurrentMonth").val();
    await $("#cboYear").lookupBuilder().setSelectedValue(currentYear);
    await $("#cboMonth").lookupBuilder().setSelectedValue(currentMonth);
    await $("#cboCostCenter").lookupBuilder().setSelectedValue(-1);
    await $("#cboWorkshop").lookupBuilder().setSelectedValue(-1);
    await loadGrids();
    $("#cboWorkshop").lookupBuilder().onChanged(async function () {
        await loadGrids();
    });
    $("#cboCostCenter").lookupBuilder().onChanged(async function () {
        await loadGrids();
    });
    $("#cboMonth").lookupBuilder().onChanged(async function () {
        await loadGrids();
    });
    $("#cboYear").lookupBuilder().onChanged(async function () {
        await loadGrids();
    });
}
async function loadGrids() {
    await loadGrid("grdReceipt");
    await loadGrid("grdEmploye");
}
async function getSelectedRow(isAll, operation) {
    var receiptCodes = [], rulingCodes = [], workShops = [];
    var gridBuilder = (operation === "insert" ? gridBuilderEmploye : gridBuilderReceipt);
    var arrayLength = 0;
    if (isAll)
        var data = gridBuilder.getDataArray()["data"];

    if (operation === "insert") {
        rulingCodes = isAll ? data.map(x => x.RulingCode) : gridBuilder.getSelectedRowsCellValue("RulingCode");
        workShops = isAll ? data.map(x => x.WorkshopCode) : gridBuilder.getSelectedRowsCellValue("WorkshopCode");
        arrayLength = rulingCodes.length;
    }
    else {
        receiptCodes = isAll ? data.map(x => x.Code) : gridBuilder.getSelectedRowsCellValue("Code");
        arrayLength = receiptCodes.length;
    }
    if (arrayLength === 0) {
        showMsgModal(0, window.top.chooseItem);
        return;
    }

    $("#progress").show();
    $('#spanCountAll').text(arrayLength);
    errorList = [];
    cancelOperation = false;
    for (var i = 0; i < arrayLength; i++) {
        if (cancelOperation)
            break;
        $('#spanCount').text(i + 1);
        $("#bar").width(Math.round(((i + 1) / arrayLength) * 100).toString() + "%");
        if (operation === "insert")
            await insertWageReceipt(rulingCodes[i], workShops[i]);
        else
            await deleteWageReceipt(receiptCodes[i]);
    }
    if (errorList.length > 0)
        showMsgModal(0, errorList.join("<br />"));
    else
        showMsgModal(2, operation === "insert" ? window.top.savedSuccessfully : window.top.deletedSuccessfully);
    $("#progress").hide();
    gridBuilder.setUnselected(-1);
    await loadGrids();
}
async function insertWageReceipt(rulingCode, workshopCode) {
    try {
        await ajax({
            url: "SalaryApi/InsertWageReceipt",
            data: {
                yearMonth: $("#cboYear").lookupBuilder().getSelectedValue() + $("#cboMonth").lookupBuilder().getSelectedValue().padStart(2, 0),
                rulingCode: rulingCode,
                receiptTypeCode: 1,
                WorkshopCode: workshopCode
            },
            success: function (retValue) {

            },
            error: function (err) {
                onError(err);
            }
        });
    }
    catch {
    }
}
async function deleteWageReceipt(receiptCode) {
    try {
        await ajax({
            url: "SalaryApi/DeleteWageReceipt",
            data: { code: receiptCode },
            success: function (retValue) {

            },
            error: function (err) {
                onError(err);
            }
        });
    }
    catch {
    }
}
function onError(err) {
    if (window.top.loadCompletePage !== undefined)
        window.top.loadCompletePage = true;
    var message, description = "";
    if (err.responseJSON && err.responseJSON.Message) {
        message = err.responseJSON.Message;
        description = err.responseJSON.Description;
    } else
        message = err.responseText;
    if (!message || message.includes("network-related")) {
        $(window.top.document).find(".progress-counter").remove();
        closeLoading();
        showConnectionError();
    }
    else {
        errorList.push(message);
    }
}
function onDeleteWageReceipt(isAll) {
    if (confirm(window.top.deleteConfirm)) {
        getSelectedRow(isAll, "Delete");
    }
}
async function loadGrid(gridId, objectParameter) {
    var isExportExcel = objectParameter && objectParameter.exportExcel ? true : false;
    var gridBuilder = (gridId === "grdReceipt" ? gridBuilderReceipt : gridBuilderEmploye);
    var costCenterCode = Number($("#cboCostCenter").lookupBuilder().getSelectedValue());
    var workshopCode = Number($("#cboWorkshop").lookupBuilder().getSelectedValue());
    var data = {
        filter: gridBuilder.getFilter(),
        sort: gridBuilder.getSortFields(),
        pageNo: isExportExcel ? -1 : gridBuilder.getCurrentPageNumber(),
        costCenterCode: costCenterCode === -1 ? null : costCenterCode,
        workshopCode: workshopCode === -1 ? null : workshopCode,
        year: $("#cboYear").lookupBuilder().getSelectedValue() || null,
        month: $("#cboMonth").lookupBuilder().getSelectedValue() || null
    };
    await ajax({
        gridBuilder: gridBuilder,
        url: "SalaryApi/" + (gridId === "grdReceipt" ? "GetWageReceiptList" : "GetPersonnelByWageRulingList"),
        data: data,
        success: function (data) {
            if (isExportExcel) {
                exportExcel(data, gridBuilder.getColumns(), gridBuilder.getColumnsCaption());
            }
            else {
                gridBuilder.loadData(data);
            }
        }
    });
}
function PrintWageRecipts(value) {
    var codes = gridBuilderReceipt.getSelectedRowsCellValue("Code");
    if (codes.length === 0) {
        var rowIndex = gridBuilderReceipt.getActiveRowIndex();
        codes.push(gridBuilderReceipt.getCellValue(rowIndex, "Code"));
    }
    var title = window.top.printDocument;
    var url = "Report/Default?GrpName=Hd_FishNew&CodeWageRecipt=" + codes.join(",");
    openInModal('', url, title);
}