import {
    ProcessQueue, PeriodInfo, LoginViewModel,
    FileUploadForm, ResultConnectionProperties, CompanyTokenInfo,
    ChangeLogViewModel, HelpViewModel, UserProfile, ResetPasswordModel,
    ConnectionManager, FolderManagement, AppConfigForm, LoginHistory,
    SecurityConfig
} from './model.js';
import { KeyboardHandler } from '../../util/keyboardHandler.js';
import vms from '../viewModelsIndex.js';
import { ApiService } from '../../util/apiService.js'
export function MasterViewModel() {
    var self = this;
    for (let m in window.entities) {
        if (window.entities.hasOwnProperty(m)) {
            self[window.entities[m].prop] = ko.observable();
        }
    }
    self.pageName = ko.observable();
    self.loginCompanyId = ko.observable();
    self.loginCompanyType = ko.observable();
    self.currentUser = ko.observable();
    self.userName = ko.observable();
    self.lsl = ko.observable();
    self.currentMappingEnabled = ko.observable();
    self.currentCompany = ko.observable();
    self.captionCompany = ko.observable();
    self.periodItem = ko.observable();
    self.permitPeriodEdit = ko.observable(true);
    self.processManagement = ko.observable(new ProcessQueue(self));
    self.keysHandler = ko.observable(new KeyboardHandler());
    self.headerSection = new HeaderSection(self);
    self.showBalanceAdjustmentDocumentForm = ko.observable(false);
    self.balanceAdjustmentDocumentForm = ko.observable();
    self.closeBalanceAdjustmentDocument = function () {
        self.showBalanceAdjustmentDocumentForm(false);
        self.balanceAdjustmentDocumentForm(null);
    }
    self.initModel = function (refresh) {
        let model;
        let container = self[entities[window.resDomain].prop];
        switch (window.resDomain) {
            case "Mapping":
                if (_h.isNullOrEmpty(container())) {
                    var vmName = window.resDomain + 'ViewModel';
                    model = vms[vmName];
                    container(new model());
                    if (refresh === undefined)
                        container().init();
                    else
                        container().reInit();
                }
                container().getBalancesheetSelectList(true);
                break;
            case "Magazine":
                if (_h.isNullOrEmpty(container()) || refresh) {
                    var vmName = window.resDomain + 'ViewModel';
                    model = vms[vmName];
                    container(new model());
                    container().init();
                }
                if (!_h.isNullOrEmpty(container()) &&
                    !_h.isNullOrEmpty(container().designSelectedModel())) {
                    container().designSelectedModel().tableTemplateModel().getRecords();
                    if (container().designMode() === true)
                        window.resSecondDomain = 'pageeditor';
                }
                break;
            case "DynamicDocument":
                var vmName = window.resDomain + 'ViewModel';
                model = vms[vmName];
                container(new model());
                container().init();
                break;
            default:
                if (_h.isNullOrEmpty(container()) || refresh) {
                    var vmName = window.resDomain + 'ViewModel';
                    model = vms[vmName];
                    container(new model());
                    container().init();
                }
                break;
        }
    }
    self.refreshSysData = function (data, refreshUi) {
        if (_h.isNullOrEmpty(data.prd))
            self.periodItem(null);
        else {
            self.periodItem(new PeriodInfo(data.prd));
            if (data.prd.cl === true || data.prd.st === 0)
                self.permitPeriodEdit(false);
            else
                self.permitPeriodEdit(true);
        }
        self.currentUser(data.ur);
        if (_h.isEmpty(data.ur.fn))
            self.userName(data.ur.un);
        else
            self.userName(data.ur.fn);
        if (refreshUi || refreshUi === undefined) {
            var activeMenu = entities[window.resDomain].menu;
            for (let m in entities) {
                if (entities.hasOwnProperty(m) && entities[m].menu === activeMenu) {
                    self[entities[m].prop](null);
                }
            }
        }
        self.currentCompany(data.cmp);
        self.loginCompanyType(data.cmp.ct);
        self.loginCompanyId(data.cmp.ci);
        self.currentMappingEnabled(data.cmp.mpe);
        if (self.loginCompanyType() === 0)
            self.captionCompany(_h.getLocalizedText("activeGroup"));
        else
            self.captionCompany(_h.getLocalizedText("activeCompany"));
    }
    self.getCurrentInfo = function (callback) {
        var data = _h.getUd();
        if (_h.isEmpty(data)) {
            _h.backToLogin();
        } else {
            self.refreshSysData(data);
            callback(true);
        }
    }
    self.refreshToken = function () {
        ApiService.request(
            {
                url: "/api/account/postrefreshtoken",
                success: function (d) {
                    if (_h.isEmpty(d)) {
                        var text = _h.getApiMessage("ErrorUnknownServer");
                        _h.failToast(text);
                        _h.backToLogin();
                        return;
                    }
                    self.changeTvm(d, true);
                },
                error: function () {
                    _h.backToLogin();
                }
            });
    }
    self.changeTvm = function (d, refreshUi) {
        _h.setUd(d.ud);
        _h.setSd(d.sd);
        if (d.sts.length > 0)
            localStorage.setItem("sts", JSON.stringify(d.sts));
        else {
            d.sts = [{ key: "RepGenAutoSave", value: "0", scopeAccess: 1 }];
            localStorage.setItem("sts", JSON.stringify(d.sts));
        }
        self.refreshSysData(d.ud, refreshUi);
        if (refreshUi) {
            self.refreshUi();
            _h.toggleDisableSections(false);
        }
        if (window.resDomain === "TableTemplate") {
            self.ttvm().refreshPage();
        }
    }
    self.refreshUi = function () {
        var activeMenu = entities[window.resDomain].menu;
        for (let m in entities) {
            if (entities.hasOwnProperty(m) && entities[m].menu === activeMenu) {
                self[entities[m].prop](null);
            }
        }
        if (activeMenu === "Operation") {
            self.initialiseTabs();
        }
        self.initModel();
    };
    self.changeLogBtn = function () {
        self.openForm(new ChangeLogViewModel());
    }
    self.openHelp = function (dataModel, e) {
        self.showForm(new HelpViewModel(self, e));
    }
    self.getAppConfig = function (callback) {
        ApiService.request(
            {
                url: "/api/common/getconfigs",
                success: function (data) {
                    if (data !== null && data !== undefined) {
                        callback(data);
                    }
                },
                error: function (data) {
                    var text = _h.getApiMessage("LoadAppConfigError");
                    _h.failToast(text);
                    callback(null);
                }
            });
    }
    self.appConfigBtn = function () {
        self.getAppConfig(function (data) {
            if (data) {
                _h.kocnx()
                    .openForm(new AppConfigForm(self, data));
            }
        });
    }
    self.editAppConfig = function (parents, btnModel, e) {
        var item = parents[1];
        if (!item.validationObject.isValid()) {
            item.validationObject.errors.showAllMessages();
            return false;
        }
        var model = item.toServer();
        ApiService.request(
            {
                url: "/api/common/postconfigs",
                data: model,
                success: function (data) {
                    _h.kocnx().closeForm();
                    var text = _h.getApiMessage("PutAppConfigSuccess");
                    _h.successToast(text);
                },
                error: function (data) {
                    var text = _h.getApiMessage("PutAppConfigError");
                    _h.failToast(text);
                }
            });
    }
    self.getUserProfile = function (callback) {
        ApiService.request(
            {
                url: "/api/user/getprofile",
                success: function (data) {
                    if (data !== null && data !== undefined) {
                        callback(data);
                    }
                },
                error: function (data) {
                    var text = _h.getApiMessage("LoadUserProfileError");
                    _h.failToast(text);
                    callback(null);
                }
            });
    }
    self.userProfileBtn = function () {
        self.getUserProfile(function (data) {
            if (data) {
                _h.kocnx()
                    .openForm(new UserProfile(self, data));
            }
        });
    }
    self.logout = function () {
        $('.splash').css('display', 'block');
        ApiService.request(
            {
                url: "/api/account/postlogoff",
                data: model,
                success: function (data) {
                    _h.backToLogin();
                },
                error: function (data) {
                    _h.backToLogin();
                }
            });
    }
    self.editUserProfile = function (parents, btnModel, e) {
        var item = parents[1];
        if (!item.validationObject.isValid()) {
            item.validationObject.errors.showAllMessages();
            return false;
        }
        var model = item.toServer();
        ApiService.request(
            {
                url: "/api/user/putprofile",
                data: model,
                success: function (data) {
                    _h.kocnx().closeForm();
                    if (self.pageName() === "Users") {
                        self.uvm().refreshTable();
                    }
                    var text = _h.getApiMessage("PutUserProfileSuccess");
                    _h.successToast(text);
                },
                error: function (data) {
                    var text = _h.getApiMessage("PutUserProfileError");
                    _h.failToast(text);
                }
            });
    }
    self.changePasswordBtn = function () {
        self.openForm(new ResetPasswordModel(self, {}));
    }
    self.editChangePassword = function (parents, btnModel, e) {
        var item = parents[1];
        if (!item.validationObject.isValid()) {
            item.validationObject.errors.showAllMessages();
            return false;
        }
        var model = item.toServer();
        ApiService.request(
            {
                url: "/api/user/postuserresetpassword",
                data: model,
                success: function (data) {
                    if (!_h.isNullOrEmpty(data)) {
                        self.closeForm();
                        var text = _h.getApiMessage("PostChangePasswordSuccess");
                        _h.successToast(text);
                    }
                },
                error: function (data) {
                    var text = _h.getApiMessage("PostChangePasswordError");
                    _h.failToast(text);
                }
            });
    }
    self.toggleChildren = function (item) {
        if (item.childrenShow() === false) {
            item.childrenShow(true);
            if (item["usersShow"])
                item["usersShow"](false);
        } else {
            item.childrenShow(false);
        }
    }
    self.showAll = function (list, type) {
        var status = type === "plus";
        list = ko.isObservable(list) ? list() : list;
        if (_h.any(list))
            for (var i = 0; i < list.length; i++) {
                var target = list[i];
                self.showChildrenAll(target, status);
            }
    };
    self.showChildrenAll = function (item, status) {
        item.childrenShow(status);
        if (_h.any(item.children()))
            for (var i = 0; i < item.children().length; i++) {
                var target = item.children()[i];
                target.childrenShow(status);
                self.showChildrenAll(target, status);
            }
    };
    self.saveTableState = function (context, hasParent) {
        var list = [];
        if (!hasParent) {
            ko.utils.arrayFilter(context.tableProperties(), function (property) {
                list.push({
                    fa: property.fa,
                    className: property.className,
                    type: property.type,
                    colName: property.name,
                    tablecol: property.tablecol,
                    visibleCol: property.visibleCol(),
                    visibleItem: property.visibleItem(),
                    sortDir: property.sortDir(),
                    size: property.size,
                    width: property.width,
                    alias: property.alias,
                    template: property.template,
                    popup: property.popup,
                    click: property.click,
                    disableSort: property.disableSort,
                    activeGroupBy: property.activeGroupBy(),
                    groupBy: property.groupBy,
                    groupDir: property.groupDir(),
                    colParent: property.colParent,
                    templateName: property.templateName,
                    filterType: property.filterType,
                });
            });
            clientStorage.setSetting(
                [{ key: context.entityName + "_TableState_" + self.loginCompanyType(), value: JSON.stringify(list) }]
            );
        } else {
            ko.utils.arrayFilter(context.tableParentProperties(),
                function (property) {
                    list.push({
                        id: property.id,
                        name: property.name,
                        visibleCol: property.visibleCol(),
                        size: property.size
                    });
                });
            clientStorage.setSetting(
                [{ key: context.entityName + "_Parent_TableState_" + self.loginCompanyType(), value: JSON.stringify(list) }]
            );
        }
    }
    self.resetTableState = function (context, i, e) {
        clientStorage.removeSetting(context.entityName + "_TableState_" + self.loginCompanyType());
        clientStorage.removeSetting(context.entityName + "_Parent_TableState_" + self.loginCompanyType());
        clientStorage.removeSetting(context.entityName + "_ShowTableState_" + self.loginCompanyType());
        context.groupProperty(undefined);
        context.groupDirection(undefined);
        context.fillTableProperties();
        context.getRecords();
    };
    self.changeColWidth = function (e) {
        var list = [];
        var context = ko.contextFor(e).$parent;
        if (!context)
            return;
        var cols = $("." + context.entityName + "-tbl").find("th:visible");
        ko.utils.arrayFilter(context.tableProperties(), function (property) {
            var width;
            for (var i = 0; i < cols.length; i++) {
                var dataName = $(cols[i]).attr("data-name");
                if (property.name === dataName && cols[i].style.width && cols[i].style.width.indexOf("%") === -1)
                    width = cols[i].style.width.replace("px", "");
            }
            var item = {
                fa: property.fa,
                className: property.className,
                type: property.type,
                colName: property.name,
                tablecol: property.tablecol,
                visibleCol: property.visibleCol(),
                visibleItem: property.visibleItem(),
                sortDir: property.sortDir(),
                size: property.size,
                width: undefined,
                alias: property.alias,
                template: property.template,
                popup: property.popup,
                click: property.click,
                activeGroupBy: property.activeGroupBy(),
                groupBy: property.groupBy,
                groupDir: property.groupDir(),
                colParent: property.colParent,
                templateName: property.templateName,
            };
            if (width)
                item.width = width;
            list.push(item);
        });
        clientStorage.setSetting(
            [{ key: context.entityName + "_TableState_" + self.loginCompanyType(), value: JSON.stringify(list), scopeAccess: 1 }]
        );
    }
    self.createPdf = function (model) {
        ApiService.request(
            {
                url: "/api/filegenerator/postPdf",
                data: model,
                success: function (data) {
                    if (!_h.isNullOrEmpty(data)) {
                        _h.downloadFile(data.model);
                    }
                },
                error: function (data) {
                    var text = _h.getApiMessage("GetFileError");
                    _h.failToast(text);
                }
            });
    }
    self.createHtml = function (controllerName, id) {
        var model = {
            controllerName: controllerName,
            id: id
        };
        ApiService.request(
            {
                url: "/api/filegenerator/gethtml",
                data: model,
                success: function (data) {
                    if (!_h.isNullOrEmpty(data)) {
                        _h.downloadFile(data.model);
                    }
                },
                error: function (data) {
                    var text = _h.getApiMessage("GetFileError");
                    _h.failToast(text);
                }
            });
    }
    self.createExcel = function (model) {
        ApiService.request(
            {
                url: "/api/filegenerator/postdownloadexcel",
                data: model,
                success: function (data) {
                    if (!_h.isNullOrEmpty(data)) {
                        _h.downloadFile(data.model);
                    }
                },
                error: function (data) {
                    var text = _h.getApiMessage("GetFileError");
                    _h.failToast(text);
                }
            });
    }
    self.toggleChkBox = function (parent, item, model) {
        if (item() === undefined)
            item(true);
        else {
            item(!item());
        }
    }
    self.openConnectMan = function (controllerName, caption) {
        self.openForm(
            new ConnectionManager(self, { controllerName: controllerName, caption: caption }));
    };
    self.folderManagementBtn = function (context, i, e) {
        var controllerName;
        for (var j = 0; j < controllerNames.length; j++) {
            var target = controllerNames[j];
            if (context.entityName === target.enText) {
                controllerName = target.value;
            }
        }
        if (controllerName) {
            self.openForm(
                new FolderManagement(context, { controllerName: controllerName }));
        }
    };
    self.init = function () {
        self.getCurrentInfo(function (res) {
            if (res) {
                self.initialiseTabs();
                self.initModel();
                _h.toggleDisableSections(false);
            }
        });
        var lsl = localStorage.getItem("lsl");
        self.lsl(lsl);
        var fs = localStorage.getItem("fs");
        if (fs) {
            self.showLoginHistory();
        }
    };
    self.loginHistoryBtn = function () {
        self.showLoginHistory();
    }
    self.showLoginHistory = function () {
        ApiService.request(
            {
                url: "/api/actionlog/getloginhistory",
                data: model,
                success: function (data) {
                    if (!_h.isNullOrEmpty(data)) {
                        self.openForm(new LoginHistory(self, data));
                    }
                    localStorage.removeItem("fs");
                },
                error: function (data) {
                    var text = _h.getApiMessage("GetLoginHistoryError");
                    _h.failToast(text); 
                    localStorage.removeItem("fs");
                }
            });
    }
    self.openLoginModal = function () {
        self.openForm(new LoginViewModel(self));
    }
    self.initialiseTabs = function () {
        switch (self.pageName()) {
            case "Operation":
                $(".master-tab").find("li").removeClass("active");
                if (self.loginCompanyType() === 0 && self.currentCompany().irt === false) {
                    window.resDomain = 'Mapping';
                    $("#Mapping-t").addClass("active");
                    $("[href='#Mapping-t']").parent().addClass("active");
                }
                if (self.loginCompanyType() === 0 && self.currentCompany().irt === true) {
                    window.resDomain = 'GroupPeriod';
                    $("#GroupPeriod-t").addClass("active");
                    $("[href='#GroupPeriod-t']").parent().addClass("active");
                }
                if (self.loginCompanyType() === 1) {
                    window.resDomain = 'Balancesheet';
                    $("[href='#Balancesheet-t']").parent().addClass("active");
                    $("#Balancesheet-t").addClass("active");
                }
                break;
        }
    }
    self.checkProcessQueue = function (sign, firstLoad) {
        self.processManagement().init(sign, firstLoad);
    };
    self.connectionProcessHandler = function (id, input, output, percent, title, processStatus, item, host) {
        var connModal = self.formModel();

        if (self.showForm() && connModal.entityName === "Connection") {
            connModal.selectedRow().processItem(item);
            if (_h.any(output.errors)) {
                connModal.selectedRow().resultErrors.removeAll();
                for (var b = 0; b < output.errors.length; b++) {
                    var target = output.errors[b];
                    var text2 = _h.getApiMessage(target.code);
                    text2 = _h.completeError(text2, target);
                    connModal.selectedRow().resultErrors.push(text2);
                }
            }
            if (_h.any(output.outputFiles)) {
                connModal.selectedRow().outputFiles.removeAll();
                for (var i = 0; i < output.outputFiles.length; i++) {
                    connModal.selectedRow().outputFiles.push(output.outputFiles[i]);
                }
                connModal.selectedRow().resultMode(true);
            }
            if (_h.any(output.properties) && output.hasNextStage) {
                for (var k = 0; k < output.properties.length; k++) {
                    var prop = new ResultConnectionProperties(output.properties[k]);
                    connModal.selectedRow().properties.push(prop);
                }
                if (!connModal.selectedRow().resultMode())
                    connModal.selectedRow().resultMode(true);
            }
            if (!_h.any(output.errors) && !_h.any(output.outputFiles) && !_h.any(output.properties) && (percent === 100 || percent === "100")) {
                connModal.selectedRow().resultMode(false);
                connModal.selectedRow().properties.removeAll();
                connModal.selectedRow().resultErrors.removeAll();
                connModal.selectedRow().outputFiles.removeAll();
                toast.success(connModal.entityName, 'postUpdate', 'CompleteRun');
                connModal.getRecords();
            }
            connModal.hasNextStage(output.hasNextStage);
        }
    }
    self.importFileBtn = function (id, parent, fileType, schemaMode) {
        self.openForm(new FileUploadForm({ fileType: fileType, id: id }, parent, schemaMode));
    };
    self.importFile = function (parents, btnModel, e) {
        var item = parents[1];
        if (!item.validationObject.isValid()) {
            item.validationObject.errors.showAllMessages();
            return false;
        }
        var model = item.toServer();
        ApiService.request({
            splashId: e,
            url: "/api/common/postimportfile",
            data: model,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    switch (item.parent.entityName) {
                        case "Tree":
                            item.parent.refreshEditor();
                            toast.success(item.parent.entityName, 'custom', `Import${item.fileTypeExpect}`);
                            break;
                        case "TableTemplate":
                            item.parent.afterCreate(data.models);
                            toast.success(item.parent.entityName, 'custom', `Import${item.fileTypeExpect}`);
                            break;
                        case "DynamicTable":
                            if (item.schemaMode()) {
                                item.parent.afterCreate(data.models);
                                toast.success(item.parent.entityName, 'custom', 'ImportExcel');
                            } else {
                                toast.success("DynamicTableData", 'custom', 'ImportExcel');
                                item.parent.childModel().getRecords();
                            }
                            break;
                    }
                    self.closeForm();
                }
            },
            error: function () {
                toast.error(item.parent.entityName, 'custom', `Import${item.fileTypeExpect}`);
            }
        });
    };
    self.securityConfigBtn = function () {
        ApiService.request(
            {
                url: "/api/account/getconfigs",
                success: function (data) {
                    if (!_h.isNullOrEmpty(data)) {
                        self.openForm(new SecurityConfig(self, data));
                    }
                },
                error: function (data) {
                }
            });
    }
    self.changeSecurityConfig = function (parents, btnModel, e) {
        var item = parents[1];
        var model = {
            list: item.toServer()
        }
        ApiService.request(
            {
                url: "/api/account/postoverwrite",
                data: model,
                success: function (data) {
                    if (!_h.isNullOrEmpty(data)) {
                        _h.kocnx().closeForm();
                    }
                },
                error: function (data) {
                }
            });
    }
}

