require('./model');
require('./resource');
import { BaseViewModel } from '../master/baseViewModel.js';
import {TreeFormulaSelectItem, NodeReportForm, NodeReportSelect} from '../master/model';
import { TreeForm, NodeForm, NodeValuePartViewModel, TreeSettingForm} from './model';

export function TreeViewModel() {
    var _ = this;
    _.filterType = ko.observable(0);
    _.treeTitle = ko.observable();
    _.treeValue = ko.observable();
    _.treeId = ko.observable(0);
    _.treeType = ko.observable();
    _.slfOwnerTree = ko.observable(undefined);
    _.newTree = ko.observable(undefined);
    _.nodeEditModel = ko.observable();
    _.showNodeEdit = ko.observable(false);
    _.showReferenceTab = ko.observable(false);
    _.searchNodeKey = ko.observable();
    _.refSearchNodeKey = ko.observable();
    _.refFilterType = ko.observable(0);
    _.eButtons = {
        "EditNode": ko.observable(false),
        "DeleteNode": ko.observable(false),
        "DeleteNodes": ko.observable(false),
        "CreateNode": ko.observable(false),
        "Sort": ko.observable(false),
        "NodeReport": ko.observable(false),
        "NodeReports": ko.observable(false),
        "ToBranch": ko.observable(false),
        "ToLeaf": ko.observable(false),
        "ExportExcel": ko.observable(false),
        "ExportAllExcel": ko.observable(false),
        "ImportExcel": ko.observable(false),
        "Paste": ko.observable(false),
        "Copy": ko.observable(false),
        "Cut": ko.observable(false),
        "SaveChange": ko.observable(false),
        "Cancel": ko.observable(false),
        "SaveSort": ko.observable(false),
        "Refresh": ko.observable(false),
        "ResetConsolidate": ko.observable(false),
        "Setting": ko.observable(false)
    }
    _.edSelector = "#tree_view_ed";
    _.onCallbackAction = function (disable) {
        for (var k in _.eButtons) {
            if (_.eButtons.hasOwnProperty(k)) {
                var param = _.eButtons[k];
                param(false);
            }
        }
        if (disable) {
            _.eButtons.Refresh(true);
            _.eButtons.Setting(true);
            return;
        }
        if (!_.treeId())
            return;
        var item = _.selectedRowRecord();
        if (item.changeCount() === -1)
            return;
        var complexMode = false;
        var actions = $(_.edSelector).treeView("getToolbarData");
        if (actions.length)
            for (var i = 0; i < actions.length; i++) {
                if (actions[i].visible)
                    _.eButtons[actions[i].name](true);
                if (actions[i].name === "Paste")
                    complexMode = true;
            }
        _.eButtons.Setting(!complexMode);
        if (_.nodes.length === 0)
            _.eButtons.CreateNode(true);
        _.eButtons.Refresh(!complexMode);
    };
    _.onClickToolbar = function (action) {
        var selectedItems;
        switch (action) {
            case "Refresh":
                _.refreshEditor();
                break;
            case "ImportExcel":
                selectedItems = $(_.edSelector).treeView("selectedItems");
                if (selectedItems.length === 1) {
                    _.importExcelBtn(selectedItems.id);
                }
                break;
            case "ExportAllExcel":
            case "ExportExcel":
            case 1:
            case 2:
                selectedItems = $(_.edSelector).treeView("selectedItems");
                if (selectedItems.length === 1) {
                    var model = {
                        controllerName: 4,
                        inputData: {
                            id: selectedItems[0].id,
                            getAll: action === "ExportAllExcel" || action === 2
                        }
                    };
                    _h.kocnx().createExcel(model);
                }
                break;
            case "SaveChange":
                _.saveChanges();
                break;
            default:
                $(_.edSelector).treeView("exeAction", action);
                break;
        }
    };
    _.onImportExcel = function () {
        _.onClickToolbar("ImportExcel");
    };
    _.onExportAllExcel = function () {
        _.onClickToolbar("ExportAllExcel");
    };
    _.onExportExcel = function () {
        _.onClickToolbar("ExportExcel");
    };
    _.nodes = [];
    _.referenceNodes = [];
    _.currentNodes = [];
    _.onNodeEnterSearchKey = function (d, e) {
        if (e.keyCode === 13) {
            if (window.resSecondDomain === "treeList") {
                _.getDiffNodes(function (res) {
                    if (res) {
                        _.configTools(true);
                    }
                });
            } else {
                if (_.showReferenceTab()) {
                    _.getDiffNodes(function (res) {
                        if (res) {
                            _.configTools(true);
                        }
                    });
                } else {
                    if (_.treeId())
                        _.getNodes(function (res) {
                            if (res) {
                                _.configTools();
                            }
                        });
                }
            }
        }
        return true;
    };
    _.treeList = ko.observableArray();
    _.getTreeSelectList = function (callback) {
        _.apiService.request({
            name: "generalTreeList",
            data: { controllerName: 4 },
            success: function (data) {
                _.treeList.removeAll();
                if (!_h.isNullOrEmpty(data)) {
                    for (var j = 0; j < data.length; j++) {
                        var item = new TreeFormulaSelectItem(data[j]);
                        _.treeList.push(item);
                    }
                }
                callback(true);
            },
            error: function () {
                var text = _h.getApiMessage("ErrorLoadTree");
                _h.failToast(text);
                callback(false);
            }
        });
    };
    _.createBtn = function () {
        _h.kocnx()
            .openForm(new TreeForm(_));
    };
    _.editBtn = function () {
        _h.kocnx()
            .openForm(new TreeForm(_, true));
    };
    _.exportExcelBtn = function (i, e) {
        var item = _.selectedRowRecord();
        var type = $(e.target).attr("data-type");
        var model = {
            controllerName: 4,
            inputData: {
                id: item.id(),
                getAll: Number(type) === 2
            }
        };
        _h.kocnx().createExcel(model);
    };
    _.showNodeReport = ko.observable(false);
    _.nodeReportModel = ko.observable();
    _.nodeCreateBtn = function () {
        var item = _.selectedRowRecord();
        $(_.edSelector).treeView("nodeCreate",
            item.treeType(),
            item.assignmentType(),
            item.accountType(),
            _h.kocnx().loginCompanyId());
    };
    _.nodeSortBtn = function () {
        $(_.edSelector).treeView("nodeSort");
    };
    _.onNodeReport = function () {
        _.nodeReportHandler();
    };
    _.onNodeReports = function () {
        _.nodeReportHandler();
    };
    _.nodeReportHandler = function (id, inModel, outList, percent, title, processStatus) {
        if (document.hidden)
            return false;
        var context = _h.kocnx();
        if (!_.showNodeReport()) {
            var model = new NodeReportForm(_);
            for (var j = 0; j < nodeReportTypes.length; j++) {
                var target = new NodeReportSelect(nodeReportTypes[j]);
                if (inModel && inModel.items.indexOf(target.id()) !== -1) {
                    target.selected(true);
                }
                model.nodeReportSelects.push(target);
            }
            if (outList) {
                model.id(id);
                model.processStatus(processStatus);
                model.title(title);
                model.percent(percent);
                model.fillReports(outList);
                model.inProgress(true);
            }
            context.openForm(model);
        } else {
            context.formModel().id(id);
            context.formModel().processStatus(processStatus);
            context.formModel().title(title);
            context.formModel().percent(percent);
            context.formModel().fillReports(outList);
            context.formModel().inProgress(true);
        }
    };
    _.nodeReportCancel = function (model, e) {
        if (!_h.kocnx().formModel().inProgress()) {
            _h.kocnx().closeForm();
            return;
        }
        _.apiService.request({
            splashId: ".node-report-modal",
            name: "/api/process/putcancel",
            data: { id: _h.kocnx().formModel().id() },
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    _h.kocnx().closeForm();
                }
            },
            error: function () {
            }
        });
    };
    _.nodeReport = function () {
        var selectedItems = $(_.edSelector).treeView("selectedItems");
        if (selectedItems.length === 0) {
            var error = _h.getApiMessage("NodeReportZeroCountError");
            _h.failToast(error);
            return;
        }
        var model = {
            treeId: _.treeId(),
            idList: [],
            items: []
        };
        selectedItems.filter(a => model.idList.push(a.id));
        for (var i = 0; i < _h.kocnx().formModel().nodeReportSelects().length; i++) {
            var target = _h.kocnx().formModel().nodeReportSelects()[i];
            if (target.selected())
                model.items.push(target.id());
        }
        _.apiService.request({
            name: "postNodeReport",
            data: model,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    _h.kocnx().checkProcessQueue(true);
                    localStorage.setItem("ProcessToken", "");
                }
            },
            error: function () {
            }
        });
    };
    _.importExcelBtn = function (id) {
        if (_h.isEmpty(id) || typeof id === 'object')
            id = _.selectedRowRecord().id();
        _h.kocnx().importFileBtn(id, _, "Excel");
    };
    _.onDeleteNode = function () {
        _.onDeleteNodes();
    };
    _.onDeleteNodes = function () {
        var error;
        var selectedItems = $(_.edSelector).treeView("selectedItems");
        if (selectedItems.length === 0) {
            error = _h.getApiMessage("NodeDeletedZeroCountError");
            _h.failToast(error);
            return;
        }
        $(_.edSelector).treeView("selectSubSet", selectedItems);

        selectedItems = $(_.edSelector).treeView("selectedItems");
        var nodeIdList = [];
        if (selectedItems.length)
            for (var i = 0; i < selectedItems.length; i++) {
                nodeIdList.push(selectedItems[i].id);
            }

        var model = {
            treeId: _.treeId(),
            idList: nodeIdList
        };
        var menu = document.getElementsByClassName("context-menu")[0];
        if (menu)
            menu.parentNode.removeChild(menu);
        var confirmText = _h.getApiMessage("NodeDeletedConfirm").replace("__", selectedItems.length);
        _h.confirmDeleteAlert(confirmText,
            function (res) {
                if (res) {
                    _.apiService.request({
                        name: "deleteNode",
                        data: model,
                        success: function (data) {
                            if (!_h.isNullOrEmpty(data)) {
                                $(_.edSelector).treeView("removeItems");
                                toast.success(_.entityName, 'custom',
                                    selectedItems.length > 1 ? 'NodesDelete' : 'NodeDelete');
                            }
                        },
                        error: function () {
                            toast.error(_.entityName, 'custom',
                                selectedItems.length > 1 ? 'NodesDelete' : 'NodeDelete');
                        }
                    });
                }
            });
    };
    _.onToBranch = function () {
        _.changeNodeType();
    };
    _.onToLeaf = function () {
        _.changeNodeType();
    };
    _.changeNodeType = function () {
        var selectedItems = $(_.edSelector).treeView("selectedItems");
        _.apiService.request({
            name: "putNodeType",
            data: { id: Number(selectedItems[0].id) },
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    toast.success(_.entityName, 'custom',
                        selectedItems[0].nodeType === 2 ? 'ToLeaf' : 'ToBranch');
                    if (_h.any(data.models)) {
                        $(_.edSelector).treeView("refreshTree", data.models);
                    }
                }
            },
            error: function () {
                toast.error(_.entityName, 'custom',
                    selectedItems[0].nodeType === 2 ? 'ToLeaf' : 'ToBranch');
            }
        });
    };
    _.pasteBtn = function () {
        var inComplex = $(_.edSelector).treeView("inComplexMode");
        if (inComplex.cut || inComplex.copy)
            _.onPaste(true);
    };
    _.onPaste = function (inRoot) {
        _.collectOpenBranches();
        var model = $(_.edSelector).treeView("getPasteModel", inRoot);
        _.apiService.request({
            name: "putPaste",
            data: model,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    if (_h.any(data.models)) {
                        $(_.edSelector).treeView("refreshTree", data.models);
                    }
                    if (_.treeOpenBranches && _.treeOpenBranches.length)
                        $(_.edSelector).treeView("expand", _.treeOpenBranches);
                    $(_.edSelector).treeView("refreshAfterPaste", model.type);
                    toast.success(_.entityName, 'custom',
                        model.type === 1 ? 'Copy' : 'Cut');
                    if (model.type !== 1)
                        _.onCallbackAction();
                }
            },
            error: function () {
                toast.error(_.entityName, 'custom',
                    model.type === 1 ? 'Copy' : 'Cut');
                _.onCallbackAction();
            }
        });
    };
    _.confirmEditNode = function () {
        if (!_h.isNullOrEmpty(_.nodeEditModel()) && _.nodeEditModel().isValid()) {
            var editModel = _.nodeEditModel().toUpdateTree();
            $(_.edSelector).treeView("refreshTree", [editModel], true);
        }
        _.onCallbackAction();
    };
    _.closeEditNode = function () {
        if (!_h.isNullOrEmpty(_.nodeEditModel())) {
            _.showNodeEdit(false);
        }
        _.onCallbackAction();
    };
    _.onEditNode = function (el, object) {
        if (!_.showNodeEdit()) {
            var model = new NodeForm();
            object = _.fixNodeCreateModel(object);
            model.fillModel(object);
            _.nodeEditModel(model);
            var pos = _h.getPosition(el);
            _.showNodeEdit(true);
            $(".nodeedit-box").css({
                left: pos.left + "px",
                top: (pos.top - 410) + "px"
            });
            $(".nodeedit-box").draggable({
                scroll: true,
                handle: ".nodeEdit-drag-handle"
            });
        } else {
            if (!_h.isNullOrEmpty(_.nodeEditModel()) && _.nodeEditModel().isValid()) {
                object = _.fixNodeCreateModel(object);
                var editModel = _.nodeEditModel().toUpdateTree();
                $(_.edSelector).treeView("refreshTree", [editModel], true);
                _.nodeEditModel().fillModel(object);
            }
        }
        _.onCallbackAction();
    };
    _.fixNodeCreateModel = function (obj) {
        if (obj.id === 0) {
            var item = _.selectedRowRecord();
            for (var k in obj) {
                if (obj.hasOwnProperty(k)) {
                    var data = obj[k];
                    if ((data + "") == "NaN") {
                        switch (k) {
                            case "tt":
                                obj.tt = item.treeType();
                                break;
                            case "as":
                                obj.as = item.assignmentType();
                                break;
                            case "at":
                                obj.at = item.accountType();
                                break;
                        }
                    }
                }
            }
        }
        return obj;
    }
    _.onNodeValuePart = function (id) {
        _h.kocnx()
            .openForm(new NodeValuePartViewModel(id));
    };
    _.saveChanges = function (i, e) {
        if (_.showNodeEdit()) {
            var text = _h.getApiMessage("PreventSaveForOpenDialog");
            toast.custom("error", text);
            return;
        }
        _.collectOpenBranches();
        var list = $(_.edSelector).treeView("getChangedItems");
        if (!list || !list.length)
            return;
        var model = {
            treeId: _.treeId(),
            list: list
        };
        _.apiService.request({
            name: "putNode",
            data: model,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    _.treeValue(data.treeValue);
                    if (_h.any(data.models)) {
                        $(_.edSelector).treeView("refreshTree", data.models);
                        if (_.treeOpenBranches && _.treeOpenBranches.length)
                            $(_.edSelector).treeView("expand", _.treeOpenBranches);
                    }
                    if (_h.any(data.nodeErrors)) {
                        $(_.edSelector).treeView("setErrors", data.nodeErrors);
                        var text = _h.getApiMessage("NodeUpdateErrors");
                        text = text.replace("__", data.nodeErrors.length);
                        toast.custom("warning", text);
                        _.eButtons.SaveChange(true);
                    } else {
                        $(_.edSelector).treeView("resetErrors");
                        toast.success(_.entityName, 'custom', 'UpdateNode');
                        _.onCallbackAction();
                    }
                }
            },
            error: function () {
                toast.error(_.entityName, 'custom', 'UpdateNode');
            }
        });
    };
    _.refreshEditor = function (model, e) {
        if (!e || !_.showReferenceTab()) {
            var item = _.selectedRowRecord();
            if (item.changeCount() !== -1)
                _.getNodes(function (res) {
                    if (res) {
                        _.configTools();
                    }
                });
        }
        if (_.showReferenceTab()) {
            _.getDiffNodes(function (res) {
                if (res) {
                    _.configTools(true);
                }
            });
            _.onCallbackAction(true);
        }
    };
    _.getNodes = function (callback) {
        var model = {
            treeId: _.treeId(),
            filterType: _.filterType(),
            searchKey: _.searchNodeKey()
        };
        _.apiService.request({
            name: "getNode",
            data: model,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    _.nodes = data.models;
                    _.treeValue(data.treeValue);
                    callback(true);
                } else {
                    _.treeValue(undefined);
                    $(_.edSelector).treeView("removeTree");
                }
                _.onCallbackAction();
            },
            error: function () {
                var text = _h.getApiMessage("ErrorLoadTree");
                _h.failToast(text);
                callback(false);
            }
        });
    };
    _.configTools = function (deffTreesConfig) {
        var context = _h.kocnx();
        var period = !_h.isNullOrEmpty(context.periodItem()) && context.permitPeriodEdit();
        if (deffTreesConfig) {
            if (_.referenceNodes.length)
                $("#tree_view_rf").treeView({
                    tType: "Reference",
                    location: "Reference",
                    nodes: _.referenceNodes,
                    rootId: _.treeId(),
                    controllerName: 5,
                    onApplyItem: _.onApplyItem,
                    onRejectItem: _.onRejectItem,
                    permitPeriodEdit: period,
                    onDeffTreeSelect: _.onDeffTreeSelect,
                });
            if (_.currentNodes.length)
                $("#tree_view_cr").treeView({
                    tType: "Current",
                    location: "Current",
                    nodes: _.currentNodes,
                    rootId: _.treeId(),
                    controllerName: 5,
                    permitPeriodEdit: period,
                    onDeffTreeSelect: _.onDeffTreeSelect
                });
            _.onCallbackAction(true);
        } else {
            var item = _.selectedRowRecord();
            $(_.edSelector).treeView({
                tType: "Editor",
                location: "Editor",
                nodes: _.nodes,
                rootId: item.id(),
                controllerName: 5,
                permitPeriodEdit: period,
                companyId: context.loginCompanyId(),
                companyType: context.loginCompanyType(),
                companyIsRoot: context.currentCompany().irt,
                actions: {
                    onNodeReport: _.onNodeReport,
                    onNodeReports: _.onNodeReports,
                    onDeleteNode: _.onDeleteNode,
                    onDeleteNodes: _.onDeleteNodes,
                    onToBranch: _.onToBranch,
                    onToLeaf: _.onToLeaf,
                    onEditNode: _.onEditNode,
                    onNodeValuePart: _.onNodeValuePart,
                    onCallbackAction: _.onCallbackAction,
                    onPaste: _.onPaste,
                    onExportExcel: _.onExportExcel,
                    onImportExcel: _.onImportExcel,
                    onExportAllExcel: _.onExportAllExcel,
                    onResetConsolidate: _.onResetBranchConsolidate
                }
            });
        }
    };
    _.onDeffTreeSelect = function (type, list) {
        if (type === "ref") {
            $("#tree_view_cr").treeView("changeSelectedItem", list);
        } else {
            $("#tree_view_rf").treeView("changeSelectedItem", list);
        }
    };
    _.onSelectRecord = function (target, sign) {
        if (target.id() === _.treeId()) {
            return;
        }
        _.slfOwnerTree(_h.kocnx().loginCompanyId() === target.cbCompanyId());
        _.newTree(target.changeCount() === -1);
        _.treeId(target.id());
        _.treeTitle(target.name());
        _.treeType(target.treeType());
        _.nodeEditModel(null);
        if (target.changeCount() !== -1) {

            _.getNodes(function (res) {
                if (res) {
                    _.configTools();
                    if (sign)
                        $('a[href="#reference-t"]').trigger('click');
                }
            });
            _.onCallbackAction();
        } else {
            _.treeValue(undefined);
            $(_.edSelector).treeView("removeTree");
            _.onCallbackAction();
        }

    };
    _.expandAll = function () {
        $(_.edSelector).treeView("expandAll");
    };
    _.collapseAll = function () {
        $(_.edSelector).treeView("collapseAll");
    };
    _.init = function () {
        window.resSecondDomain = "tree";
        _.fillTableProperties();
        _.getRecords();

        _.getFolderList();
        _.iconSize("icon-image-small");
    };
    _.newTreeBtn = function (btn, item) {
        if (!item || item["icon"])
            item = _.selectedRowRecord();
        if (!item["name"] && btn["name"])
            item = btn;
        var message = _h.getApiMessage("NewTreeConfirm");
        message = message.replace("__", item.name());
        _h.confirmChooseAlert(message,
            function (res) {
                _.syncTrees(res ? 0 : 1);
            });
    };
    _.onApplyItem = function (list) {
        _.syncTrees(3, list);
    };
    _.onRejectItem = function (list) {
        _.syncTrees(4, list);
    };
    _.changesTreeBtn = function () {
        var item = _.selectedRowRecord();
        var text = _h.getApiMessage("ChangesTreeConfirm");
        text = text.replace("__", item.name());
        _h.confirmChooseAlert(text,
            function (res) {
                switch (res) {
                    case true:
                        _.syncTrees(0);
                        break;
                    case false:
                        _.syncTrees(1);
                        break;
                }
            });
    };
    _.syncTrees = function (type, list) {
        _.collectOpenBranches();
        var model = {};
        switch (type) {
            case 0:
            case 1:
                model = {
                    id: _.treeId(),
                    acceptAll: type === 0,
                    rejectAll: type === 1,
                    accepted: [],
                    rejected: []
                };
                break;
            case 3:
                model = {
                    id: _.treeId(),
                    acceptAll: false,
                    rejectAll: false,
                    accepted: list,
                    rejected: []
                };
                break;
            case 4:
                model = {
                    id: _.treeId(),
                    acceptAll: false,
                    rejectAll: false,
                    accepted: [],
                    rejected: list
                };
                break;
        }
        _.apiService.request({
            name: "postSyncTrees",
            data: model,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    switch (type) {
                        case 0:
                            $(_.edSelector).treeView("removeTree");
                            toast.success(_.entityName, 'custom', 'AcceptAllSyncTree');
                            _.newTree(false);
                            _.treeId(undefined);
                            _.treeTitle(undefined);
                            _.getRecords();
                            break;
                        case 1:
                            $(_.edSelector).treeView("removeTree");
                            toast.success(_.entityName, 'custom', 'RejectAllSyncTree');
                            _.newTree(false);
                            _.treeId(undefined);
                            _.treeTitle(undefined);
                            _.getRecords();
                            break;
                        case 3:
                            toast.success(_.entityName, 'custom', 'AcceptListSyncTree');
                            _.getDiffNodes(function (res) {
                                if (res) {
                                    _.configTools(true);
                                    setTimeout(function () {
                                        if (_.treeOpenBranches && _.treeOpenBranches.length)
                                            $("#tree_view_rf").treeView("expand", _.treeOpenBranches);
                                    }, 150);
                                }
                            });
                            break;
                        case 4:
                            toast.success(_.entityName, 'custom', 'RejectListSyncTree');
                            _.getDiffNodes(function (res) {
                                if (res) {
                                    _.configTools(true);
                                    setTimeout(function () {
                                        if (_.treeOpenBranches && _.treeOpenBranches.length)
                                            $("#tree_view_rf").treeView("expand", _.treeOpenBranches);
                                    }, 150);
                                }
                            });
                            break;
                    }
                }
            },
            error: function () {
                toast.error(_.entityName, 'custom', 'SyncTree');
            }
        });
    };
    ko.utils.extend(_, new BaseViewModel({
        entityName: "Tree",
        apiService: {
            actionList: ["filterby",
                "post", "put", "delete", "postnodereport", "deleteNode",
                "getnode", "putnode", "deletenode",
                "putnodetype", "putpaste", "postsynctrees",
                "getdifftrees", "gettreesetting", "puttreesetting", "postresetbranch"]
        },
        getList: true,
        filters: [
            { name: 'accountType', type: "select", source: accountTypes },
            { name: 'assignmentType', type: "select", source: assignmentTypes },
            { name: 'valueType', type: "select", source: valueTypes },
            { name: 'showRejected', type: "bool" }
        ],
        buttons: [
            { name: 'edit', access: true, icon: 'Edit', cMenu: true },
            { name: 'delete', access: true, icon: 'Delete', cMenu: true },
            {
                name: 'exportExcel', access: true, icon: 'ExportExcel',
                cMenu: true, templateName: "excelexport-table-template"
            },
            { name: 'newTree', access: true, icon: 'AcceptTable', cMenu: true },
            { name: 'changesTree', access: true, icon: 'AcceptTable', cMenu: true },

            { name: 'importExcel', access: true, icon: 'ImportExcel', cMenu: true },
            { name: 'help', access: false, cMenu: false },
            { name: 'refresh', access: false, cMenu: false },
            { name: 'tools', templateName: "toolsbtn-tree-template", access: false, cMenu: false },
            { name: 'create', access: true, cMenu: false }
        ],
        sortDirection: "Ascending",
        sortProperty: "id",
        context: _,
        cols: treeModelRes,
        searchKeyType: "enter",
        selectRow: true,
        contextMenu: true,
        tableStyle: "font-size: 11px;table-layout: auto;",
        tableClass: "table ko-tbl",
        saveState: true,
        folderManagement: true
    }));
    _.btnVisibility = ko.computed(function () {
        var context = _h.kocnx();
        var period = !_h.isNullOrEmpty(context.periodItem()) && context.permitPeriodEdit();
        var item = _.selectedRowRecord();
        if (!_h.isNullOrEmpty(item)) {
            var owner = item.cbCompanyId()
                === context.loginCompanyId();
            var hasChild = item.hasChildren();
            var group = context.loginCompanyType() !== 1;
            var isNew = item.changeCount() === -1;
            _.visedit(period && !isNew);
            _.visdelete((owner && !hasChild && period && !isNew) || (!owner && period && !isNew));
            if (group) {
                _.visexportExcel(_h.contains([6, 7, 8], item.treeType()) && !_h.isNullOrEmpty(context.periodItem()) && !isNew);
                _.visimportExcel(_h.contains([6, 7, 8], item.treeType()) && period && !isNew);
            } else {
                _.visexportExcel(_h.contains([2, 3, 6, 7, 8], item.treeType()) && !_h.isNullOrEmpty(context.periodItem()) && !isNew);
                _.visimportExcel(_h.contains([2, 3, 6, 7, 8], item.treeType()) && period && !isNew);
            }
            _.visnewTree(isNew);
            _.vischangesTree(item.changeCount() > 0);
        } else {
            _.visedit(false);
            _.visdelete(false);
            _.visexportExcel(false);
            _.visimportExcel(false);
            _.visnewTree(false);
            _.vischangesTree(false);
        }
        _.viscreate(period);
        _.vistools(true);
        _.vishelp(true);
        _.visrefresh(true);
    });
    _.proxyKeyboard = function (type) {
        switch (type) {
            case "create":
                if (window.resSecondDomain === "editor") {
                    $(_.edSelector).treeView("nodeCreate");
                } else {
                    if (_.viscreate())
                        _.createBtn();
                }
                break;
            case "refresh":
                if (window.resSecondDomain === "editor") {
                    _.getNodes(function (res) {
                        if (res) {
                            _.configTools();
                        }
                    });
                } else {
                    _.refreshTable();
                }
                break;
            case "delete":
                if (window.resSecondDomain === "editor") {
                    _.onDeleteNodes();
                } else {
                    if (_.visdelete())
                        _.deleteBtn();
                }
                break;
            case "edit":
                if (window.resSecondDomain === "editor") {
                    $(_.edSelector).treeView("nodeEditTrigger");
                } else {
                    if (_.visedit())
                        _.editBtn();
                }
                break;
        }
    };
    _.isVisibleColumn = function (name) {
        var record = null;
        ko.utils.arrayFilter(_.tableProperties(),
            function (col) {
                if (col.name === name) {
                    record = col;
                }
            });
        if (record === null)
            return false;

        if (record.name === 'id')
            return true;
        return record.visibleCol() && record.tablecol;
    };
    _.getDiffNodes = function (callback) {
        if (!_.treeId())
            return;
        var model = {
            treeId: _.treeId(),
            referenceFilterType: _.refFilterType(),
            referenceSearchKey: _.refSearchNodeKey(),
            currentFilterType: _.filterType(),
            currentSearchKey: _.searchNodeKey()
        };
        _.apiService.request({
            name: "getDiffTrees",
            data: model,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    if (_h.any(data.referenceTree)) {
                        _.referenceNodes = data.referenceTree;
                        $("#tree_view_rf").treeView("removeTree");
                    } else {
                        _.referenceNodes = [];
                        $("#tree_view_rf").treeView("removeTree");
                    }

                    if (_h.any(data.currentTree)) {
                        $("#tree_view_cr").treeView("removeTree");
                        _.currentNodes = data.currentTree;
                    } else {
                        $("#tree_view_cr").treeView("removeTree");
                        _.currentNodes = [];
                    }
                    callback(true);
                }

            },
            error: function () {
                callback(false);
            }
        });
    };
    _.toggleReferenceTab = function (href) {
        var item = _.selectedRowRecord();
        switch (href) {
            case "#reference-t":
                _.showReferenceTab(true);
                _.searchNodeKey(undefined);
                _.refSearchNodeKey(undefined);
                _.filterType(0);
                _.getDiffNodes(function (res) {
                    if (res) {
                        _.configTools(true);
                    }
                });
                break;
            case "#list-t":
                _.showReferenceTab(false);
                _.searchNodeKey(undefined);
                _.refSearchNodeKey(undefined);
                _.filterType(0);

                _.getRecords(item.id());
                break;
        }
    };
    _.afterFilterBy = function (data, selectedId) {
        if (selectedId && _.records().length) {
            for (var i = 0; i < _.records().length; i++) {
                var target = _.records()[i];
                if (!_.groupProperty()) {
                    if (target.id() === selectedId) {
                        _.treeId(undefined);
                        _.onlySelectedRow(target);
                        _.onSelectRecord(target);
                    }
                } else {
                    for (var j = 0; j < target.list().length; j++) {
                        var innerTarget = target.list()[j];
                        if (innerTarget.id() === selectedId) {
                            _.treeId(undefined);
                            _.onlySelectedRow(innerTarget);
                            _.onSelectRecord(innerTarget);
                        }
                    }
                }
            }
        }
        _.resetTrees();

    }
    _.onChangeLabelClick = function (item) {
        _.onSelectRecord(item[0], true);
    };
    _.onNewLabelClick = function (item) {
        _.newTreeBtn(null, item[0]);
    };
    _.resetTrees = function () {
        _.treeId(0);
        _.treeTitle(undefined);
        $(".dmn-tree").empty();
    };
    _.rightClickSelectRow = function (target, eventTarget, event) {
        if (_.configTable.selectRow && _.configTable.contextMenu)
            _.selectedRow(target, event, true);
    };
    _.selectedRow = function (target, e, rightClick) {
        if (!_.eButtons.SaveChange()) {
            var ctrlSelect = e.ctrlKey;
            var shiftSelect = e.shiftKey;
            if (shiftSelect === undefined) shiftSelect = false;
            if (ctrlSelect === undefined) ctrlSelect = false;
            var res = _.isValidClickSingleRow(e);
            if (res !== "label") {
                _.changeSelectedRecord(target, ctrlSelect, shiftSelect, rightClick);
                _.fillChildModel(target);
            } else {
                _.changeSelectedRecord(target, ctrlSelect, shiftSelect, rightClick);
                _.fillChildModel(target);
            }
        } else {
            var confirmText = _h.getApiMessage("HasChangedConfirm");
            confirmText = confirmText.replace("__", "درختواره");
            _h.confirmDeleteAlert(confirmText,
                function (res) {
                    if (res) {
                        var ctrlSelect = e.ctrlKey;
                        var shiftSelect = e.shiftKey;
                        if (shiftSelect === undefined) shiftSelect = false;
                        if (ctrlSelect === undefined) ctrlSelect = false;
                        var isValid = _.isValidClickSingleRow(e);
                        if (isValid !== "label") {
                            _.changeSelectedRecord(target, ctrlSelect, shiftSelect, rightClick);
                            _.fillChildModel(target);
                        } else {
                            _.changeSelectedRecord(target, ctrlSelect, shiftSelect, rightClick);
                            _.fillChildModel(target);
                        }
                    }
                });
        }
    };
    _.treeOpenBranches = [];
    _.collectOpenBranches = function () {
        _.treeOpenBranches = [];
        var tree = $(_.edSelector);
        if (tree.length === 0) {
            tree = $("#tree_view_rf");
        }
        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"));
            }
        _.treeOpenBranches = array;
    };
    _.openTreeSetting = function () {
        _.apiService.request({
            name: "getTreeSetting",
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    _h.kocnx()
                        .openForm(new TreeSettingForm(_, data));
                }
            },
            error: function () {
            }
        });
    }
    _.confirmSettingNode = function (parents, btnModel, e) {
        var item = parents[1];
        var model = item.toServer();
        _.apiService.request({
            name: "putTreeSetting",
            data: model,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    _h.kocnx().closeForm();
                    toast.success(_.entityName, 'custom', 'SaveSettingNode');
                    _.getNodes(function (res) {
                        if (res) {
                            _.configTools();
                        }
                    });
                }
            },
            error: function () {

            }
        });
    }
    _.onResetBranchConsolidate = function (nodeId) {
        var confirmText = _h.getApiMessage("ResetConsolidateBranchConfirm");
        _h.confirmDeleteAlert(confirmText, function (res) {
            if (res) {
                _.resetConsolidate(1, nodeId);
            }
        });
    }
    _.onResetTreeConsolidate = function () {
        var confirmText = _h.getApiMessage("ResetConsolidateBranchConfirm");
        _h.confirmDeleteAlert(confirmText, function (res) {
            if (res) {
                _.resetConsolidate(2);
            }
        });
    }
    _.resetConsolidate = function (type, nodeId) {
        _.collectOpenBranches();
        var model = {};
        switch (type) {
            case 1:
                model.treeId = _.treeId();
                model.nodeId = nodeId;
                break;
            case 2:
                model.treeId = _.treeId();
                break;
        }
        _.apiService.request({
            name: "postResetBranch",
            data: model,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    switch (type) {
                        case 1:
                            if (_h.any(data.models)) {
                                $(_.edSelector).treeView("refreshTree", data.models);
                                if (_.treeOpenBranches && _.treeOpenBranches.length)
                                    $(_.edSelector).treeView("expand", _.treeOpenBranches);
                            }
                            toast.success(_.entityName, 'custom', 'ResetConsolidationBranch');
                            break;
                        case 2:
                            toast.success(_.entityName, 'custom', 'ResetConsolidationTree');
                            _.getNodes(function (res) {
                                if (res) {
                                    _.configTools();
                                }
                            });
                            break;
                    }
                }
            },
            error: function () {

            }
        });
    }
}

$(document).on("shown.bs.tab", '.tree-tab a[data-toggle="tab"]', function () {
    var href = $(this).attr("href");
    _h.kocnx().treevm().toggleReferenceTab(href);
    return false;
});
$(document).on("focus", '.focus-area', function (e) {
    var parent = $(e.currentTarget).parent();
    $(parent).find(".header-title").css("font-weight", "300");

    var loc = $(e.currentTarget).attr("data-loc");
    switch (loc) {
        case "editor":
            $(e.currentTarget).find(".header-title").css("font-weight", "bold");
            break;
        case "treeList":
            $(e.currentTarget).find(".header-title").css("font-weight", "bold");
            break;
    }
    window.resSecondDomain = loc;
});



