var gridBuilderNoSelect;
var gridBuilderSelect;
var documentList;
var systemList = [];
var formId = getQuery("formId");
var helpType = $('.selected-main-title').attr('data-value');
var platformType = $("#cboPlatform").val();
var formParentSystem;
$(document).ready(function () {
    showLoading();
    gridBuilderNoSelect = $("#grdList").gridBuilder();
    gridBuilderSelect = $("#grdSelectList").gridBuilder();
    gridBuilderNoSelect.onExportClick(function () {
        loadGrid("grdList", { exportExcel: true });
    });
    gridBuilderSelect.onExportClick(function () {
        loadGrid("grdSelectList", { exportExcel: true });
    });
    initial();
});
async function initial() {
    $("#cboForm").attr("data-value", window.top.helpFormAddress);
    $("#cboForm").find(".lookup-button").attr("disabled", "disabled");
    $("#cboForm").find(".lookup-button .text").text(window.top.helpFormAddress);
    await fillSelectedTab(helpType, formId, platformType);
    $("#divMain").show();
    closeLoading();
    $(".main-title").click(async function () {
        showLoading();
        $('.main-title').removeClass("selected-main-title");
        $(this).addClass("selected-main-title");
        helpType = $('.selected-main-title').attr('data-value');
        await fillSelectedTab(helpType, formId, platformType);
        loadGrid("grdList");
        loadGrid("grdSelectList");
        closeLoading();
    });
    $("#cboSystem").lookupBuilder().onChanged(async function () {
        loadGrid("grdList");
    });
    $("#cboForm").lookupBuilder().onChanged(async function () {
        formId = $("#cboForm").lookupBuilder().getSelectedValue().split("|")[1];
        showLoading();
        helpType = $('.selected-main-title').attr('data-value');
        await fillSelectedTab(helpType, formId, platformType);
        loadGrid("grdList");
        loadGrid("grdSelectList");
        closeLoading();
    });
}
async function fillSelectedTab(type, formId, platformType) {
    switch (type) {
        case "help":
            await getHelpTypeInfo("سیستم های راهنما", type, formId, platformType);
            break;
        case "knowledge":
            await getHelpTypeInfo("سیستم های بانک دانش", type, formId, platformType);
            break;
        case "faq":
            await getHelpTypeInfo("سیستم های سوالات متداول", type, formId, platformType);
            break;
    }
}
async function getHelpTypeInfo(caption, type) {
    setCaption("cboSystem", caption);
    await getEventLookupCombo($("#cboSystem"));
    await getFormSubject(formId);
    var systemCode = "";
    if (systemList.filter(x => x.Name.trim() === formParentSystem).length > 0)
        systemCode = systemList.filter(x => x.Name.trim() === formParentSystem)[0].Code;
    $("#cboSystem").lookupBuilder().setSelectedValue(systemCode);
    await getHelpDocumentList(helpType, platformType);
    await getSelectedCode(formId, platformType);
    loadGrid("grdList");
    loadGrid("grdSelectList");
}
async function getEventLookupCombo($combo, search, isAndroid) {
    var url;
    var data;
    if (isAndroid) {
        url = "GeneralApi/GetAndroidFormList";
        data = {};
    } else {
        url = "GeneralApi/GetHelpSystemList";
        data = { helpType: helpType, platformType: platformType };
    }
    await ajax({
        url: url,
        data: data,
        success: function (result) {
            if (isAndroid) {
                var data = result.map(function (item) { return { Code: item.Id + "|" + item.FormUrl, Name: item.Title }; });
                $("#cboForm").lookupBuilder().bindData(data);
                if (data.length > 0)
                    $("#cboForm").lookupBuilder().setSelectedValue(data[0].Code);
            } else {
                systemList = result;
                $("#cboSystem").lookupBuilder().bindData(result);
            }
        }
    });
}
async function getHelpDocumentList(helpType, platformType, codeItemList) {
    await ajax({
        url: "GeneralApi/GetHelpDocumentList",
        data: { helpType: helpType, platformType: platformType, codeItemList: codeItemList },
        success: function (result) {
            documentList = result;
        }
    });
}
async function getSelectedCode(formId, platformType) {
    await ajax({
        url: "GeneralApi/GetGheyasHelpList",
        data: { formUrl: formId, platformType: platformType },
        success: function (result) {
            result.forEach(function (item) {
                var selectedData = documentList.find(c => c.Code === item.DocumentCode);
                if (selectedData)
                    selectedData.IsSelected = true;
            });
        }
    });
}
async function getFormSubject(formId) {
    var formParent = formId.split("/")[0];
    if (formParent) {
        switch (formParent.toLowerCase()) {
            case "accounting":
                formParentSystem = "حسابداری";
                break;
            case "treasury":
                formParentSystem = "دریافت و پرداخت";
                break;
            case "sale":
                formParentSystem = "خرید و فروش";
                break;
            case "store":
                formParentSystem = "انبار";
                break;
            case "general":
            case "setting":
                formParentSystem = "عمومی و تنظیمات";
                break;
            default:
                formParentSystem = "";
                break;
        }
    }
}
async function platformChanged() {
    platformType = $("#cboPlatform").val();
    if (platformType === "web") {
        showLoading();
        formId = getQuery("formId");
        $("#cboForm").attr("data-value", window.top.helpFormAddress);
        $("#cboForm").find(".lookup-button").prop("disabled", true);
        $("#cboForm").find(".lookup-button .text").text(window.top.helpFormAddress);
        await fillSelectedTab(helpType, formId, platformType);
        loadGrid("grdList");
        loadGrid("grdSelectList");
        closeLoading();
    } else {
        showLoading();
        $("#cboForm").removeAttr("data-value");
        $("#cboForm").find(".lookup-button .text").text("");
        await getEventLookupCombo("#cboForm", "", true);
        $("#cboForm").find(".lookup-button").prop("disabled", false);
        await fillSelectedTab(helpType, formId, platformType);
        loadGrid("grdList");
        loadGrid("grdSelectList");
        closeLoading();
    }
}
function loadGrid(gridId, objectParameter) {
    var isExportExcel = objectParameter && objectParameter.exportExcel ? true : false;
    var selected = gridId === "grdSelectList";
    var gridBuilder = selected ? gridBuilderSelect : gridBuilderNoSelect;
    var systemCode = Number($("#cboSystem").lookupBuilder().getSelectedValue() ?? 0);
    var codeItemList = systemCode !== 0 ? systemList.filter(x => x.Code === systemCode)[0].CodeItemList : "";
    var data;
    if (selected)
        data = documentList.filter(x => x.IsSelected);
    else
        data = documentList.filter(x => !x.IsSelected && (codeItemList === "" || codeItemList.includes(x.CodeItem)));

    if (isExportExcel)
        exportExcel(data, gridBuilder.getColumns(), gridBuilder.getColumnsCaption());
    else
        gridBuilder.loadData(data);
}
function addRemoveAll(state) {
    gridBuilder = state ? gridBuilderNoSelect : gridBuilderSelect;
    gridBuilder.setSelected(-1);
    var code = gridBuilder.getSelectedRowsCellValue('Code');
    addRemoveSelected(code, state);
}
function addRemoveSingle(state) {
    gridBuilder = state ? gridBuilderNoSelect : gridBuilderSelect;
    var codes = gridBuilder.getSelectedRowsCellValue("Code");
    if (codes.length === 0) {
        var activeRowCode = gridBuilder.getActiveRowCellValue("Code");
        if (activeRowCode)
            codes.push(activeRowCode);
    }
    addRemoveSelected(codes, state);
}
function addRemoveSelected(codes, state) {
    for (var i = 0; i < codes.length; i++) {
        var item = documentList.find(x => x.Code === Number(codes[i]));
        item.IsSelected = state;
    }
    gridBuilderNoSelect.setUnselected(-1);
    gridBuilderSelect.setUnselected(-1);
    loadGrid("grdList");
    loadGrid("grdSelectList");
    if (state)
        save(formId, codes);
    else
        deleteHelp(formId, codes);
}
function setCaption(id, text) {
    $("#" + id + "_dropdown .has-float-label span").text(text);
    $("#lbl_" + id).text(text);
}
function save(formId, codeList) {
    ajax({
        loading: true,
        url: "GeneralApi/InsertGheyasHelp",
        data: { formUrl: formId, platformType: platformType, documentCodeList: codeList },
        success: function (result) {
            showMsgModal(2, window.top.savedSuccessfully);
        }
    });
}
function deleteHelp(formId, codeList) {
    ajax({
        loading: true,
        url: "GeneralApi/DeleteGheyasHelp",
        data: { formUrl: formId, platformType: platformType, documentCodeList: codeList },
        success: function (result) {
            showMsgModal(2, window.top.savedSuccessfully);
        }
    });
}