MasterViewModel.prototype.showForm = ko.observable(false);
MasterViewModel.prototype.formModel = ko.observable();
MasterViewModel.prototype.openForm = function (formModel, target) {
    var mb = $(".modal-box");
    mb.css("width", "");
    mb.css("min-width", "");
    mb.css("left", "");
    mb.css("top", "");
    MasterViewModel.prototype.formModel(formModel);
    MasterViewModel.prototype.showForm(true);
    if (_h.isEmpty(formModel.backgroundModal))
        $(".modal-back").css("display", "block");

    if (!_h.isEmpty(formModel.backgroundColor))
        $(".modal-back").css("background-color", "white");
    if (formModel.width)
        _h.adjustModalPosition(formModel.width, formModel.minWidth);
    mb.draggable({
        scroll: true,
        handle: ".panel-heading"
    });
    var className = formModel.constructor.name;
    var selector, selectedTag;
    if (target) {
        selectedTag = $(target);
    } else {
        selector = className === "NodeForm" || className === "CompanyForm" ? ".dmn-selected" : ".table-row-selected";
        selectedTag = $(selector);
    }
    if (selectedTag.length) {
        var pos = _h.getPosition(selectedTag[0]);
        mb.css("top", pos.scrollTop + "px");
    }

}
MasterViewModel.prototype.closeForm = function () {
    MasterViewModel.prototype.showForm(false);
    MasterViewModel.prototype.formModel(null);
    $(".modal-back").css("display", "");
}
$(document).on("shown.bs.tab", '.master-tab a[data-toggle="tab"]', function (e) {
    const target = $(e.target).attr("href");
    if (_h.isEmpty(target))
        return;
    window.resDomain = target.replace("-t", "").replace("#", "");
    _h.kocnx().initModel();
})

