
require('./resource');
require('./model');
import { BaseViewModel } from '../master/baseViewModel.js';
import { SelectItem } from '../master/model';
import { CompanyForm, CompanyDynamicForm, Company } from './model';

export function CompanyViewModel() {
    var self = this;
    self.selectList = ko.observableArray();
    self.users = ko.observableArray();
    self.usersFiltered = ko.observableArray();
    self.userSearchKey = ko.observable();
    self.userSearchKey.subscribe(function (value) {
        if (_h.isEmpty(value)) {
            var allUsers = ko.toJS(self.users());
            self.usersFiltered(allUsers);
        } else {
            self.usersFiltered.removeAll();
            for (var i = 0; i < self.users().length; i++) {
                var isValueMultiPart = value.indexOf(" ") !== -1;
                if (!isValueMultiPart) {
                    if (self.checkWordInUsers(self.users()[i], value))
                        self.usersFiltered.push(self.users()[i]);
                } else {
                    var splits = value.split(" ");
                    var result = false;
                    for (let j = 0; j < splits.length; j++) {
                        if (!_h.isEmpty(splits[j]) && self.checkWordInUsers(self.users()[i], splits[j])) {
                            result = result || true;
                        }
                    }
                    if (result)
                        self.usersFiltered.push(self.users()[i]);
                }
            }
        }
    });
    self.checkWordInUsers = function (user, value) {
        var inUserName = user.userName.indexOf(value) !== -1;
        var inFirstName = user.firstName.indexOf(value) !== -1;
        var inLastName = user.lastName.indexOf(value) !== -1;
        if (inFirstName || inLastName || inUserName)
            return true;
        return false;
    }
    self.onTreeNodeSelect = function (item) {
        self.userSearchKey(undefined);
        self.onlySelectedRow(item);
        self.getCompanyUsers(item);
    }
    self.getSelectList = function () {
        self.apiService.request({
            name: "/api/common/getcompanylist",
            data: { controllerName : 1},
            success: function (data) {
                self.selectList.removeAll();
                if (_h.any(data))
                    for (var j = 0; j < data.length; j++) {
                        var target = data[j];
                        self.selectList.push(new SelectItem(target));
                    }
            },
            messageType: 'getSelectList',
            messageKey: self.entityName
        });
    }
    self.toggleUserState = function (item) {
        var model = {
            controllerName: 2,
            inputData: {
                idList: [item.id],
                stateType: item.stateType() === 0 ? 1 : 0
            }
        };
        self.apiService.request({
            name: "putStateType",
            data: model,
            success: function (data) {
                item.stateType(item.stateType() === 0 ? 1 : 0);
                toast.success(self.entityName, 'putUpdate', 'UserState');
            },
            error: function () {
                toast.success(self.entityName, 'putUpdate', 'UserState');
            }
        });
    }
    self.createBtn = function () {
        _h.kocnx()
            .openForm(new CompanyForm(self, false));
    }
    self.editBtn = function (id, e, target) {
        if (!target || target["currentTarget"])
            target = undefined;
        _h.kocnx()
            .openForm(new CompanyForm(self, true), target);
    }
    self.addSubsetBtn = function () {
        var selectedRecord = self.getSelectedRecord();
        _h.kocnx()
            .openForm(new CompanyForm(self, false, selectedRecord.na(), selectedRecord.id()));
    }
    self.formMakerBtn = function () {
        _h.kocnx()
            .openForm(new CompanyDynamicForm(self));
    }
    self.getCompanyUsers = function (item) {
        self.apiService.request({
            name: "/api/common/getuserslist",
            data: {
                companyId: Number(item.id()),
                controllerName: self.controllerName
            },
            success: function (data) {
                self.users.removeAll();
                self.usersFiltered.removeAll();
                if (_h.any(data))
                    for (var j = 0; j < data.length; j++) {
                        data[j].stateType = ko.observable(data[j].stateType);
                        self.users.push(data[j]);
                        self.usersFiltered.push(data[j]);
                    }
            },
            messageType: 'getList',
            messageKey: "User"
        });
    }
    self.init = function () {
        self.fillTableProperties();
        self.getRecords();
        self.getSelectList();
        self.iconSize("icon-image-small");
    }
    ko.utils.extend(self, new BaseViewModel({
        entityName: "Company",
        getList: true,
        apiService: {
            actionList: ["filterby",
                "post", "put", "delete", "getselectlist"]
        },
        buttons: [
            { name: 'disable', access: true, icon: 'DocDisable', cMenu: true },
            { name: 'enable', access: true, icon: 'DocEnable', cMenu: true },
            { name: 'addSubset', access: true, icon: 'TreeCreate', cMenu: true },
            { name: 'formMaker', access: true, icon: 'FormMaker', cMenu: true },
            { name: 'delete', access: true, icon: 'Delete', cMenu: true },
            { name: 'edit', access: true, icon: 'Edit', cMenu: true },
            { name: 'help', access: false, cMenu: false },
            { name: 'refresh', access: false, cMenu: false },
            { name: 'create', access: false, cMenu: false }
        ],
        filters: [
            { name: 'companyType', type: "select", source: companyTypes },
            { name: 'stateType', type: "select", source: stateTypes },
            { name: 'currencyName', type: "select", source: currencyNames }
        ],
        sortDirection: "Ascending",
        sortProperty: "id",
        context: self,
        saveState: true,
        cols: companyModelRes,
        selectRow: true,
        contextMenu: true,
        rowStyle: "rowStyleValue",
        searchKeyType: "enter",
        resizable: true
    }));
    self.btnVisibility = ko.computed(function () {
        var context = _h.kocnx();
        var isSelected = self.isSelectedRecord();
        var item = self.getSelectedRecord();
        var permitPeriodEdit = context.permitPeriodEdit();
        if (isSelected) {
            var companyType = item.nt();
            self.visedit(permitPeriodEdit);
            self.visdelete(permitPeriodEdit && item.id() !== context.loginCompanyId());
            self.visaddSubset(permitPeriodEdit && companyType === 0);
            self.visdisable(permitPeriodEdit && item.stateType() === 1);
            self.visenable(permitPeriodEdit && item.stateType() === 0);
        } else {
            self.visedit(false);
            self.visdelete(false);
            self.visaddSubset(false);
            self.visdisable(false);
            self.visenable(false);
        }
        self.visformMaker(context.loginCompanyType() === 0);
        self.vishelp(true);
        self.visrefresh(true);
        self.viscreate(permitPeriodEdit);
    });
    self.afterFilterBy = function () {
        self.configTools();
    };
    self.configTools = function () {
        $("#tree_view").treeView({
            nodes: self.records,
            tType: "Company",
            location: "Company",
            rootId: "_",
            context: self,
            actions: {
                onEdit: self.editBtn
            }
        });
    };
    self.treeOpenBranches = [];
    self.collectOpenBranches = function () {
        var tree = $("#tree_view");
        var ulList = tree.find("ul: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;
    };
    self.afterUpdate = function (models, searchDeep) {
        for (var i = 0; i < models.length; i++) {
            var oldRecord = self.findRecord(models[i].id, searchDeep);
            if (!_h.isNullOrEmpty(oldRecord)) {
                if (oldRecord.pi() === models[i].pi) {
                    oldRecord.refreshModel(models[i]);
                } else {
                    var parent = self.findRecord(oldRecord.pi(), searchDeep);
                    parent.children.remove(oldRecord);
                    var newParent = self.findRecord(models[i].pi, searchDeep);
                    var record = new Company(models[i], newParent);
                    newParent.children.push(record);
                }

            }
        }
    }
}