require('./model');
require('./resource');
import { BaseViewModel } from '../master/baseViewModel.js';
import { SelectItem, TreeBalanceReportSelectItem } from '../master/model';
import { AdjustmentDocumentViewModel } from '../adjustmentdocument/viewModel.js';
import { TotalBalanceReportDataViewModel, BalanceReportDataViewModel  } from './model.js';


export function BalanceReportViewModel() {
    var self = this;
    self.firstLoad = ko.observable(true);
    self.showBalanceTree = ko.observable(false);
    self.nodePath = ko.observable();
    self.companySelectedName = ko.observable();
    self.balanceSheetId = ko.observable();
    self.sheetSearchKey = ko.observable();
    self.treeId = ko.observable();
    self.nodeId = ko.observable();
    self.level = ko.observable();
    self.amountType = ko.observable(2);
    self.displayType = ko.observable(1);
    self.companyId = ko.observable();
    self.worksheetView = ko.observable(0);
    self.justConfirmed = ko.observable(false);
    self.navigationDirection = ko.observable();
    self.nodeIdList = ko.observableArray();
    self.treeSearchKey = ko.observable();
    self.lastLevel = ko.observable();
    self.showUpLevel = ko.observable(false);
    self.showDownLevel = ko.observable(false);
    self.nodeCodeSelected = ko.observable();
    self.levelSelectList = ko.observableArray();
    self.treeGroupSelectList = ko.observableArray();
    self.treeSelectList = ko.observableArray();
    self.fileSelectList = ko.observableArray();
    self.companySelectList = ko.observableArray();
    self.treeNodeRecords = [];
    self.toggleWorksheetView = function () {
        if (self.worksheetView() === 0) {
            self.worksheetView(1);
            self.nodeCodeSelected(null);
        } else {
            self.worksheetView(0);
        }
        clientStorage.setSetting(
            [{
                key: "BalanceReport_worksheetView_" + _h.kocnx().loginCompanyType(),
                value: self.worksheetView()
            }]
        );
        self.getRecords();
    }
    self.toggleBalanceTree = function () {
        if (_h.isEmpty(self.treeId()))
            return;
        if (!self.showBalanceTree()) {
            self.showBalanceTree(true);
            $(".balancetree-box").draggable({
                scroll: true,
                handle: ".balancetree-drag-handle"
            });
            self.getTreeNodeRecords();
        } else {
            self.showBalanceTree(false);
        }

    };
    self.onTreeEnterSearchKey = function (d, e) {
        if (e.keyCode === 13) {
            self.getTreeNodeRecords();
        }
        return true;
    };
    self.showAmountType = ko.observable(true);
    self.treeId.subscribe(function (newValue) {
        if (newValue === null || newValue === undefined || newValue === "") return;
        if (!self.firstLoad())
            self.changeCascadeItems(newValue);
        self.nodeId(undefined);
        self.nodeCodeSelected(null);
        self.clearSelectedItem();

    });
    self.companyId.subscribe(function (newValue) {
        if (!_h.isNullOrEmpty(newValue) && newValue > 1) {
            var name = self.getCompany(newValue);
            self.companySelectedName(" :: " + name);
        }
        if (_h.isNullOrEmpty(newValue) || newValue === -1) {
            self.companySelectedName("");
        }
    });
    self.getCompany = function (id) {
        var name = null;
        for (var i = 0; i < self.companySelectList().length; i++) {
            if (self.companySelectList()[i].value() === id)
                name = self.companySelectList()[i].text();
        }
        return name;
    }
    self.changeNodePath = function (item) {
        var path = " :: ";
        var parents = self.getParents(item);
        for (var j = 0; j < parents.length; j++) {
            var target = parents[j];
            path += target.name();
            if (parents.length - 1 !== j) {
                path += " => ";
            }
        }
        self.nodePath(path);
    };
    self.getParents = function (item) {
        var def = item.depth;
        var array = [];
        if (def <= 0)
            return array;
        var result = item;
        var bigger;
        for (var i = 0; i < def; i++) {
            if (result !== null && result !== undefined) {
                bigger = result.parent();
                result = bigger;
                array.push(result);
            }
        }
        return array.reverse();
    }
    self.clearSelectedItem = function () {
        ko.utils.arrayFilter(self.treeNodeRecords(),
            function (cat) {
                cat.selected(false);
                self.clearChildrenSelectedItem(cat);
            });
    };
    self.clearChildrenSelectedItem = function (item) {
        item.selected(false);
        ko.utils.arrayFilter(item.children(),
            function (cat) {
                cat.selected(false);
                if (cat.children().length > 0)
                    self.clearChildrenSelectedItem(cat);
            });
    }
    self.changeCascadeItems = function (treeId) {
        var item = null;
        if (_h.kocnx().loginCompanyType() === 0) {
            ko.utils.arrayFilter(self.treeGroupSelectList(),
                function (tree) {
                    if (tree.value() === treeId) {
                        item = tree;
                    }
                });
        }
        if (_h.kocnx().loginCompanyType() === 1) {
            ko.utils.arrayFilter(self.treeSelectList(),
                function (tree) {
                    if (tree.value() === treeId) {
                        item = tree;
                    }
                });
            self.fileSelectList.removeAll();
            self.fileSelectList.push(new SelectItem({ text: "همه فایل ها", value: -1 }));
            if (_h.any(item.effectedFiles())) {
                for (var j = 0; j < item.effectedFiles().length; j++) {
                    var targetf = item.effectedFiles()[j];
                    self.fileSelectList.push(new SelectItem(targetf));
                }
            }
            var firstc = self.fileSelectList()[0];
            self.balanceSheetId(firstc.value());
            self.filterBox().balanceSheetId(firstc.value());
        }
        self.levelSelectList.removeAll();
        if (item.levels() !== null && item.levels() !== undefined && item.levels().length > 0) {
            for (var i = 0; i < item.levels().length; i++) {
                var targetl = item.levels()[i];
                self.levelSelectList.push(new SelectItem(targetl));
            }
            if (self.levelSelectList().length > 0) {
                var firstl = self.levelSelectList()[0];
                self.level(firstl.value());
                self.filterBox().level(firstl.value());
            }
        }
        self.findLastLevel();
    }
    self.downTableNode = function (item) {
        self.level(item.level + 1);
        self.filterBox().level(self.level());
        self.nodeId(item.id);
        self.navigationDirection(2);
        self.filterBy();
        if (!_h.isEmpty(item.path))
            self.nodePath(" :: " + item.path);
        else {
            self.nodePath("");
        }
    };
    self.upTableNode = function (item) {
        self.level(item.level - 1);
        self.filterBox().level(self.level());
        self.nodeId(item.id);
        self.navigationDirection(1);
        self.filterBy();
        if (!_h.isEmpty(item.pathParent))
            self.nodePath("::" + item.pathParent);
        else {
            self.nodePath("");
        }
    };
    self.upLevelTreeSurf = function () {
        self.level(self.level() - 1);
        self.filterBox().level(self.level());
        self.nodeId(undefined);
        self.clearSelectedItem();
        self.pageNumber(1);
        self.getRecords();
        self.toggleShowSurfBtn();
        self.nodePath("");
    };
    self.downLevelTreeSurf = function () {
        self.level(self.level() + 1);
        self.filterBox().level(self.level());
        self.nodeId(undefined);
        self.clearSelectedItem();
        self.pageNumber(1);
        self.getRecords();
        self.toggleShowSurfBtn();
        self.nodePath("");
    };
    self.toggleShowSurfBtn = function () {
        if (self.level() > 1 && self.level() !== 0) {
            self.showUpLevel(true);
        }
        if (self.level() === 1 || self.level() === 0) {
            self.showUpLevel(false);
        }
        var highLevel = 1;
        ko.utils.arrayFilter(self.levelSelectList(),
            function (level) {
                if (level.value() > highLevel) {
                    highLevel = level.value();
                }
            });
        if (self.level() >= highLevel || self.level() === 0) {
            self.showDownLevel(false);
        } else {
            self.showDownLevel(true);
        }
    }
    self.toggleChildren = function (item) {
        if (item.childrenShow() === false) {
            item.childrenShow(true);
        } else {
            item.childrenShow(false);
        }
    }
    self.getTreeSelectList = function (callback) {
        self.apiService.request({
            name: "getTreeList",
            success: function (data) {
                var isTreeExist = false;
                var treeId = clientStorage.getSetting("BalanceReport_treeId_" + _h.kocnx().loginCompanyType(), 1);
                self.treeSelectList.removeAll();
                if (_h.any(data))
                    for (var j = 0; j < data.length; j++) {
                        var target = data[j];
                        self.treeSelectList
                            .push(new TreeBalanceReportSelectItem({
                                text: target.name,
                                value: target.id,
                                levels: target.levels,
                                effectedFiles: target.effectedFiles,
                                currencyType: target.currencyType
                            }));
                        if (treeId && Number(treeId) === target.id)
                            isTreeExist = true;
                    }
                if (self.treeSelectList().length > 0) {
                    var first = self.treeSelectList()[0];
                    self.treeId(isTreeExist ? Number(treeId) : first.value());
                    self.filterBox().treeId(isTreeExist ? Number(treeId) : first.value());
                    self.changeCascadeItems(self.treeId());
                }
                callback(true);
            },
            error: function () {
                var text = _h.getApiMessage("ErrorLoadTree");
                _h.failToast(text);
                callback(false);
            }
        });
    }
    self.getGroupTreeSelectList = function (callback) {
        self.apiService.request({
            name: "getTreeList",
            success: function (data) {
                var isTreeExist = false;
                var treeId = clientStorage.getSetting("BalanceReport_treeId_" + _h.kocnx().loginCompanyType());
                self.treeGroupSelectList.removeAll();
                if (_h.any(data.trees))
                    for (var j = 0; j < data.trees.length; j++) {
                        var target = data.trees[j];
                        self.treeGroupSelectList.push(new TreeBalanceReportSelectItem({
                            text: target.name,
                            value: target.id,
                            levels: target.levels,
                            currencyType: target.currencyType
                        }));
                        if (treeId && Number(treeId) === target.id)
                            isTreeExist = true;
                    }
                self.companySelectList.push(new SelectItem({ text: "کلیه شرکت های مشمول تلفیق", value: -1 }));
                if (_h.any(data.companies))
                    for (var i = 0; i < data.companies.length; i++) {
                        var targetC = data.companies[i];
                        self.companySelectList.push(new SelectItem(targetC));
                    }

                var firstC = self.companySelectList()[0];
                self.filterBox().companyId(firstC.value());
                self.companyId(firstC.value());
                if (self.treeGroupSelectList().length > 0) {
                    var first = self.treeGroupSelectList()[0];
                    self.treeId(isTreeExist ? Number(treeId) : first.value());
                    self.filterBox().treeId(isTreeExist ? Number(treeId) : first.value());
                    self.changeCascadeItems(self.treeId());
                }
                self.findLastLevel();
                callback(true);
            },
            error: function () {
                var text = _h.getApiMessage("ErrorLoadTree");
                _h.failToast(text);
                callback(false);
            }
        });
    }
    self.getTreeNodeRecords = function () {
        var model = {
            id: self.treeId(),
            searchKey: self.treeSearchKey(),
            controllerName: 12
        };
        self.apiService.request({
            name: "getNodeSelection",
            data: model,
            success: function (data) {
                if (_h.any(data)) {
                    self.treeNodeRecords = data;
                    self.configTools();
                }
            },
            error: function (message, level) {
                var text = _h.getApiMessage("ErrorLoadMapTree");
                _h.failToast(text);
            }
        });
    };
    self.initDefault = function () {
        if (_h.kocnx().loginCompanyType() === 0) {
            self.getGroupTreeSelectList(function (res) {
                if (res) {
                    self.loadClientSideFilterData();
                    self.getRecords();
                    self.firstLoad(false);
                }
            });
        }
        if (_h.kocnx().loginCompanyType() === 1) {
            self.getTreeSelectList(function (res) {
                if (res) {
                    self.loadClientSideFilterData();
                    self.getRecords();
                    self.firstLoad(false);
                }
            });
        }
    };
    self.loadClientSideFilterData = function () {
        var context = _h.kocnx();
        var amountType = clientStorage.getSetting("BalanceReport_amountType_" + context.loginCompanyType());
        var displayType = clientStorage.getSetting("BalanceReport_displayType_" + context.loginCompanyType());
        var worksheetView = clientStorage.getSetting("BalanceReport_worksheetView_" + context.loginCompanyType());
        if (amountType) {
            self.amountType(Number(amountType));
            self.filterBox().amountType(Number(amountType));
        }
        if (displayType) {
            self.displayType(Number(displayType));
            self.filterBox().displayType(Number(displayType));
        }
        if (!_h.isNullOrEmpty(worksheetView))
            self.worksheetView(Number(worksheetView));
    };
    self.init = function () {
        self.fillTableProperties();
        self.initDefault();
    };
    self.createExcel = function () {
        var context = _h.kocnx();
        var model = {
            controllerName: 12,
            inputData: {
                pageNumber: self.pageNumber(),
                pageSize: self.pageSize(),
                sortProperty: self.sortProperty(),
                sortDirection: self.sortDirection(),
                balanceSheetId: self.balanceSheetId(),
                sheetSearchKey: self.sheetSearchKey(),
                treeId: self.treeId(),
                nodeId: self.nodeId(),
                level: self.level(),
                amountType: self.amountType(),
                displayType: self.displayType(),
                navigationDirection: self.navigationDirection(),
                justConfirmed: self.justConfirmed(),
                type: 0,
                worksheetView: self.worksheetView(),
                nodeIdList: self.nodeIdList()
            }
        };
        if (_h.kocnx().loginCompanyType() === 0) {
            model.inputData.companyId = self.companyId();
        }
        _h.kocnx().createExcel(model);
    };
    self.createSeparationExcel = function () {
        var model = {
            controllerName: 12,
            inputData: {
                pageNumber: self.pageNumber(),
                pageSize: self.pageSize(),
                sortProperty: self.sortProperty(),
                sortDirection: self.sortDirection(),
                balanceSheetId: self.balanceSheetId(),
                sheetSearchKey: self.sheetSearchKey(),
                treeId: self.treeId(),
                nodeId: self.nodeId(),
                level: self.level(),
                amountType: self.amountType(),
                displayType: self.displayType(),
                companyId: self.companyId(),
                navigationDirection: self.navigationDirection(),
                justConfirmed: self.justConfirmed(),
                type: 1,
                worksheetView: self.worksheetView(),
                nodeIdList: self.nodeIdList()
            }
        };
        _h.kocnx().createExcel(model);
    }
    self.balanceReportDetailsBtn = function (item, e) {
        if (e.ctrlKey || e.shiftKey)
            return;
        _h.kocnx()
            .openForm(new BalanceReportDataViewModel(self, item));
    };
    self.amendmentsDetailsBtn = function (type, item, e) {
        if (e.ctrlKey || e.shiftKey)
            return;
        var context = _h.kocnx()
        context.balanceAdjustmentDocumentForm(null);
        var record = new AdjustmentDocumentViewModel("View");
        if (context.loginCompanyType() === 0)
            record.companyId(self.companyId());
        if (context.loginCompanyType() === 1) {
            if (!self.balanceSheetId()) {
                self.balanceSheetId(-1);
                record.balanceSheetId(-1);
            }
            else
                record.balanceSheetId(self.balanceSheetId());
        }
        record.amountType(self.amountType());
        record.isCreditor(type === "creditorFlow");
        record.nodeId(item.id);
        record.treeId(self.treeId());
        context.balanceAdjustmentDocumentForm(record);
        context.balanceAdjustmentDocumentForm().init();
    };
    self.totalDetailsBtn = function (item, e) {
        if (e.ctrlKey || e.shiftKey)
            return;
        _h.kocnx()
            .openForm(new TotalBalanceReportDataViewModel(self, item));
    };
    self.findLastLevel = function () {
        if (self.levelSelectList().length > 0) {
            var first = 0;
            ko.utils.arrayFilter(self.levelSelectList(),
                function (level) {
                    if (level.value() > first) {
                        first = level.value();
                    }
                });
            self.lastLevel(first);
        }
    }
    ko.utils.extend(self, new BaseViewModel({
        entityName: "BalanceReport",
        apiService: {
            actionList: ["filterby", "gettreelist"]
        },
        sortDirection: "Ascending",
        extraParams: [
            "totalDebtor", "totalCreditor", "totalCreditorFlow", "totalDebtorFlow",
            "totalCreditorBalance", "totalDebtorBalance"
        ],
        sortProperty: "id",
        context: self,
        cols: balancereportModelRes,
        searchKeyType: "enter",
        getList: false,
        saveState: false,
        selectRow: false,
        contextMenu: false
    }));
    self.records = [];
    self.getRecords = function () {
        self.collectOpenBranches();
        var filterModel = {
            pageNumber: self.pageNumber(),
            pageSize: self.pageSize(),
            sortProperty: self.sortProperty(),
            sortDirection: self.sortDirection(),
            balanceSheetId: self.balanceSheetId(),
            sheetSearchKey: self.sheetSearchKey(),
            treeId: self.treeId(),
            nodeId: self.nodeId(),
            level: self.level(),
            amountType: self.amountType(),
            displayType: self.displayType(),
            companyId: self.companyId(),
            justConfirmed: self.justConfirmed(),
            navigationDirection: self.navigationDirection(),
            nodeIdList: self.nodeIdList(),
            worksheetView: self.worksheetView(),
            searchKey: self.searchKey()
        };
        self.apiService.request({
            name: "filterby",
            data: filterModel,
            success: function (data) {
                self.records = [];
                if (!_h.isNullOrEmpty(data)) {
                    if (_h.any(data.list)) {
                        self.records = data.list;
                    }
                    self.total(data.total);
                    self.totalDebtor(data.totalDebtor);
                    self.totalCreditor(data.totalCreditor);
                    self.totalCreditorFlow(data.totalCreditorFlow);
                    self.totalDebtorFlow(data.totalDebtorFlow);
                    self.totalCreditorBalance(data.totalCreditorBalance);
                    self.totalDebtorBalance(data.totalDebtorBalance);
                }
                self.configTableView();

                self.toggleShowSurfBtn();
                _h.fixLabelsSize();
            },
            error: function (message, level) {
                toast.error(self.entityName, 'getList');
            }
        });
    }
    self.filterBox = ko.observable(new BalanceReportFilter(self));
    self.connectManBtn = function () {
        _h.kocnx().openConnectMan(12, "connectManCaption2");
    };
    self.formatLevel = ko.computed(function () {
        if (self.level() !== 0)
            return '-' + ' سطح ' + self.level();
        if (self.level() === 0)
            return '-' + ' همه سطوح ';
    });
    self.expandAll = function () {
        $("#tree_view_w").treeView("expandAll");
    };
    self.collapseAll = function () {
        $("#tree_view_w").treeView("collapseAll");
    };
    self.clearSelectedItem = function () {
        $("#tree_view_w").treeView("clearSelect");
    };
    self.changeNodeSelected = function (item, callback) {
        if (!item.selected) {
            if (item.depth === undefined || item.depth === 0) {
                self.nodeId(undefined);
            } else {
                self.nodeId(item.parentId);
            }
            self.nodeCodeSelected(item.code);
            self.level(item.depth + 1);
            self.filterBox().level(item.depth + 1);
            self.clearSelectedItem();
            self.pageNumber(1);
            self.getRecords();
            self.nodePath(item.path);
            callback(true);
        } else {
            self.nodeId(undefined);
            self.nodeCodeSelected(null);
            self.nodePath("");
            self.clearSelectedItem();
            self.pageNumber(1);
            self.getRecords();
            callback(false);
        }
    };
    self.configTools = function () {
        $("#tree_view_w").treeView({
            tType: "BalanceReport",
            nodes: self.treeNodeRecords,
            rootId: self.treeId(),
            controllerName: 12,
            location: "BalanceReport",
            onClickItem: self.changeNodeSelected
        });
    };
    self.brSelector = "#br_Table";
    self.configTableView = function () {
        $(self.brSelector).tableTreeView({
            nodes: self.records,
            type: "BalanceReport",
            companyType: _h.kocnx().loginCompanyType(),
            rootId: self.treeId(),
            cols: ko.toJS(self.tableProperties()),
            controllerName: 12,
            sortProperty: self.sortProperty(),
            context: self,
            worksheetView: self.worksheetView(),
            nodeCodeSelected: self.nodeCodeSelected(),
            footerData: {
                totalDebtor: self.totalDebtor(),
                totalCreditor: self.totalCreditor(),
                totalCreditorFlow: self.totalCreditorFlow(),
                totalDebtorFlow: self.totalDebtorFlow(),
                totalCreditorBalance: self.totalCreditorBalance(),
                totalDebtorBalance: self.totalDebtorBalance()
            }
        });
        setTimeout(function () {
            if (self.treeOpenBranches && self.treeOpenBranches.length)
                $(self.brSelector).tableTreeView("expand", self.treeOpenBranches);
        }, 150);
    };
    self.treeOpenBranches = [];
    self.collectOpenBranches = function () {
        self.treeOpenBranches = [];
        var tree = $(self.brSelector);
        var ulList = tree.find(".node-ch:not(.dmn-c)");
        var array = [];
        if (ulList.length)
            for (var i = 0; i < ulList.length; i++) {
                var item = ulList[i];
                var parent = $(item).parent();
                if (parent)
                    array.push(parent.attr("did"));
            }
        self.treeOpenBranches = array;
    };
}
function BalanceReportFilter(parent) {
    var self = this;
    self.parent = parent;
    self.treeId = ko.observable();
    self.companyId = ko.observable();
    self.level = ko.observable();
    self.nodeIdList = ko.observableArray();
    self.justConfirmed = ko.observable(false);
    self.amountType = ko.observable(2);
    self.displayType = ko.observable(1);
    self.balanceSheetId = ko.observable();
    self.sheetSearchKey = ko.observable();
    self.refreshSign = ko.observable(false);
    self.validationObject = ko.validatedObservable({
        treeId: self.treeId.extend({
            required: {
                params: true,
                message: "لطفا درخت نگاشت را انتخاب کنید"
            }
        }),
        balanceSheetId: self.balanceSheetId.extend({
            required: {
                onlyIf: function () {
                    return _h.kocnx().loginCompanyType() === 1;
                },
                params: true,
                message: "لطفا فایل تراز را انتخاب کنید"
            }
        }),
        companyId: self.companyId.extend({
            required: {
                onlyIf: function () {
                    return _h.kocnx().loginCompanyType() === 0;
                },
                params: true,
                message: "لطفا گروه/شرکت را انتخاب کنید"
            }
        }),
        level: self.level.extend({
            required: {
                params: true,
                message: "لطفا سطح نمایش را انتخاب کنید"
            }
        }),
        displayType: self.displayType.extend({
            required: {
                params: true,
                message: "لطفا وضعیت  نمایش را انتخاب کنید"
            }
        }),
        amountType: self.amountType.extend({
            required: {
                params: true,
                message: "لطفا نمایش ارقام را انتخاب کنید"
            }
        })
    });
    self.level.subscribe(function (newValue) {
        if (newValue === null || newValue === undefined || newValue === "") return;
        self.parent.searchKey("");
        self.nodeIdList.removeAll();
        self.refreshSign(true);
        self.refreshSign(false);
    });
    self.treeId.subscribe(function (newValue) {
        if (_h.isEmpty(newValue)) return;
        self.toggleShowAmountType(newValue);
        if (!self.parent.firstLoad())
            self.parent.changeCascadeItems(newValue);
    });
    self.toggleShowAmountType = function (value) {
        var list, target;
        if (_h.kocnx().loginCompanyType() === 0)
            list = self.parent.treeGroupSelectList;
        else
            list = self.parent.treeSelectList;
        for (var i = 0; i < list().length; i++) {
            if (list()[i].value() === value)
                target = list()[i];
        }
        if (target) {
            if (target.currencyType() === 2)
                self.parent.showAmountType(false);
            else
                self.parent.showAmountType(true);
        } else {
            self.parent.showAmountType(true);
        }
    }
    self.onNodeSelect = function (name, list) {
        self.nodeIdList.removeAll();
        if (_h.any(list)) {
            for (var i = 0; i < list.length; i++) {
                if (self.nodeIdList().indexOf(list[i].value) === -1)
                    self.nodeIdList.push(list[i].value);
            }
        }
    }
    self.clearSearchBoxes = function () {
        self.justConfirmed(false);
        self.parent.justConfirmed(self.justConfirmed());
        self.amountType(2);
        self.parent.amountType(self.amountType());
        self.displayType(1);
        self.parent.displayType(self.displayType());
        if (self.nodeIdList().length > 0) {
            self.nodeIdList.removeAll();
            self.refreshSign(true);
            self.refreshSign(false);
            self.parent.nodeIdList(self.nodeIdList());
        }
        var firstItem;
        if (self.parent.fileSelectList().length > 0) {
            firstItem = self.parent.fileSelectList()[0];
            self.balanceSheetId(firstItem.value());
            self.parent.balanceSheetId(firstItem.value());
        }
        if (self.parent.companySelectList().length > 0) {
            firstItem = self.parent.companySelectList()[0];
            self.parent.companyId(firstItem.value());
            self.companyId(firstItem.value());
        }

        self.sheetSearchKey(undefined);
        self.parent.sheetSearchKey(self.sheetSearchKey());
        self.parent.searchKey("");
        if (self.parent.levelSelectList().length > 0) {
            firstItem = self.parent.levelSelectList()[0];
            self.level(firstItem.value());
            self.parent.level(self.level());
        }
        self.parent.pageNumber(1);
        self.setLocalData();
        self.parent.filterBy();
    }
    self.filterBy = function () {
        if (!self.validationObject.isValid()) {
            self.validationObject.errors.showAllMessages();
            return false;
        }
        self.parent.treeId(self.treeId());
        self.parent.companyId(self.companyId());
        self.parent.level(self.level());
        self.parent.justConfirmed(self.justConfirmed());
        self.parent.amountType(self.amountType());
        self.parent.displayType(self.displayType());
        self.parent.balanceSheetId(self.balanceSheetId());
        self.parent.sheetSearchKey(self.sheetSearchKey());

        self.parent.nodeIdList(self.nodeIdList());
        self.setLocalData();
        self.parent.filterBy();
    }
    self.setLocalData = function () {
        var context = _h.kocnx();
        clientStorage.setSetting(
            [{ key: "BalanceReport_treeId_" + context.loginCompanyType(), value: self.treeId() },
            { key: "BalanceReport_amountType_" + context.loginCompanyType(), value: self.amountType() },
            { key: "BalanceReport_displayType_" + context.loginCompanyType(), value: self.displayType() }]
        );
    }
}