export class HeaderSection {
    constructor(parent) {
        this.parent = parent;
        this.preSelectedCompany = ko.observable();
        this.preSelectedPeriod = ko.observable();
        this.companies = ko.observableArray();
        var date = dateHelper.getCurrentJalaaliYear();
        this.yearPeriod = ko.observable(date.jy).extend({ rateLimit: 500 });
        this.monthPeriod = ko.observable(undefined).extend({ rateLimit: 500 });
        this.searchCompany = ko.observable();
        this.searchCompany.subscribe(function (val) {
            for (let i = 0; i < this.companies().length; i++) {
                if (_h.isEmpty(val) || this.companies()[i].name().indexOf(val) !== -1) {
                    this.companies()[i].show(true);
                } else {
                    this.companies()[i].show(false);
                }
            }
        }.bind(this));
        this.getVerticalAlignLogotype = ko.pureComputed(function () {
            if (this.parent.currentCompany() !== null && this.parent.currentCompany() !== undefined) {
                var name = _h.getLogoType(this.parent.currentCompany().n);
                if (name === "ا" || name === "آ")
                    return "vertical-align :sub";
                if (name === "ط" || name === "ظ" || name === "گ" || name === "ک")
                    return "vertical-align :text-bottom";
            }
            return "";
        }.bind(this));
    }

