var code = getQuery("code");
var tradeAccess = true;
var baseCurrencyCode = window.top.$("#hfBaseCurrencyCode").val();
$(document).ready(function () {
    initial();
});
async function initial() {
    await getLockDetail();
    await getUsers();
    if (code)
        getCashDesk();
    else if (tradeAccess) {
        await getConfigArray();
    }
    else {
        $("#divMain").show();
        closeLoading();
    }
}
function cboTafsilGroupChange() {
    $("#cboTafsil").lookupBuilder().setSelectedValue("");
}   
function cboTafsilChange() {
    if ($("#cboCurrency").length === 0)
        return;
    var selectedItem = $("#cboTafsil").lookupBuilder().getSelectedValue();
    if (selectedItem.length > 0) {
        selectedItem = selectedItem.split("|");
        $("#cboCurrency").lookupBuilder().setSelectedValue(selectedItem[1]);
        $("#cboCurrency").lookupBuilder().setEnabled(Number(selectedItem[0]) === -1 ? true : false);
    }
    else {
        $("#cboCurrency").lookupBuilder().setSelectedValue(baseCurrencyCode);
    }

}   
function save() {
    var exceptionText = checkValidation('');
    if (exceptionText === '') {
        var data = getJsonValue();
        var userList = [];
        $('[data-id="employee"]').not(".template").each(function () {
            if ($(this).is(":checked") && Number($(this).attr("data-code")) > 0)
                userList.push({ Code: $(this).attr("data-code") });
        });
        if (userList.length === 0)
            showMsgModal(0, window.top.selectUserList);
        else {
            data["Users"] = userList;
            if (code)
                data['Code'] = code;
            ajax({
                loading: true,
                url: "TreasuryApi/" + (code ? "UpdateCashDesk" : "InsertCashDesk"),
                data: data,
                success: function () {
                    showMsgModal(2, window.top.savedSuccessfully);
                    refreshParent('loadGrid()');
                    closeTopModal();
                }
            });
        }
    }
    else {
        showMsgModal(0, exceptionText);
    }
}
function chkUserChange() {
    $('#chkAllUser').prop('checked', true);
    $('[data-id="employee"]').not(".template").each(function () {
        if (!$(this).is(":checked")) {
            $("#chkAllUser").prop('checked', false);
        }
    });
}
function chkAllUserChange(sender) {
    var checked = $(sender).is(":checked");
    $('[data-id="employee"]').not(".template").each(function () {
        $(this).prop('checked', checked);
    });
}
async function getLockDetail() {
    await ajax({
        url: "GeneralApi/GetLckDetail",
        data: { },
        success: function (result) {
            tradeAccess = result.some(x => x.Code === enumLockDetail.trade);
            if (!tradeAccess)
                $("[data-account=true]").hide();
        }
    });
}
async function getConfigArray() {
    var data = ["Sandoog_Group", "Sandoog_Moain", "AsnadNzSandog_Moain", "Guarantee_Moain"];
    var accountConfig;
    await ajax({
        url: "GeneralApi/GetConfigArray",
        data: { nameList: data },
        success: function (result) {
            accountConfig = result;
        }
    });
    await $("#cboTafsilGroup").lookupBuilder().setSelectedValue(accountConfig.find(x => x.Param === "Sandoog_Group").Value);
    await $("#drpMoainCash").lookupBuilder().setSelectedValue(accountConfig.find(x => x.Param === "Sandoog_Moain").Value);
    await $("#drpMoainCashDesk").lookupBuilder().setSelectedValue(accountConfig.find(x => x.Param === "AsnadNzSandog_Moain").Value);
    await $("#drpGuaranteed").lookupBuilder().setSelectedValue(accountConfig.find(x => x.Param === "Guarantee_Moain").Value);
    $("#divMain").show();
    closeLoading();
}
async function getUsers() {
    await ajax({
        url: "GeneralApi/GetShobehUserList",
        success: function (result) {
            result.forEach(function (item,index) {
                var $data = $(".row-data[hidden]").clone();
                $data.removeAttr("hidden").removeClass("template");
                $data.find("[data-id='employee']").attr("data-code", item.Code);
                $data.find(".checkbox-title").text(item.Name);
                $data.find(".checkbox-control").attr("tabindex",index + 10);
                $("#divEmployee").append($data);
            });
        }
    });
}
async function getCashDesk() {
    var data
    await ajax({
        url: "TreasuryApi/GetCashDesk",
        data: { code: code },
        success: function (result) {
            data = result;
        }
    });
    loadData(data);
}
async function loadData(data) {
    data.TafsilCode = data.TafsilCode + "|" + data.TafsilCurrencyCode;
    $("#cboTafsil").lookupBuilder().setEnabled(false);
    $("#cboTafsilGroup").lookupBuilder().setEnabled(false);
    await setJsonValue(data);
    $('[data-id="employee"]').each(function () {
        var code = $(this).attr("data-code");
        if (data.IsAllUserCredit || data.Users.some(x => x.Code.toString() === code))
            $(this).prop('checked', true);
    });
    chkUserChange($("#chkAllUser"))
    $("#divMain").show();
    closeLoading();
}
async function getEventLookupCombo($combo, search, code) {
    var id = $combo.attr('id');
    var url = "";
    var data = null;

    switch (id) {
        case "cboTafsilGroup":
            url = "AccountingApi/GetTafsilGroupList";
            data = { level: -1, search: search, pageNo: 1, selectedCode: code };
            break;
        case "cboTafsil":
            url = "AccountingApi/GetTafsilList";
            data = { tafsilGroupCode: $("#cboTafsilGroup").lookupBuilder().getSelectedValue(), level: -1, search: search, pageNo: 1, selectedCode: code };
            break;
        case "cboCurrency":
            url = "GeneralApi/GetCurrencyList";
            data = { search: search, filter: "", Sort: "", pageNo: 1 };
            break;
        case "drpMoainCash": case "drpMoainCashDesk":
            url = "AccountingApi/GetMoainLinkedTafsilGroup";
            data = { tafsilGroupCode: $("#cboTafsilGroup").lookupBuilder().getSelectedValue(), search: search, sort: "", pageNo: 1 };
            break;
        case "drpGuaranteed":
            url = "AccountingApi/GetMoainLinkedTafsilGroup";
            data = { search: search, sort: "", pageNo: 1 };
            break;
    }

    await ajax({
        url: url,
        data: data,
        success: function (result) {
            if (id === "cboTafsil") {
                var newResult = [{ Name: window.top.newAccount, Code: "-1|" + baseCurrencyCode }];
                $.each(result, function () {
                    this.Code = this.Code + "|" + this.CodeArz;
                });
                result = newResult.concat(result);
            }
            $combo.lookupBuilder().bindData(result);
        }
    });
}