    changeActiveCompany(item) {
        this.preSelectedPeriod(null);
        for (let i = 0; i < this.companies().length; i++) {
            if (this.companies()[i].id() === item.id()) {
                this.companies()[i].preSelected(!item.preSelected());
                this.preSelectedCompany(item);

                for (let j = 0; j < this.preSelectedCompany().periods().length; j++) {
                    if (this.preSelectedCompany().periods()[j].preSelected()) {
                        this.preSelectedPeriod(this.preSelectedCompany().periods()[j]);
                    }
                }
            } else
                this.companies()[i].preSelected(false);
        }
    }

    changeActivePeriod(item) {
        for (let j = 0; j < this.preSelectedCompany().periods().length; j++) {
            this.preSelectedCompany().periods()[j].preSelected(false);
        }
        item.preSelected(true);
        this.preSelectedPeriod(item);
    }

    changeActiveItems(item) {
        var isPreNull = _h.isNullOrEmpty(this.preSelectedPeriod());
        var isPeriodItemNull = _h.isNullOrEmpty(this.parent.periodItem());
        if (!isPreNull && !isPeriodItemNull) {
            if (this.preSelectedPeriod().id === this.parent.periodItem().pi
                && this.preSelectedCompany().id() === this.parent.loginCompanyId()) {
                return;
            }
        }
        var periodId, companyId;
        if (!_h.isEmpty(this.preSelectedPeriod())) {
            periodId = this.preSelectedPeriod().id;
        } else {
            periodId = 0;
        }
        if (!_h.isEmpty(this.preSelectedCompany())) {
            companyId = this.preSelectedCompany().id();
        } else {
            companyId = this.parent.loginCompanyId();
        }

        ApiService.request(
            {
                url: "/api/common/postcurrentdata",
                data: {
                    periodId: periodId,
                    companyId: companyId
                },
                success: function (data) {
                    var text = _h.getApiMessage("ActivePeriodSelectSuccess");
                    _h.successToast(text);
                    for (let i = 0; i < this.companies().length; i++) {
                        if (this.companies()[i].id() === this.preSelectedCompany().id()) {
                            this.companies()[i].selected(true);
                            this.companies()[i].preSelected(false);
                            for (let j = 0; j < this.companies()[i].periods().length; j++) {
                                if (this.companies()[i].periods()[j].preSelected()) {
                                    this.companies()[i].periods()[j].selected = true;
                                } else {
                                    this.companies()[i].periods()[j].selected = false;
                                }
                            }
                        } else {
                            this.companies()[i].selected(false);
                            this.companies()[i].preSelected(false);
                            for (let j = 0; j < this.companies()[i].periods().length; j++) {
                                if (this.companies()[i].periods()[j].selected)
                                    this.companies()[i].periods()[j].preSelected(true);
                                else
                                    this.companies()[i].periods()[j].preSelected(false);
                            }
                        }
                    }
                }.bind(this),
                error: function (data) {
                    var text = _h.getApiMessage("ActivePeriodSelectError");
                    _h.failToast(text);
                }
            });
    }

    getCompanies(defaultList) {
        var activeCompanyId;
        if (!_h.isEmpty(this.preSelectedCompany())) {
            activeCompanyId = this.preSelectedCompany().id();
        } else {
            activeCompanyId = this.parent.loginCompanyId();
        }
        ApiService.request(
            {
                url: "/api/common/getcurrentoptions",
                data: {
                    year: this.yearPeriod(),
                    month: this.monthPeriod(),
                    activeCompanyId: activeCompanyId,
                    defaultList: defaultList,
                },
                success: function (data) {
                    if (defaultList === false) {
                        if (this.preSelectedCompany())
                            this.preSelectedCompany().fillPeriods(data[0].periods);
                    } else {
                        this.companies.removeAll();
                        if (_h.any(data)) {
                            for (let i = 0; i < data.length; i++) {
                                var target = data[i];
                                this.companies.push(new CompanyTokenInfo(target, this.parent.loginCompanyId()));
                                if (this.parent.currentCompany().ci === this.companies()[i].id()) {
                                    this.preSelectedCompany(this.companies()[i]);
                                    this.preSelectedCompany().preSelected(true);
                                    for (let j = 0; j < this.preSelectedCompany().periods().length; j++) {
                                        if (this.preSelectedCompany().periods()[j].selected) {
                                            this.preSelectedPeriod(this.preSelectedCompany().periods()[j]);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }.bind(this),
                error: function (data) {
                    var text = _h.getApiMessage("ErrorLoadSelectCompany");
                    _h.failToast(text);
                }
            });
    }

    resetActiveSelectMenu(def) {
        var date = dateHelper.getCurrentJalaaliYear();
        this.yearPeriod(date.jy);
        this.monthPeriod(undefined);
        this.getCompanies(def === true);
    }

    openActiveSelectMenu() {
        if (this.companies().length === 0) {
            this.getCompanies(true);
        }
    }

    getPeriodBtn() {
        this.getCompanies(false);
    }
    openProcessManagementForm() {
        this.parent.processManagement().showForm(true);
        $(".process-box").draggable({
            scroll: true,
            handle: ".panel-heading"
        });
    }
}

