var { BaseModel, BaseFormModel, FormBuilder, BaseSecondaryForm, BaseInnerModel, BaseInfoModel } = require('../master/baseModels.js');
import { SelectItem, TreeFormulaSelectItem, PeriodSelectItem, CompanySelectItem } from '../master/model';

import { ApiService } from "../../util/apiService.js";
require('knockout.validation');
import { BaseViewModel } from '../master/baseViewModel.js';
import ApexCharts from 'apexcharts';
export class TableTemplate extends BaseModel {
    constructor(model) {
        super(model);
        this.shortDesc = ko.pureComputed(function () {
            var code = this.code();
            var templateTableType = _h.getEnumText(templateTableTypes, this.templateTableType());

            return code + "-" + templateTableType;
            ;
        }, this);
        this.shortName = ko.pureComputed(function () {
            var title = this.title();
            if (!_h.isEmpty(title)) {
                if (title.length < 50)
                    return title;
                return title.substr(0, 47) + "...";
            }
            return "";
        }, this);
        this.lockedCaption = ko.pureComputed(function () {
            var lockedBy = this.lockedBy();
            if (lockedBy)
                return "قفل شده توسط " + lockedBy;
        }, this);
    }
}
export class TableTemplateForm extends BaseFormModel {
    constructor(viewModel, editMode, res) {
        super(viewModel, editMode);
        this.updateTemplateTableType = true;
        this.lastPriority = ko.observable();
        this.fileName = ko.observable();
        this.file = ko.observable();
        this.fileType = ko.observable();
        this.templateTypes = [
            { text: "صورت مالی", enText: "FinanceStatement", value: 1, color: "" },
            { text: "یادداشت همراه", enText: "Note", value: 2, color: "" }
        ];
        this.fillLists();
        if (editMode) {
            var model = viewModel.getSelectedRecord();
            this.lastPriority(res);
            this.updateTemplateTableType = false;
            this.templateTableType(model.templateTableType());
            this.updateTemplateTableType = true;
        }
        else {
            this.lastPriority(res + 1);
            this.priority(res + 1);
        }
        this.condFirst = ko.pureComputed(function () {
            return this.templateTableType() !== 4;
        }, this);

        this.condSecond = ko.pureComputed(function () {
            return !_h.isNullOrEmpty(this.templateTableType()) && this.templateTableType() !== 4;
        }, this);
        this.condThird = ko.pureComputed(function () {
            return this.templateTableType() === 4;
        }, this);
        this.setValidationObject();
        this.createForm();
    }
    setValidationObject() {
        var self = this;
        self.validationObject = ko.validatedObservable({
            title: self.title.extend({
                required: true,
                minLength: 3,
                maxLength: 100,
                validCharacterName: true,
                remoteIsUniqueRule: { params: [self.id, "TableTemplate", "title", "remotePlaceHolder"] }
            }),
            templateTableType: self.templateTableType.extend({
                required: true
            }),
            accountType: self.accountType.extend({
                required: {
                    onlyIf: function () {
                        return self.templateTableType() !== 4;
                    }
                }
            }),
            defaultRowNumber: self.defaultRowNumber.extend({
                required: true,
                number: true,
                min: 1,
                max: 100
            }),
            defaultColumnNumber: self.defaultColumnNumber.extend({
                required: true,
                number: true,
                min: 1,
                max: 100
            }),
            file: self.file.extend({
                checkOnlyExcel: { params: [self.fileName] }
            })
        });
    }
    handleFileChoose(files) {
        var file = files;
        var ext = _h.getExtension(file.name);
        _h.toBase64(file, function (res) {
            this.file(res);
        }.bind(this));
        switch (ext) {
            case "xls":
                this.fileType(8);
                break;
            case "xlsx":
                this.fileType(9);
                break;
            default:
        }
        this.fileName(file.name);
    }
    fillLists() {
        this.templateTypes = [
            { text: "صورت مالی", enText: "FinanceStatement", value: 1, color: "" },
            { text: "یادداشت همراه", enText: "Note", value: 2, color: "" }];
        var context = _h.kocnx();
        if (context.loginCompanyType() === 0) {
            this.templateTypes
                .push({
                    text: "حساب های متقابل",
                    enText: "BilateralAccounts",
                    value: 3, color: ""
                });
            this.templateTypes
                .push({
                    text: "گزارش ماتریسی",
                    enText: "MatrixReport",
                    value: 5, color: ""
                });
        }
        this.templateTypes
            .push({
                text: "محاسبات",
                enText: "TotalCost",
                value: 4, color: ""
            });
    }
    createForm() {
        const controls = [
            this.createLine({ t: 'tsp', val: this.priority, min: 1, max: this.editMode() === true ? this.lastPriority() : this.priority() },
                { t: 'txb', val: this.title }),
            this.createLine({ t: 'slc', val: this.templateTableType, options: this.templateTypes, dis: this.editMode },
                null, true, 30),

            this.createLine({ t: 'tsp', val: this.defaultRowNumber, min: 1, max: 100, dis: this.editMode },
                { t: 'tsp', val: this.defaultColumnNumber, min: 1, max: 100, dis: this.editMode }, true, 30),

            this.createLine({ t: 'tm', templateName: 'upload-tabletemplate-form-t' }, undefined, true, 30, 30),

            this.createLine({ t: 'slc', val: this.accountType, options: accountTypes },
                null, this.condFirst, 30),

            this.createLine({ t: 'slc', val: this.folderId, options: this.parentVM.folderList },
                null, true, 30)
        ];
        this.formControls(controls);
        this.formButtons({
            name: 'footer-form-t', data: {
                buttons: [
                    { name: 'create', vis: !this.editMode(), click: this.parentVM.create },
                    { name: 'edit', vis: this.editMode, click: this.parentVM.edit },
                    { name: 'cancel', click: _h.kocnx().closeForm }]
            }
        });
    }
}
export class TableTemplatePreviewDefault extends FormBuilder {
    constructor(viewModel, model) {
        super();
        this.parentVM = viewModel;
        this.showComparativePeriod = ko.observable(true);
        this.fillModel(model);
        this.createForm();
    }
    fillModel(model) {
        let paramList = [
            { name: "selectivePeriods", type: "obar" },
            { name: "caption", type: "ob", val: _h.getLocalizedText('previewDefaultCaption') },
            { name: "tableTemplateId", type: "ob", val: model.tableTemplateId },
            { name: "paperSize", type: "ob", val: model.paperSize },
            { name: "amountType", type: "ob", val: model.amountType },
            { name: "pageOrientation", type: "ob", val: model.pageOrientation },
            { name: "displayType", type: "ob", val: model.displayType },
            { name: "currentPeriodId", type: "ob", val: model.currentPeriodId },
            { name: "currentPeriodTitle", type: "ob", val: model.currentPeriodTitle }
        ];
        _autoMapper.createPropsFromList(this, paramList);
        if (_h.any(model.comparativePeriods))
            for (var i = 0; i < model.comparativePeriods.length; i++) {
                this[model.comparativePeriods[i].order + "ComparativePeriod"] = ko.observable(model.comparativePeriods[i].id);
            }


        for (var j = 0; j < model.selectivePeriods.length; j++) {
            this.selectivePeriods.push(new PeriodSelectItem(model.selectivePeriods[j]));
        }
    }
    getLastOrder() {
        var number = 0;
        for (const key of Object.keys(this)) {
            const char = key.slice(0, 2);
            var numb = char.match(/\d/g);
            if (numb && numb.length) {
                var number = parseFloat(char.replace(/[^0-9]/g, ''));
            }
        }
        return number;
    }
    getComparativePeriodsList() {
        var array = [];
        var order = this.getLastOrder();
        for (var f = 0; f < order; f++) {
            array.push({ order: f + 1, id: this[(f + 1) + "ComparativePeriod"]() });
        }
        return array;
    }
    toogleShowComparativeperiod() {
        if (this.showComparativePeriod()) {
            this.showComparativePeriod(false);
            $(".cp-box").css("display", "none");
        } else {
            this.showComparativePeriod(true);
            $(".cp-box").css("display", "block");
        }
    }
    createForm() {
        const controls = [
            this.createLine({ t: 'rdo', val: this.amountType, list: amountTypes, className: "radio-info" }, null, this.visFormControls, 0),
            this.createLine({ t: 'rdo', val: this.displayType, list: displayTypes2, className: "radio-info" }, null, this.visFormControls, 30),
            this.createLine({ t: 'rdo', val: this.pageOrientation, list: pageOrientations }, null, this.visFormControls, 30),
        ];
        controls.push(this.createLine({ t: 'tm', templateName: 'show-comparativeperiod-form-t' }, undefined, true, 30, 0));
        for (const key of Object.keys(this)) {
            const char = key.slice(0, 2);
            var numb = char.match(/\d/g);
            if (numb && numb.length) {
                controls.push(this.createLine({
                    t: 'slc', val: this[key],
                    options: this.selectivePeriods,
                    renderFunc: _h.periodSelectRowTemplate
                }, null, this[key]() > 0, 30, 0, "row cp-box"));
            }
        }
        this.formControls(controls);
        this.formButtons({
            name: 'footer-form-t', data: {
                buttons: [
                    { name: 'edit', vis: true, click: this.parentVM.savePreviewDefault },
                    { name: 'cancel', vis: true, click: this.parentVM.closePreviewForm }
                ]
            }
        });
        setTimeout(function () {
            this.toogleShowComparativeperiod();
        }.bind(this), 150)
    }
    toServer() {
        var list = this.getComparativePeriodsList();
        var model = {
            tableTemplateId: this.tableTemplateId(),
            amountType: this.amountType(),
            displayType: this.displayType(),
            pageOrientation: this.pageOrientation(),
            currentPeriodId: this.currentPeriodId(),
            comparativePeriods: list
        };

        return model;
    }
}

export function TreeInfoViewModel() {
    var self = this;
    self.treeId = ko.observable();
    self.periodId = ko.observable();
    self.treeName = ko.observable();
    self.nodeDisplayType = ko.observable(1);
    self.controllerName = 19;
    self.treeOpenBranches = [];
    self.treeSelectList = ko.observableArray();
    self.collectOpenBranches = function () {
        var tree = $("#tablestructure-tree-sec").find(".dmn-tree");
        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;
        return array;
    }
    self.getTreeName = function (id) {
        var name = "-";
        ko.utils.arrayFilter(self.treeSelectList(), function (item) {
            if (id === item.value)
                name = item.text;
        });
        return name;
    }
    self.treeSelectConfig = function (item) {
        var model = self.getTree(item.text);
        return '<div>' +
            '<span class="item-title">' +
            '<span class="item-name">' +
            item.text +
            '</span>' +
            '<span class="item-valueType">' +
            _h.getEnumText(valueTypes, model.valueType) +
            '</span>' +
            '</span>' +
            '<ul class="item-meta">' +
            '<li class="item-type">' +
            model.type +
            '</li></ul></div>';
    }
    self.getTree = function (text) {
        var name = "-";
        ko.utils.arrayFilter(self.treeSelectList(), function (item) {
            if (text === item.text)
                name = item;
        });
        return name;
    }
    self.onSelect = function (type, item) {
        switch (type) {
            case "treeId":
                if (item) {
                    if (_h.isNullOrEmpty(self.periodId()))
                        return;
                    var treeName = self.getTreeName(item.value);
                    self.treeName(treeName);
                    self.getRecords();
                } else {
                    $("#tree_view").treeView("removeTree");
                }
                self.treeOpenBranches = [];
                break;
            case "periodId":
                if (!item) {
                    self.treeId(null);
                    self.treeSelectList.removeAll();
                    $("#tree_view").treeView("removeTree");
                } else {
                    self.treeId(null);
                    $("#tree_view").treeView("removeTree");
                    self.getTreeSelectList();
                }
                break;
        }
    }
    self.getTreeSelectList = function (oldTreeId) {
        ApiService.request(
            {
                url: "/api/common/getgeneraltreelist",
                data: {
                    controllerName: 19,
                    period: self.periodId()
                },
                success: function (data) {
                    self.treeSelectList.removeAll();
                    if (_h.any(data))
                        for (var j = 0; j < data.length; j++) {
                            if (!_h.isNullOrEmpty(data[j])) {
                                var item = new TreeFormulaSelectItem(data[j]);
                                self.treeSelectList.push(item);
                            }
                        }
                    if (oldTreeId)
                        self.treeId(oldTreeId);
                    else
                        self.treeId(null);
                },
                error: function (data) {
                    var text = _h.getApiMessage("ErrorLoadTree");
                    _h.failToast(text);
                }
            });
    }
    ko.utils.extend(self, new BaseViewModel({
        entityName: "TreeInfo",
        getList: false,
        apiService: {
            actionList: []
        },
        buttons: [
            { name: 'refresh', access: false, cMenu: false },
            { name: 'tools', access: false, cMenu: false }
        ],
        filters: [
            { name: 'treeId' },
            { name: 'period' },
            { name: 'treeName' },
            { name: 'controllerName' }
        ],
        tableStyle: "font-size: 11px;",
        sortDirection: "Ascending",
        sortProperty: "code",
        context: self,
        cols: treeInfoModelRes,
        searchKeyType: "enter",
        selectRow: true,
        saveState: true,
        contextMenu: false,
        isMultiSelectRows: true
    }));
    self.btnVisibility = ko.computed(function () {
        self.visrefresh(true);
        self.vistools(true);
    });
    self.init = function (oldModel) {
        self.fillTableProperties();
        if (oldModel) {
            self.periodId(oldModel.periodId);
            self.treeOpenBranches = oldModel.treeOpenBranches;
            if (oldModel.nodeDisplayType)
                self.nodeDisplayType(oldModel.nodeDisplayType);
            self.getTreeSelectList(oldModel.treeId);
        }
        self.getRecords();
        self.iconSize("icon-image-small");
    }
    self.getRecords = function () {
        var filterModel = {
            id: self.treeId(),
            searchKey: self.searchKey(),
            controllerName: 19,
            period: self.periodId()
        };
        if (_h.isNullOrEmpty(filterModel.id))
            return;
        self.apiService.request({
            name: "getNodeSelection",
            data: filterModel,
            success: function (data) {
                if (_h.any(data)) {
                    self.records = data;
                }
                self.configTools();
                _h.fixLabelsSize();
            },
            error: function () {
                var text = _h.getApiMessage("ErrorLoadTree");
                _h.failToast(text);
            }
        });
    }
    self.expandAll = function () {
        $("#tree_view").treeView("expandAll");
    }
    self.collapseAll = function () {
        $("#tree_view").treeView("collapseAll");
    }
    self.configTools = function () {
        $("#tree_view").treeView({
            tType: self.entityName,
            location: self.entityName,
            nodes: self.records,
            rootId: self.treeId(),
            controllerName: 19,
            rootName: self.treeName(),
            periodId: self.periodId(),
            treeId: self.treeId(),
            nodeDisplayType: self.nodeDisplayType

        });
        if (self.treeOpenBranches && self.treeOpenBranches.length)
            $("#tree_view").treeView("expand", self.treeOpenBranches);
    }
}
export function TableInfoViewModel(parent) {
    var self = this;
    self.parent = parent;
    self.controllerName = 19;
    self.tableName = ko.observable();
    self.tableId = ko.observable();
    self.getTable = function (text) {
        var target;
        ko.utils.arrayFilter(self.tableSelectList(), function (item) {
            if (text === item.text)
                target = item;
        });
        return target;
    }
    self.getTableName = function (id) {
        var name = "-";
        ko.utils.arrayFilter(self.tableSelectList(), function (item) {
            if (id === item.value())
                name = item.text;
        });
        return name;
    }
    self.onSelect = function (type, item) {
        switch (type) {
            case "tableId":
                if (!_h.isNullOrEmpty(item.value)) {
                    var tableName = self.getTableName(item.value);
                    self.tableName(tableName);
                    self.getRecords();
                }
                if (_h.isNullOrEmpty(item.value)) {
                    self.tableName("");
                    self.records.removeAll();
                }
                break;
        }
    }
    self.tableSelectList = ko.observableArray();
    self.gettableSelectList = function (oldTableId) {
        ApiService.request(
            {
                url: "/api/common/gettablelist",
                data: {
                    controllerName: 19
                },
                success: function (data) {
                    self.tableSelectList.removeAll();
                    if (_h.any(data))
                        for (var j = 0; j < data.length; j++) {
                            data[j].id = data[j].value;
                            var item = new SelectItem(data[j]);
                            self.tableSelectList.push(item);
                        }
                    if (oldTableId)
                        self.tableId(oldTableId);
                    else
                        self.tableId(null);
                    self.onSelect("tableId", { value: oldTableId });
                },
                error: function (data) {

                }
            });
    }
    self.getRecords = function () {
        self.apiService.request({
            name: "/api/selectlist/gettablefields",
            data: { id: self.tableId() },
            success: function (data) {
                self.records.removeAll();
                if (_h.any(data)) {
                    for (var j = 0; j < data.length; j++) {
                        var target = data[j];
                        var record = new TableInfo(target);
                        self.records.push(record);
                    }
                }
                _h.fixLabelsSize();
            },
            error: function (message, level) {
            }
        });
    };
    ko.utils.extend(self, new BaseViewModel({
        entityName: "TableInfo",
        getList: false,
        apiService: {
            actionList: ["filterby"]
        },
        buttons: [
            { name: 'refresh', access: false, cMenu: false },
            { name: 'tools', access: false, cMenu: false }
        ],
        filters: [
            { name: 'tableId' },
            { name: 'tableName' },
            { name: 'controllerName' }
        ],
        tableStyle: "font-size: 11px;",
        sortDirection: "Ascending",
        sortProperty: "id",
        context: self,
        cols: tableModelRes,
        saveState: true,
        contextMenu: false
    }));
    self.btnVisibility = ko.computed(function () {
        self.visrefresh(true);
        self.vistools(true);
    });
    self.init = function (oldModel) {
        self.fillTableProperties();
        self.gettableSelectList(oldModel["tableId"]);
        self.iconSize("icon-image-small");
    }
    self.selectedRow = function (target, e, rightClick) {
        var ctrlSelect = e.ctrlKey;
        var shiftSelect = e.shiftKey;
        if (shiftSelect === undefined) shiftSelect = false;
        if (ctrlSelect === undefined) ctrlSelect = false;
        var res = self.isValidClickSingleRow(e);
        if (res !== "label") {
            self.changeSelectedRecord(target, ctrlSelect, shiftSelect, rightClick);
            self.fillChildModel(target);
        } else {
            self.changeSelectedRecord(target, ctrlSelect, shiftSelect, rightClick);
        }
    }
    self.changeSelectedRecord = function (target, ctrlSelect, shiftSelect, rightClick) {
        if (self.isMultiSelectRows && self.showType() !== "List") {
            if (shiftSelect) {
                if (self.extraBufferKey() === null || self.extraBufferKey() === undefined) {
                    self.extraBufferKey(target);
                    target.selected(true);
                } else {
                    var first, second, groupRoot, indexFirst, indexSecond, cr = false;
                    ;
                    if (self.groupProperty()) {
                        for (var i = 0; i < self.records().length; i++) {
                            var rec = self.records()[i];
                            for (var j = 0; j < rec.list().length; j++) {
                                var innerRec = rec.list()[j];
                                if (self.extraBufferKey().id() === innerRec.id()) {
                                    groupRoot = rec;
                                    indexFirst = rec.list().indexOf(self.extraBufferKey());
                                    indexSecond = rec.list().indexOf(target);
                                }
                            }
                        }
                        if (indexFirst === indexSecond)
                            return;
                        if (indexFirst > indexSecond) {
                            first = target;
                            second = self.extraBufferKey();
                        }
                        if (indexFirst < indexSecond) {
                            first = self.extraBufferKey();
                            second = target;
                        }

                        ko.utils.arrayFilter(groupRoot.list(),
                            function (rec) {
                                if (rec.id() === first.id())
                                    cr = true;
                                if (cr)
                                    rec.selected(true);
                                if (rec.id() === second.id())
                                    cr = false;
                            });
                    } else {
                        indexFirst = self.records().indexOf(self.extraBufferKey());
                        indexSecond = self.records().indexOf(target);
                        if (indexFirst === indexSecond) {
                            return;
                        }
                        if (indexFirst > indexSecond) {
                            first = target;
                            second = self.extraBufferKey();
                        }
                        if (indexFirst < indexSecond) {
                            first = self.extraBufferKey();
                            second = target;
                        }


                        ko.utils.arrayFilter(self.records(),
                            function (rec) {
                                if (rec.id() === first.id())
                                    cr = true;
                                if (cr)
                                    rec.selected(true);
                                if (rec.id() === second.id())
                                    cr = false;
                            });
                    }

                }
            } else {
                if (ctrlSelect) {
                    if (target.selected() === false)
                        self.extraBufferKey(target);
                    target.selected(!target.selected());
                } else {
                    if (rightClick) {
                        if (!target.selected()) {
                            self.extraBufferKey(target);
                            self.multiCommandExecute("toggle", false);
                            target.selected(true);
                        }
                        target.selected(true);
                    } else {
                        self.extraBufferKey(target);
                        self.multiCommandExecute("toggle", false);
                        if (self.configTable.isMultiSelectRows)
                            self.selectedRowRecord(target);
                        target.selected(true);
                    }
                }
            }
        } else {
            self.extraBufferKey(target);
            if (self.selectedRowRecord() !== null && self.selectedRowRecord() !== undefined)
                self.selectedRowRecord().selected(false);
            self.selectedRowRecord(target);
            target.selected(true);
        }
    }
    self.isValidClickSingleRow = function (e) {
        var tag;
        if (e.target === undefined)
            tag = e.tagName.toLowerCase();
        else
            tag = e.target.tagName.toLowerCase();
        switch (tag) {
            case "span":
            case "label":
                return "label";
            case "button":
            case "i":
            case "a":
            case "li":
                return false;
            default:
                return true;
        }
    }
}
export class TableInfo extends BaseInnerModel {
    constructor(model) {
        super(model);
        this.selected = ko.observable(false);
        this.selected.subscribe(function (newValue) {
            setTimeout(function () {
                var list = $("#dyn_col_list .table-row-selected");
                var dlist = $("#dyn_col_list tr:not(.table-row-selected)");
                var el;
                if (_h.any(list))
                    for (var i = 0; i < list.length; i++) {
                        el = list[i];
                        el.setAttribute("draggable", true);
                        el.addEventListener('dragstart',
                            function (event) {
                                var title = $(event.currentTarget).attr("data-title");
                                var id = $(event.currentTarget).attr("data-id");
                                var tableId = $(event.currentTarget).attr("data-table");
                                var div = document.getElementById('drag-label');
                                div.style.display = "block";
                                var span = div.getElementsByTagName("span")[0];
                                span.innerText = title;
                                event.dataTransfer.setData('application/json',
                                    JSON.stringify({
                                        action: "tableCol",
                                        model: {
                                            id: id,
                                            title: title,
                                            tableId: tableId
                                        }
                                    }));
                                event.dataTransfer.setDragImage(div, 60, 0);
                            });
                    }

                if (_h.any(dlist))
                    for (var j = 0; j < dlist.length; j++) {
                        var elem = dlist[j];
                        elem.setAttribute("draggable", false);
                    }
            },
                100);

        });
    }
}
export function CellBindForm() {
    var self = this;
    self.parent = null;
    self.gParent = null;
    self.id = null;
    self.selectedItem = ko.observable();
    self.cellBinds = ko.observableArray();
    self.addCellBindBtn = function () {
        if (!_h.isNullOrEmpty(self.selectedItem())) {
            if (!self.selectedItem().validationObject.isValid()) {
                self.selectedItem().validationObject.errors.showAllMessages();
                return false;
            }
            self.selectedItem().editMode(false);
        }
        var record = new CellBind(
            {title: "", firstCell: undefined, secondCell: undefined, deterrent: false, errorRate: undefined }, self, self.parent);
        record.editMode(true);
        self.cellBinds.unshift(record);
        self.selectedItem(record);
    };
    self.removeCellBindBtn = function (item) {
        self.cellBinds.remove(item);
        self.selectedItem(null);
    };
    self.closeMode = ko.observable(false);
    self.saveCellBindBtn = function () {
        if (!_h.isNullOrEmpty(self.selectedItem())) {
            if (!self.selectedItem().validationObject.isValid()) {
                self.selectedItem().validationObject.errors.showAllMessages();
                return false;
            }
        }
        if (_h.isNullOrEmpty(self.selectedItem().errorRate())
            || self.selectedItem().errorRate() === "") {
            self.selectedItem().errorRate(0);
        }

        self.closeMode(true);
        self.selectedItem().editMode(false);
        self.selectedItem(null);
        var list = [];
        if (self.cellBinds().length)
            for (var i = 0; i < self.cellBinds().length; i++) {
                var target = self.cellBinds()[i];
                if (target.validationObject.isValid()) {
                    var record = {title: target.title(), firstCell: target.firstCell(), secondCell: target.secondCell(), deterrent: target.deterrent(), errorRate: target.errorRate() };
                    list.push(record);
                }
            }
        $("#rg-" + self.id).rg("setCellBinds", list);


    }
    self.onRowClick = function (item) {
        if (item.editMode())
            return;

        if (self.closeMode()) {
            self.closeMode(false);
            return;
        }

        if (!_h.isNullOrEmpty(self.selectedItem())) {
            if (!self.selectedItem().validationObject.isValid()) {
                self.selectedItem().validationObject.errors.showAllMessages();
                return false;
            }
            self.selectedItem().editMode(false);
        }

        self.selectedItem(item);
        item.editMode(true);
    };
    self.init = function (model) {
        self.parent = model.parent;
        self.gParent = model.gParent;
        self.id = model.id;
        self.refresh(model.cellBinds);
    }
    self.refresh = function (cellBinds) {
        if (!cellBinds)
            cellBinds = $("#rg-" + self.id).rg("getCellBinds");

        self.cellBinds.removeAll();
        if (_h.any(cellBinds))
            for (var l = 0; l < cellBinds.length; l++) {
                var cellBind = new CellBind(cellBinds[l], self, self.parent);
                self.cellBinds.push(cellBind);
            }
    }
}
export function CellBind(model, parent, parentModel) {
    var self = this;
    self.parentForm = parent;
    self.parentModel = parentModel;
    self.editMode = ko.observable(false);
    self.title = ko.observable(model.title);
    self.firstCell = ko.observable(model.firstCell);
    self.secondCell = ko.observable(model.secondCell);
    self.deterrent = ko.observable(model.deterrent);
    self.errorRate = ko.observable(model.errorRate);
    self.addCell = function (address) {
        if (self.activeCell() === 1)
            self.firstCell(address);
        else
            self.secondCell(address);
    }
    self.firstCellKeyDown = function (data, event) {
        var cols = self.parentModel.cols;
        var rows = self.parentModel.rows;
        var val = self.firstCell();
        var number, letter;
        if ((event.keyCode >= 96 && event.keyCode <= 105) ||
            (event.keyCode >= 48 && event.keyCode <= 57)) {
            if (!_h.isNullOrEmpty(val) && val !== "") {
                number = self.firstCell().replace(/^\D+/g, '');
                letter = self.firstCell().replace(number, '');
                if (_h.isEmpty(number)) {
                    if (Number(number) + Number(event.key) <= rows)
                        self.firstCell(self.firstCell() + event.key);
                } else {
                    if (Number(number) + Number(event.key) <= rows)
                        self.firstCell(self.firstCell() + event.key);
                }
            }

        } else if (event.keyCode >= 65 && event.keyCode <= 90) {
            if (_h.isNullOrEmpty(val) || val === "") {
                if (_h.alphabetToNumber(event.key.toUpperCase()) <= cols)
                    self.firstCell(self.firstCell() + event.key.toUpperCase());
            } else {
                number = self.firstCell().replace(/^\D+/g, '');
                letter = self.firstCell().replace(number, '');
                if (_h.isEmpty(number)) {
                    if (_h.alphabetToNumber(letter + event.key) <= cols)
                        self.firstCell(self.firstCell() + event.key.toUpperCase());
                }
            }


        } else {
            if (event.keyCode === 35 || event.keyCode === 8)
                return true;

        }
    }
    self.secondCellKeyDown = function (data, event) {
        var cols = self.parentModel.cols;
        var rows = self.parentModel.rows;
        var val = self.secondCell();
        var number, letter;
        if ((event.keyCode >= 96 && event.keyCode <= 105) ||
            (event.keyCode >= 48 && event.keyCode <= 57)) {
            if (!_h.isNullOrEmpty(val) && val !== "") {
                number = self.secondCell().replace(/^\D+/g, '');
                if (_h.isEmpty(number)) {
                    if (Number(number) + Number(event.key) <= rows)
                        self.secondCell(self.secondCell() + event.key);
                } else {
                    if (Number(number) + Number(event.key) <= rows)
                        self.secondCell(self.secondCell() + event.key);
                }
            }
        } else if (event.keyCode >= 65 && event.keyCode <= 90) {
            if (_h.isNullOrEmpty(val) || val === "") {
                if (_h.alphabetToNumber(event.key.toUpperCase()) <= cols)
                    self.secondCell(self.secondCell() + event.key.toUpperCase());
            } else {
                number = self.secondCell().replace(/^\D+/g, '');
                letter = self.secondCell().replace(number, '');
                if (_h.isEmpty(number)) {
                    if (_h.alphabetToNumber(letter + event.key) <= cols)
                        self.secondCell(self.secondCell() + event.key.toUpperCase());
                }
            }
        } else {
            if (event.keyCode === 35 || event.keyCode === 8)
                return true;
        }
    }
    self.validationObject = ko.validatedObservable({
        title: self.title.extend({
            required: true
        }),
        firstCell: self.firstCell.extend({
            required: true,
            englishOnly: true,
            chkStringTypeCell: [self.parentForm],
            duplicateCell: [self.parentForm],
            compareSameCell: [self.parentForm, self.secondCell]
        }),
        secondCell: self.secondCell.extend({
            required: true,
            englishOnly: true,
            chkStringTypeCell: [self.parentForm],
            duplicateCell: [self.parentForm],
            compareSameCell: [self.parentForm, self.firstCell]
        }),
        errorRate: self.errorRate.extend({
            chkErrorRate: true,
            chkPercentRate: true
        })
    })
    self.toggleDeterrent = function () {
        self.deterrent(!self.deterrent());
    }
}
export function CellSelectForm() {
    var self = this;
    self.templateName = ko.observable();
    self.caption = ko.observable("اتصال به قالب جداول دیگر");
    self.dataModel = ko.observable();
    self.tableTemplateId = ko.observable();
    self.tableTemplateListFiltered = ko.observableArray();
    self.getTemplateName = function (id) {
        var name = "-";
        var context = _h.kocnx();
        for (var j = 0; j < context.ttvm().tableTemplateList().length; j++) {
            var target = context.ttvm().tableTemplateList()[j];
            if (id === target.value())
                name = target.text();
        }
        return name;
    }
    self.filterList = function () {
        var context = _h.kocnx();
        var designItem = context.ttvm().findFocusDesignItem();
        self.tableTemplateListFiltered.removeAll();
        if (_h.any(context.ttvm().tableTemplateList()))
            for (var j = 0; j < context.ttvm().tableTemplateList().length; j++) {
                var target = context.ttvm().tableTemplateList()[j];
                if (designItem.value() !== target.value()) {
                    switch (target.tableTemplateType()) {
                        case 3:
                            if (designItem.type() === 3)
                                self.tableTemplateListFiltered.push(target);
                            break;
                        case 5:
                        case 1:
                        case 2:
                            if (designItem.type() === 1 ||
                                designItem.type() === 2 ||
                                designItem.type() === 5)
                                self.tableTemplateListFiltered.push(target);
                            break;
                    }
                }
            }
    }
    self.onSelect = function (type, item) {
        switch (type) {
            case "tableTemplateId":
                if (item && item.value) {
                    var name = self.getTemplateName(item.value);
                    self.templateName(name);
                }

                if (!item) {
                    self.templateName("");
                }
                break;
        }
    }
    self.init = function (oldModel) {
        self.tableTemplateId(oldModel.tableTemplateId);

    }
}
export function CellSpecMenu() {
    var self = this;
    self.parent = ko.observable();
    self.caption = ko.observable();
    self.show = ko.observable(false);
    self.nodeCount = ko.observable(0);
    self.tableTemplateType = ko.observable();
    self.cellAddress = "";
    self.cellCount = "";
    self.viewType = ko.observable();
    self.xbrlConcept = ko.observable();
    self.decimalPlaces = ko.observable();
    self.dataType = ko.observable();
    self.accountType = ko.observable();
    self.valueSource = ko.observable();
    self.groupType = ko.observable();
    self.valueAccountType = ko.observable();
    self.sortDirection = ko.observable();
    self.negativeInParentheses = ko.observable(false);
    self.negativeRedNumber = ko.observable(false);
    self.zeroDisplay = ko.observable(1);
    self.percent = ko.observable(false);
    self.valueDisplay = ko.observable(false);
    self.financialPeriod = ko.observable();
    self.roundingApproach = ko.observable(1);
    self.applyToTable = function (dataType, newValue) {
        var record = self.parent().getFocusDesignRecord();
        $("#rg-" + record.id).find(".rp-gen").rg("command",
            { viewType: self.viewType(), value: newValue, id: dataType });
        _h.kocnx().ttvm().focusDesignItem().refreshToolBar(true);
    }
    self.roundingApproachsub = self.roundingApproach.supsendableSubscribe(function (newValue) {
        self.applyToTable("roundingApproach", newValue);
    });
    self.valueAccountTypesub = self.valueAccountType.supsendableSubscribe(function (newValue) {
        self.applyToTable("valueAccountType", newValue);
    });
    self.valueSourcesub = self.valueSource.supsendableSubscribe(function (newValue) {
        self.applyToTable("valueSource", newValue);
    });
    self.decimalPlacessub = self.decimalPlaces.supsendableSubscribe(function (newValue) {
        self.applyToTable("decimals", newValue);
    });
    self.dataTypesub = self.dataType.supsendableSubscribe(function (newValue) {
        self.applyToTable("dataType", newValue);
    });
    self.accountTypesub = self.accountType.supsendableSubscribe(function (newValue) {
        self.applyToTable("accountType", newValue);
    });
    self.financialPeriodsub = self.financialPeriod.supsendableSubscribe(function (newValue) {
        self.applyToTable("financialPeriod", newValue);
    });
    self.negativeInParenthesessub = self.negativeInParentheses.supsendableSubscribe(function (newValue) {
        self.applyToTable("minusParenthese", newValue);
    });
    self.negativeRedNumbersub = self.negativeRedNumber.supsendableSubscribe(function (newValue) {
        self.applyToTable("minusRedText", newValue);
    });
    self.percentsub = self.percent.supsendableSubscribe(function (newValue) {
        self.applyToTable("percent", newValue);
    });
    self.valueDisplaysub = self.valueDisplay.supsendableSubscribe(function (newValue) {
        self.applyToTable("valueDisplay", newValue);
    });
    self.groupTypesub = self.groupType.supsendableSubscribe(function (newValue) {
        self.applyToTable("groupType", newValue);
    });
    self.sortDirectionsub = self.sortDirection.supsendableSubscribe(function (newValue) {
        self.applyToTable("sortDirection", newValue);
    });
    self.zeroDisplaysub = self.zeroDisplay.supsendableSubscribe(function (newValue) {
        self.applyToTable("zeroDisplay", newValue);
    });
    self.sizeClass = ko.observable("col-lg-2 floating-menu");
    self.toggleNegativeInParentheses = function () {
        self.negativeInParentheses(!self.negativeInParentheses());
    }
    self.toggleNegativeRedNumber = function () {
        self.negativeRedNumber(!self.negativeRedNumber());
    }
    self.togglePercent = function () {
        self.percent(!self.percent());
    }
    self.toggleXbrlConcept = function () {
        self.applyToTable("xbrlConcept", false);
    }
    self.init = function (option) {
        self.show(true);
        self.viewType(option.viewType);
        self.parent(option.parent);
        self.tableTemplateType(option.templateTableType);
        self.nodeCount(option.nodeCount);
        var cell = option.cell;
        switch (option.viewType) {
            case "cell":
                self.caption("خصوصیات سلول");
                self.sizeClass("col-lg-3 floating-menu cell-spec-menu");
                self.toggleSuspendPageControls(true);
                self.decimalPlaces(cell.extraParams.decimals);
                self.dataType(cell.extraParams.dataType);
                self.accountType(cell.extraParams.accountType);
                self.financialPeriod(cell.extraParams.financialPeriod);
                self.negativeInParentheses(cell.extraParams.minusParenthese);
                self.zeroDisplay(cell.extraParams.zeroDisplay);
                self.negativeRedNumber(cell.extraParams.minusRedText);
                self.percent(cell.extraParams.percent);
                self.valueDisplay(cell.extraParams.valueDisplay);
                self.valueSource(cell.extraParams.valueSource);
                self.valueAccountType(cell.extraParams.valueAccountType);
                self.roundingApproach(cell.extraParams.roundingApproach);
                if (cell.xbrlConcept)
                    self.xbrlConcept(cell.xbrlConcept.title);
                self.sortDirection(option.sortDirection);
                self.groupType(option.groupType);
                self.toggleSuspendPageControls(false);
                self.cellAddress = cell.cellAddress;
                break;
            case "cells":
                self.sizeClass("col-lg-3 floating-menu cell-spec-menu");
                self.caption("خصوصیات سلول ها");
                self.toggleSuspendPageControls(true);
                self.financialPeriod(0);
                self.roundingApproach(1);
                self.decimalPlaces(0);
                self.accountType(null);
                self.valueSource(null);
                self.valueAccountType(0);
                self.dataType(null);
                self.cellCount = "";
                self.negativeInParentheses(false);
                self.zeroDisplay(null);
                self.negativeRedNumber(false);
                self.percent(false);
                self.valueDisplay(undefined);
                self.toggleSuspendPageControls(false);
                break;
        }

        self.toggleHeightMenu(option);
        $(".cell-spec-menu").draggable({
            scroll: true,
            handle: ".cellspec-drag-handle"
        });
    }
    self.toggleHeightMenu = function (option) {
        if (option.target)
            $(".floating-menu").position({
                my: 'center top',
                at: 'center bottom',
                of: $(option.target),
                offset: '0 5',
                collision: 'fit'
            });
    }
    self.toggleSuspendPageControls = function (sta) {
        if (sta) {
            self.negativeInParenthesessub.suspend();
            self.zeroDisplaysub.suspend();
            self.negativeRedNumbersub.suspend();
            self.percentsub.suspend();
            self.valueDisplaysub.suspend();
            self.financialPeriodsub.suspend();
            self.accountTypesub.suspend();
            self.dataTypesub.suspend();
            self.decimalPlacessub.suspend();
            self.valueSourcesub.suspend();
            self.valueAccountTypesub.suspend();
            self.groupTypesub.suspend();
            self.sortDirectionsub.suspend();
            self.roundingApproachsub.suspend();
        } else {
            self.negativeInParenthesessub.unsuspend();
            self.zeroDisplaysub.unsuspend();
            self.negativeRedNumbersub.unsuspend();
            self.percentsub.unsuspend();
            self.valueDisplaysub.unsuspend();
            self.financialPeriodsub.unsuspend();
            self.accountTypesub.unsuspend();
            self.dataTypesub.unsuspend();
            self.decimalPlacessub.unsuspend();
            self.valueSourcesub.unsuspend();
            self.valueAccountTypesub.unsuspend();
            self.groupTypesub.unsuspend();
            self.sortDirectionsub.unsuspend();
            self.roundingApproachsub.unsuspend();
        }
    }
    self.hide = function () {
        self.show(false);
    }
}
export function ContextMenu() {
    var self = this;
    self.show = ko.observable(false);
    self.parent = ko.observable();
    self.element = null;
    self.caption = ko.observable();
    self.textWrap = ko.observable(false);
    self.viewType = ko.observable();
    self.sortDirection = ko.observable();
    self.regions = ko.observableArray();
    self.width = ko.observable().extend({ formatSize: { min: 5, max: 1000 } });
    self.height = ko.observable().extend({ formatSize: { min: 5, max: 200 } });
    self.applyToTable = function (dataType, newValue, colNumber, rowNumber) {
        self.parent().scope.find(".rp-gen").rg("command",
            { viewType: self.viewType(), value: newValue, id: dataType, colNumber: colNumber, rowNumber: rowNumber });
        _h.kocnx().ttvm().focusDesignItem().refreshToolBar(true);
    }
    self.textWrapsub = self.textWrap.supsendableSubscribe(function (newValue) {
        self.applyToTable("textWrap", newValue, self.colNumber, undefined);
    });
    self.heightsub = self.height.supsendableSubscribe(function (newValue) {
        self.applyToTable("height", newValue, undefined, self.rowNumber);
    });
    self.widthsub = self.width.supsendableSubscribe(function (newValue) {
        self.applyToTable("width", newValue, self.colNumber, undefined);
    });
    self.sortDirectionsub = self.sortDirection.supsendableSubscribe(function (newValue) {
        self.applyToTable("colSortDirection", newValue, self.colNumber);
    });
    self.addRegion = function () {
        self.regions.push(new CellRegion({}, self));
    }
    self.removeRegion = function (item) {
        self.regions.remove(item);
        self.subscribeRegions();
    }
    self.subscribeRegions = function (data) {
        var array = [];
        for (var i = 0; i < self.regions().length; i++) {
            var start = self.regions()[i].start() ? Number(self.regions()[i].start()) : undefined;
            var end = self.regions()[i].end() ? Number(self.regions()[i].end()) : undefined;
            array.push({ start: start, end: end });
        }
        var filtered = array.filter(a => !_h.isEmpty(a.start) && !_h.isEmpty(a.end));
        self.applyToTable("region", filtered, self.colNumber, undefined);
    }
    self.init = function (option) {
        self.show(true);
        self.viewType(option.viewType);
        self.parent(option.parent);
        self.element = option.element;
        self.colNumber = option.colNumber;
        self.rowNumber = option.rowNumber;

        switch (option.viewType) {
            case "col":
                self.caption("تنظیمات ستون");
                self.toggleSuspendPageControls(true);
                self.textWrap(option.textWrap);
                self.width(option.width);
                self.sortDirection(option.sortDirection);
                self.regions.removeAll();
                if (_h.any(option.regions))
                    for (var i = 0; i < option.regions.length; i++) {
                        var rec = new CellRegion(option.regions[i], self);
                        self.regions.push(rec);
                    }
                self.toggleSuspendPageControls(false);
                break;
            case "row":
                self.caption("تنظیمات سطر");
                self.toggleSuspendPageControls(true);
                self.height(option.height);
                self.toggleSuspendPageControls(false);
                break;
            case "cross":
                self.caption("تنظیمات سطر و ستون");
                self.toggleSuspendPageControls(true);
                self.width(option.width);
                self.height(option.height);
                self.toggleSuspendPageControls(false);
                break;
        }

        self.toggleHeightMenu(option);
    };
    self.toggleTextWrap = function () {
        self.textWrap(!self.textWrap());
    }
    self.toggleHeightMenu = function (option) {
        $(".rg-cotext-menu").position({
            my: 'center top',
            at: 'center bottom',
            of: $(option.element),
            offset: '0 5',
            collision: 'fit'
        });
    }
    self.toggleSuspendPageControls = function (sta) {
        if (sta) {
            self.widthsub.suspend();
            self.textWrapsub.suspend();
            self.heightsub.suspend();
            self.sortDirectionsub.suspend();
        } else {
            self.heightsub.unsuspend();
            self.textWrapsub.unsuspend();
            self.widthsub.unsuspend();
            self.sortDirectionsub.unsuspend();
        }
    }
}
export function NodeValue(model, parent, pageNumber) {
    var self = this;
    self.parent = parent;
    self.pageNumber = pageNumber;
    self.isDisabled = ko.observable(false);
    self.code = model.code;
    self.title = model.title;
    self.type = model.type;
    self.operator = ko.observable(model.operator);
    self.operator.subscribe(function (value) {
        if (!_h.isEmpty(value))
            self.parent.changeOperator();
    });
}
export function InfoDropDown(parent) {
    var self = this;
    self.show = ko.observable(false);
    self.list = ko.observableArray();
    self.parentForm = parent;
    self.init = function () {
        self.pageNumber(1);
        self.pageNumberStr(1);
        self.showPaggingMenu(false);
        self.total(0);
        self.pageNumbers([]);
        var list = self.parentForm.scope.find(".rp-gen").rg("getCellValues");
        var pagenumber = 1;
        self.total(list.length);

        if (list && list.length)
            for (var i = 0; i < list.length; i++) {
                var div = (i + 1) / 12;
                if (div > pagenumber)
                    pagenumber = pagenumber + 1;
                var item = new NodeValue(list[i], self, pagenumber);
                self.list.push(item);
            }
        self.show(true);
        self.operatorConfig();
    }
    self.refresh = function () {
        self.show(false);
        self.list.removeAll();
        self.pageNumber(1);
        self.pageNumberStr(1);
        self.showPaggingMenu(false);
        self.total(0);
        self.pageNumbers([]);
        var list = self.parentForm.scope.find(".rp-gen").rg("getCellValues");
        var pagenumber = 1;
        self.total(list.length);
        for (var i = 0; i < list.length; i++) {
            var div = (i + 1) / 12;
            if (div > pagenumber)
                pagenumber = pagenumber + 1;
            var item = new NodeValue(list[i], self, pagenumber);
            self.list.push(item);
        }
        self.show(true);
        self.operatorConfig();
    }
    self.terminate = function () {
        self.show(false);
        self.list.removeAll();
    }
    self.removeItem = function (item) {
        self.list.remove(item);
        var list = self.prepareList();
        var cell = self.parentForm.scope.find(".rp-gen").rg("setFormula", { id: "NodeInCell", value: list });
        if (cell)
            self.parentForm.scope.find(".txtFormula").val(cell.value);
        else
            self.parentForm.scope.find(".txtFormula").val("");
        if (self.list().length === 0)
            self.show(false);
        self.operatorConfig();
    }
    self.operatorConfig = function () {
        if (self.list().length === 0)
            return;
        if (self.list().length === 1)
            self.list()[0].isDisabled(true);
        else
            self.list()[self.list().length - 1].isDisabled(true);
    }
    self.changeOperator = function (item) {
        var list = self.prepareList();
        var cell = self.parentForm.scope.find(".rp-gen").rg("setFormula", { id: "NodeInCell", value: list });
        self.parentForm.scope.find(".txtFormula").val(cell.value);
    }
    self.prepareList = function () {
        var array = [];
        if (_h.any(self.list()))
            for (var i = 0; i < self.list().length; i++) {
                array.push({
                    code: self.list()[i].code,
                    title: self.list()[i].title,
                    type: self.list()[i].type,
                    operator: self.list()[i].operator(),

                });
            }
        return array;
    }
    self.pageNumbers = ko.observableArray([]);
    self.pageSize = ko.observable(12);
    self.pageNumber = ko.observable(1);
    self.pageNumberStr = ko.observable(1);
    self.showPaggingMenu = ko.observable(false);
    self.total = ko.observable(0);
    self.forward = function () {
        self.pageNumber(self.pageNumber() + 1);
    }
    self.backward = function () {
        if (self.pageNumber() > 1) {
            self.pageNumber(self.pageNumber() - 1);
        }
    }
    self.paggingMenu = ko.computed(function () {
        self.pageNumberStr(self.pageNumber());
        var pageCount = parseInt(self.total() / self.pageSize());
        if (self.total() % self.pageSize() !== 0) {
            pageCount += 1;
        }
        self.pageNumbers.removeAll();
        var isActive;
        if (pageCount < 2) {
            self.showPaggingMenu(false);
        } else if (pageCount < 100) {
            for (var i = 0; i < pageCount; i++) {
                isActive = self.pageNumber() === i + 1;
                self.pageNumbers.push({ name: i + 1, active: ko.observable(isActive) });
            }
            self.showPaggingMenu(true);
        } else if (pageCount > 100) {
            self.pageNumbers.push({ name: pageCount - 2, active: ko.observable(self.pageNumber() === pageCount - 2) });
            self.pageNumbers.push({ name: pageCount - 1, active: ko.observable(self.pageNumber() === pageCount - 1) });
            self.pageNumbers.push({ name: pageCount, active: ko.observable(self.pageNumber() === pageCount) });
            self.showPaggingMenu(true);
        }

    });
    self.paggingMenuItemClick = function (item) {
        self.pageNumber(item.name);
        return false;
    };
    self.onClickPageNumberStr = function (d, e) {
        var number = Number(self.pageNumberStr());
        var pageCount = parseInt(self.total() / self.pageSize());
        if (self.total() % self.pageSize() !== 0) {
            pageCount += 1;
        }

        var res = false;
        if (!_h.isNullOrEmpty(number) && number <= pageCount) {
            self.pageNumber(number);
            res = true;
        }
        if (res && self.pageNumbers().length) {
            for (var i = 0; i < self.pageNumbers().length; i++) {
                if (self.pageNumbers()[i].name === number)
                    self.pageNumbers()[i].active(true);
                else
                    self.pageNumbers()[i].active(false);
            }
        }
    };
}
export function RpSetting() {
    var self = this;
    self.autoSave = ko.observable(0);
    self.setItems = function () {
        clientStorage.setSetting({ key: "RepGenAutoSave", value: self.autoSave() });
        if (!_h.isEmpty(autoSave) && autoSave !== "null" && autoSave !== "0" && autoSave !== 0) {
            var time = Number(autoSave) * 1000;
            self.removeTimers();
            self.initTimers(time);

        } else {
            self.removeTimers();
        }
    };
    self.saveinterval = null;
    self.init = function () {
        var autoSave = clientStorage.getSetting("RepGenAutoSave");
        if (!_h.isEmpty(autoSave) && autoSave !== "null" && autoSave !== "0" && autoSave !== 0) {
            self.autoSave(Number(autoSave));
            var time = Number(autoSave) * 1000;
            self.initTimers(time);
        }
    };
    self.initTimers = function (time) {
        self.saveinterval = setInterval(function () {
            var record = _h.kocnx().ttvm().getFocusDesignRecord();
            if (record) {
                var arrayData = $("#rg-" + record.id).find(".rp-gen").rg("toServer");
                var model = arrayData[0];
                _h.kocnx().ttvm().saveChanges(model, function (dataRes) {
                    if (dataRes !== false) {
                        if (_h.any(dataRes.bindErrors))
                            $("#rg-" + record.id).find(".rp-gen").rg("setWarning", dataRes.bindErrors);
                        if (_h.any(dataRes.cellsTag))
                            $("#rg-" + record.id).find(".rp-gen").rg("refreshCellsTag", dataRes.cellsTag);
                    }
                });
            }
        }, time);
    }
    self.removeTimers = function () {
        if (!_h.isNullOrEmpty(self.saveinterval)) {
            clearInterval(self.saveinterval);
            self.saveinterval = null;
        }
    };
}
export class CustomStyleCategory extends BaseInnerModel {
    constructor(model) {
        super(model);
        this.isCustom = ko.observable(false);
        this.styles = ko.observableArray(model.styles);
    }
}
export class CustomStyle extends BaseInfoModel {
    constructor(model) {
        super(model);
        this.showPanel = ko.observable(false);
    }

    togglePanel() {
        this.showPanel(!this.showPanel());
    }
}
export class CustomStyleForm extends BaseSecondaryForm {
    constructor(viewModel, model) {
        super(viewModel, [
            { name: "backColor", type: "ob" },
            { name: "textColor", type: "ob" },
            { name: "titleStyle", type: "ob" },
            { name: "textAlign", type: "", val: model.textAlign },
            { name: "textBold", type: "", val: model.textBold },
            { name: "textItalic", type: "", val: model.textItalic },
            { name: "textUnderline", type: "", val: model.textUnderline },
            { name: "textFontFamily", type: "", val: model.textFontFamily },
            { name: "textFontSize", type: "", val: model.textFontSize },
            { name: "textWrap", type: "", val: model.textWrap },
            { name: "borderStyle", type: "", val: model.borderStyle },
            { name: "borderWidth", type: "", val: model.borderWidth },
            { name: "borderColor", type: "", val: model.borderColor }
        ], "CustomStyleCaption");
        if (!_h.isEmpty(model.backColor)) {
            var backColor = _h.toHex3(model.backColor);
            this.backColor(backColor);
        }
        if (!_h.isEmpty(model.textColor)) {
            var textColor = _h.toHex3(model.textColor);
            this.textColor(textColor);
        }
        this.setValidationObject();
        this.createForm();
    }

    setValidationObject() {
        this.validationObject = ko.validatedObservable({
            titleStyle: this.titleStyle.extend({
                required: true,
                minLength: 3,
                maxLength: 20
            })
        });
    }

    toServer() {
        return {
            id: _h.generateUuid(),
            backColor: this.backColor(),
            borderColor: this.borderColor,
            borderStyle: this.borderStyle,
            borderColor: this.borderColor,
            borderWidth: this.borderWidth,
            textAlign: this.textAlign,
            textBold: this.textBold,
            textColor: this.textColor(),
            textFontFamily: this.textFontFamily,
            textFontSize: this.textFontSize,
            textItalic: this.textItalic,
            textUnderline: this.textUnderline,
            textWrap: this.textWrap,
            title: this.titleStyle()
        };
    }

    createForm() {
        const controls = [
            this.createLine({ t: 'txb', val: this.titleStyle }, null, true, 30),
        ];
        this.formControls(controls);
        this.formButtons({
            name: 'footer-form-t', data: {
                buttons: [
                    { name: "custom", resText: 'createFormBtn', vis: true, click: this.parentVM.addCustomStyle },
                    { name: 'cancel', click: _h.kocnx().closeForm }]
            }
        });
    }
}
export function CustomStyleMenu() {
    var self = this;
    self.show = ko.observable(false);
    self.caption = ko.observable(false);
    self.cellStyles = ko.observableArray();
    self.fillCellStyle = function (id) {
        var cellStyles = [
            {
                category: "مالی و پولی",
                styles: [
                    {
                        id: -1,
                        title: "جمع میانی 1",
                        textColor: "",
                        backColor: "#ffb886",
                        textAlign: "",
                        textBold: true,
                        textItalic: false,
                        textUnderline: false,
                        textFontFamily: "",
                        textFontSize: "",
                        borderStyle: "solid none solid none",
                        borderWidth: "1px 0px 1px 0px",
                        borderColor: "#ff842d #ffffff #ff842d #ffffff"
                    },
                    {
                        id: -1,
                        title: "جمع میانی 2",
                        textColor: "",
                        backColor: "#ffffff",
                        textAlign: "",
                        textBold: true,
                        textItalic: false,
                        textUnderline: false,
                        textFontFamily: "",
                        textFontSize: "",
                        borderStyle: "solid none solid none",
                        borderWidth: "1px 0px 1px 0px",
                        borderColor: "#000000 #ffffff #000000 #ffffff"
                    },
                    {
                        id: -1,
                        title: "جمع نهایی 1",
                        textColor: "",
                        backColor: "#ffb886",
                        textBold: true,
                        textItalic: false,
                        textUnderline: false,
                        textFontFamily: "",
                        textFontSize: "",
                        borderStyle: "solid none double none",
                        borderWidth: "1px 4px 3px 4px",
                        borderColor: "#ff842d #ffffff #ff842d #ffffff"
                    },
                    {
                        id: -1,
                        title: "جمع نهایی 2",
                        textColor: "",
                        backColor: "#ffffff",
                        textBold: true,
                        textItalic: false,
                        textUnderline: false,
                        textFontFamily: "",
                        textFontSize: "",
                        borderStyle: "solid none double none",
                        borderWidth: "1px 4px 3px 4px",
                        borderColor: "#000000 #ffffff #000000 #ffffff"
                    }
                ]
            },
            {
                category: "سرتیتر و عنوان",
                styles: [
                    {
                        id: -1,
                        title: "ستون عنوان",
                        textColor: "",
                        backColor: "#cecece",
                        textAlign: "center",
                        textBold: false,
                        textItalic: false,
                        textUnderline: false,
                        textFontFamily: "",
                        textFontSize: "",
                        borderStyle: "solid solid solid solid",
                        borderWidth: "1px 4px 1px 4px",
                        borderColor: "#ffffff #ffffff #808080 #ffffff"
                    }
                ]
            }
        ];
        self.cellStyles.removeAll();
        for (var i = 0; i < cellStyles.length; i++) {
            var target = cellStyles[i];
            var record = new CustomStyleCategory(target);
            self.cellStyles.push(record);
        }
        var customStyles = new CustomStyleCategory({ category: "استایل سفارشی" });
        customStyles.isCustom(true);
        var list = clientStorage.getSetting("CustomStyles");
        if (list) {
            if (_h.any(list))
                for (var j = 0; j < list.length; j++) {
                    var rec = new CustomStyle(list[j]);
                    if (!id || id !== list[j].id)
                        customStyles.styles.push(rec);
                }
        }
        self.cellStyles.push(customStyles);
    }
    self.addCustomStyleBtn = function () {
        var record = _h.kocnx().ttvm().getFocusDesignRecord();

        self.selectedCells = $("#rg-" + record.id).find(".rp-gen").rg("getSelectedCells");
        if (self.selectedCells.length === 1) {
            _h.kocnx()
                .openForm(new CustomStyleForm(self, self.selectedCells[0].style));
        }
    }
    self.addCustomStyle = function (parents, btnModel, e) {
        var item = parents[1];
        if (!item.validationObject.isValid()) {
            item.validationObject.errors.showAllMessages();
            return false;
        }
        var model = item.toServer();
        var customStyles;
        for (var i = 0; i < self.cellStyles().length; i++) {
            var item = self.cellStyles()[i];
            if (item.isCustom()) {
                customStyles = item;
            }
        }
        if (customStyles) {
            var rec = new CustomStyle(model);
            customStyles.styles.push(rec);
        }
        _h.kocnx().closeForm();
        self.changeList();
    }
    self.deleteCustomStyle = function (item) {
        var confirmText = toast.createMessage("CustomStyle", 'del', null, 'confirm');
        _h.confirmDeleteAlert(confirmText,
            function (res) {
                if (res) {
                    self.fillCellStyle(item.id);
                    self.changeList();
                }
            });
    }
    self.changeList = function () {
        var list = [], customStyles;
        for (var i = 0; i < self.cellStyles().length; i++) {
            var item = self.cellStyles()[i];
            if (item.isCustom()) {
                customStyles = item;
            }
        }
        list = ko.toJS(customStyles.styles());
        clientStorage.setSetting([{ key: "CustomStyles", value: list }]);
    }
    self.applyCustomStyle = function (parent, command, model) {
        var record = _h.kocnx().ttvm().getFocusDesignRecord();
        $("#rg-" + record.id).find(".rp-gen").rg("command", { id: "cellStyle", value: model });
        _h.kocnx().ttvm().focusDesignItem().refreshToolBar(true);
        _h.kocnx().ttvm().focusDesignItem().refreshToolBar(false);
    }
}
export function RgMenu(parent) {
    var self = this;
    self.parentModel = parent;
    self.treeDataSource = ko.observable(new TreeInfoViewModel());
    self.tableDataSource = ko.observable(new TableInfoViewModel(self));
    self.cellSelectModel = ko.observable(new CellSelectForm());
    self.xbrlConceptModel = ko.observable(new XbrlConceptViewModel());
    self.showTableDataSource = ko.observable(false);
    self.showTreeDataSource = ko.observable(false);
    self.showXbrlConcept = ko.observable(false);
    self.showPreview = ko.observable(false);
    self.showConsolidate = ko.observable(false);
    self.showCompare = ko.observable(false);
    self.showCellSelect = ko.observable(false);
    self.showInfo = ko.observable(false);
    self.childInfoModel = ko.observable();
    self.compareCellModel = ko.observable();
    self.companySelectList = ko.observableArray();
    self.companiesFiltered = ko.observableArray();
    self.companySearchKey = ko.observable();
    self.companySearchKey.subscribe(function (value) {
        if (_h.isEmpty(value)) {
            //var allCompanies = ko.toJS(self.companySelectList());
            self.companiesFiltered(self.companySelectList().slice());
        } else {
            self.companiesFiltered.removeAll();
            for (var i = 0; i < self.companySelectList().length; i++) {
                var isValueMultiPart = value.indexOf(" ") !== -1;
                if (!isValueMultiPart) {
                    if (self.checkWordInCompanies(self.companySelectList()[i], value))
                        self.companiesFiltered.push(self.companySelectList()[i]);
                } else {
                    var splits = value.split(" ");
                    var result = false;
                    for (let j = 0; j < splits.length; j++) {
                        if (!_h.isEmpty(splits[j]) && self.checkWordInCompanies(self.companySelectList()[i], splits[j])) {
                            result = result || true;
                        }
                    }
                    if (result)
                        self.companiesFiltered.push(self.companySelectList()[i]);
                }
            }
        }
        self.configConsolidate();
    });
    self.checkWordInCompanies = function (company, value) {
        return company.text().indexOf(value) !== -1;
    }
    self.configConsolidate = function () {
        var items = document.getElementsByClassName("consolidate-item");
        if (items && items.length) {
            for (var i = 0; i < items.length; i++) {
                items[i].addEventListener('dragstart', function (event) {
                    var img = this.getElementsByTagName("img")[0];
                    var model = {
                        id: this.getAttribute("data-id"),
                        name: this.getAttribute("data-name"),
                        isRoot: this.getAttribute("data-root")
                    };
                    event.dataTransfer.setData('application/json',
                        JSON.stringify({
                            action: "consolidate",
                            model: model
                        }));
                    event.dataTransfer.setDragImage(img, 30, 0);
                });
                items[i].ondragover = function (e) {
                    e.preventDefault();
                };
                items[i].ondragleave = function (e) {
                    e.preventDefault();
                };
                items[i].ondragend = function (e) {
                    e.preventDefault();
                };
            }
        }
    }
    self.getCompanySelectList = function () {
        var model = _h.kocnx().ttvm().getFocusDesignRecord();
        ApiService.request(
            {
                url: "/api/tablestructure/getconsolidated",
                data: { id: model.id },
                success: function (data) {
                    self.companySelectList.removeAll();
                    self.companiesFiltered.removeAll();
                    if (_h.any(data)) {
                        for (var j = 0; j < data.length; j++) {
                            var target = data[j];
                            self.companySelectList.push(new CompanySelectItem(target));
                            self.companiesFiltered.push(new CompanySelectItem(target));
                        }
                        self.configConsolidate();
                    }
                },
                error: function (data) {
                    toast.error(self.entityName, 'getSelectList', 'Consolidated');
                }
            });
    }
    self.toggleConsolidate = function () {
        self.showConsolidate(!self.showConsolidate());
        if (self.showConsolidate()) {
            self.getCompanySelectList();
            $(".consolidate-box").draggable({
                scroll: true,
                handle: ".consolidate-drag-handle"
            });
        }
    }
    self.toggleTableDataSource = function () {
        self.showTableDataSource(!self.showTableDataSource());
        if (self.showTableDataSource()) {
            self.tableDataSource().init({});
            $(".datasource-box").draggable({
                scroll: true,
                handle: ".tabledatasource-drag-handle"
            });
        }
    }
    self.toggleTreeDataSource = function () {
        if (self.showTreeDataSource()) {
            self.treeDataSource().collectOpenBranches();
        }
        self.showTreeDataSource(!self.showTreeDataSource());
        if (self.showTreeDataSource()) {
            self.treeDataSource().init();
            $(".datasource-box").draggable({
                scroll: true,
                handle: ".treedatasource-drag-handle"
            });
        }
    }
    self.toggleXbrlConcept = function () {
        if (self.showXbrlConcept()) {
            self.xbrlConceptModel().collectOpenBranches();
        }
        self.showXbrlConcept(!self.showXbrlConcept());
        if (self.showXbrlConcept()) {
            self.xbrlConceptModel().init();
            $(".xbrlconcept-box").draggable({
                scroll: true,
                handle: ".xbrlconcept-drag-handle"
            });
        }
    }
    self.togglePreview = function (vm, e) {
        if ($(e.currentTarget).attr("locked"))
            return;
        self.showPreview(!self.showPreview());
        var designItem = self.parentModel.findFocusDesignItem();
        if (!designItem)
            return;
        if (self.showPreview()) {
            $(e.currentTarget).attr("locked", "true");
            var templateModel = self.parentModel.getFocusDesignRecord();
            var arrayData = $("#rg-" + templateModel.id).find(".rp-gen").rg("toServer");
            self.showTableDataSource(false);
            self.showTreeDataSource(false);
            self.showConsolidate(false);
            ApiService.request({
                url: "/api/tabletemplate/postPreview",
                data: {
                    tableTemplateId: templateModel.id,
                    data: arrayData[0]
                },
                success: function (data) {
                    if (!_h.isEmpty(data)) {
                        $(e.currentTarget).attr("locked", "");
                        designItem.previewMode(false);
                        designItem.previewResult = data.models;
                        designItem.hiddenRows = data.hiddenRows;
                        designItem.hiddenCols = data.hiddenCols;
                        designItem.bindErrors = data.bindErrors;
                        designItem.previewMode(true);
                    }
                }.bind(this),
                error: function () {
                    $(e.currentTarget).attr("locked", "");
                    toast.error("TableTemplate", 'get', "Preview");
                }
            });
        } else {
            self.saveState();
            designItem.previewMode(false);
        }
    }
    self.toggleCompareValueCell = function () {
        var context = _h.kocnx();
        var templateModel = context.ttvm().getFocusDesignRecord();
        var cellBinds = $("#rg-" + templateModel.id).rg("getCellBinds");
        if (self.showCompare()) {
            var list = [];
            if (self.compareCellModel().cellBinds().length)
                for (var i = 0; i < self.compareCellModel().cellBinds().length; i++) {
                    var target = self.compareCellModel().cellBinds()[i];
                    if (target.validationObject.isValid()) {
                        var record = { title: target.title() ,firstCell: target.firstCell(), deterrent: target.deterrent(), secondCell: target.secondCell(), errorRate: target.errorRate() };
                        list.push(record);
                    }
                }
            $("#rg-" + templateModel.id).rg("setCellBinds", list);
            self.compareCellModel().selectedItem(null);
            self.showCompare(!self.showCompare());
        } else {
            var cCell = new CellBindForm();
            self.compareCellModel(cCell);
            self.compareCellModel().init({ parent: templateModel, gParent: self, cellBinds: cellBinds, id: templateModel.id });
            self.showCompare(!self.showCompare());
            $(".compare-value-cell-box").draggable({
                scroll: true,
                handle: ".compare-value-drag-handle"
            });
        }
    }
    self.toggleCellSelect = function () {
        if (self.showCellSelect())
            self.showCellSelect(false);
        else {
            if (self.hasSelectedCell()) {
                self.showCellSelect(true);
                self.cellSelectModel().filterList();
                $(".select-cell-box").draggable({
                    scroll: true,
                    handle: ".selectcell-drag-handle"
                });
            }
            else
                toast.custom("error", "لطفا سلولی از جدول  را جهت اتصال انتخاب نمایید");
        }
    }
    self.onSelectCellAction = function (cell) {
        var designItem = context.ttvm().findFocusDesignItem();
        $("#rg-" + designItem.value()).find(".rp-gen").rg("command",
            {
                id: "cellSelect", value: cell.tag, title: self.cellSelectModel().templateName()
                    + "(" + cell.address + ")"
            });

    }
    self.hasSelectedCell = function () {
        var context = _h.kocnx();
        var designItem = context.ttvm().findFocusDesignItem();
        var selectedItems = $("#rg-" + designItem.value()).find(".rp-gen").rg("getSelectedCells");
        if (!selectedItems || selectedItems.length === 0)
            return false;
        return true;
    }
    self.toolItemDragFunctionality = function () {
        var items = document.getElementsByClassName("tool-item");
        if (items && items.length) {
            for (var i = 0; i < items.length; i++) {
                items[i].addEventListener('dragstart', function (event) {
                    var img = this.getElementsByTagName("img")[0];
                    event.dataTransfer.setData('application/json',
                        JSON.stringify({
                            action: "sign",
                            actionType: this.getAttribute("data-action")
                        }));
                    event.dataTransfer.setDragImage(img, 20, 0);
                }, false);
                items[i].addEventListener('dragover', function (event) {
                    event.preventDefault();
                }, false);
                items[i].addEventListener('dragleave', function (event) {
                    event.preventDefault();
                }, false);
                items[i].addEventListener('dragend', function (event) {
                    event.preventDefault();
                }, false);
            }
        }
    }
    self.toggleShowInfo = function () {
        if (!self.showInfo()) {
            self.childInfoModel(new RgMenuInfo());
            self.showInfo(true);
            self.childInfoModel().init();
        } else {
            self.showInfo(false);
            self.childInfoModel(null);
        }
    }
    self.resetWindows = function () {
        self.showTableDataSource(false);
        self.showTreeDataSource(false);
        self.showConsolidate(false);
        self.showPreview(false);
        self.showCompareValueCell(false);
    }
    self.saveState = function () {
        var model = {
            treeOpenBranches: self.treeDataSource().treeOpenBranches,
            treeId: self.treeDataSource().treeId(),
            periodId: self.treeDataSource().periodId(),
            nodeDisplayType: self.treeDataSource().nodeDisplayType(),
            tableId: self.tableDataSource().tableId()
        };

        if (self.cellSelectModel()) {
            model.tableTemplateId = self.cellSelectModel().tableTemplateId();
        }

        clientStorage.setSetting(
            [{ key: "RgMenu_", value: JSON.stringify(model) }]
        );
    }
    self.loadState = function () {
        model = self.readstate();
        if (model.periodId && model.treeId) {
            self.treeDataSource().init(model);
        }
        if (model.tableId) {
            self.tableDataSource().init(model);
        }
        if (model.tableTemplateId) {
            self.cellSelectModel().init(model);
        }
        return model;
    }
    self.readstate = function () {
        var context = _h.kocnx();

        var model = {};
        var data = clientStorage.getSetting("RgMenu_" + context.loginCompanyId());
        if (!_h.isEmpty(data)) {
            model = JSON.parse(data);
        }
        return model;

    }
    self.init = function () {
        self.loadState();
    }
    self.init();
    self.closeAllModals = function () {
        if (self.showPreview()) {
            self.saveState();
            var designItem = self.parentModel.findFocusDesignItem();
            designItem.previewMode(false);
            self.showPreview(false);
        }
        if (self.showXbrlConcept()) {
            self.xbrlConceptModel().collectOpenBranches();
            self.showXbrlConcept(false);
        }
        if (self.showCompare()) {
            self.showCompare(false);
            self.compareCellModel().selectedItem(null);
        }
        if (self.showConsolidate())
            self.showConsolidate(false);
        if (self.showInfo()) {
            self.showInfo(false);
            self.childInfoModel(null);
        }
        if (self.showTreeDataSource()) {
            self.treeDataSource().collectOpenBranches();
            self.showTreeDataSource(false);
        }
        if (self.showTableDataSource()) {
            self.showTableDataSource(false);
        }
        if (self.showCellSelect())
            self.showCellSelect(false);
    }
}
export class ActionMenu extends BaseInnerModel {
    constructor(model) {
        super(model);
        this.show = ko.observable(model.inner ? false : true);
        this.header = model.header;
        this.inner = model.inner;
        this.iconAddr = '/App/src/images/Icons/' + model.icon + ".png";
        switch (model.icon) {
            case 33:
            case 34:
            case 35:
                this.iconAddr = '/App/src/images/Icons/' + model.icon + '/' + model.value + ".png";
                break;
        }
        this.actionName = ko.observable(model.name || model.title);
        this.oldPattern = "";
        this.value = ko.observable(model.value);
        this.pattern = ko.observable(model.pattern);
        this.pattern.subscribe(function (value) {
            if (_h.isEmpty(value)) {
                this.pattern(this.oldPattern);
            }
        }.bind(this));
        this.changeToDefualt = function () {
            this.pattern(this.defaultValue());
        }
    }
}
export class SubMenu extends BaseInnerModel {
    constructor(model) {
        super(model);
        this.editMode = ko.observable(false);
        this.actions = ko.observableArray();
        if (_h.any(model.actions))
            for (var j = 0; j < model.actions.length; j++) {
                var action = model.actions[j];
                this.actions.push(new ActionMenu(action));
            }
    }

    onHeaderSelect(item) {
        this.actions().filter(a => {
            if (a.icon() === item.icon()) {
                a.show(!a.show());
            }
        });
    }
}
export function RgMenuInfo() {
    var self = this;
    self.subMenuItems = ko.observableArray();
    self.toolItemDragFunctionality = function () {
        var items = document.getElementsByClassName("tool-item");
        if (items && items.length) {
            for (var i = 0; i < items.length; i++) {
                items[i].addEventListener('dragstart', function (event) {
                    var img = this.getElementsByTagName("img")[0];
                    event.dataTransfer.setData('application/json',
                        JSON.stringify({
                            action: "sign",
                            actionType: this.getAttribute("data-action")
                        }));
                    event.dataTransfer.setDragImage(img, 20, 0);
                }, false);
                items[i].addEventListener('dragover', function (event) {
                    event.preventDefault();
                }, false);
                items[i].addEventListener('dragleave', function (event) {
                    event.preventDefault();
                }, false);
                items[i].addEventListener('dragend', function (event) {
                    event.preventDefault();
                }, false);
            }
        }
    }
    self.selectSubMenu = function (item) {
        if (item.selected() && item.actions().length > 0) {
            item.selected(false);
            return;
        }
        if (item.actions().length > 0) {
            for (var i = 0; i < self.subMenuItems().length; i++) {
                self.subMenuItems()[i].selected(false);
            }
            item.selected(true);
        }
    }
    self.fillMenuItems = function () {
        var context = _h.kocnx();
        var designItem = context.ttvm().findFocusDesignItem();
        self.getInfoMenuDataForm(function (list) {
            var infoActions = [];
            if (list) {
                var c1 = false, c2 = false, c3 = false;
                for (var i = 0; i < list.length; i++) {
                    var infoAction;
                    var info = _h.getEnumItem(cellInfoTypes, list[i].cellInfoType);
                    if (info.value !== 33 && info.value !== 34 && info.value !== 35) {
                        if (info.value !== 25) {
                            infoAction = {
                                name: list[i].title, value: list[i].value, icon: info.value, action: "info:'" + info.value + "'",
                                defaultValue: list[i].defaultValue, pattern: list[i].pattern, oldPattern: list[i].pattern
                            };
                            infoActions.push(infoAction);

                        } else {
                            if (designItem.type() === 4) {
                                infoAction = {
                                    name: "شماره سطر", value: list[i].value, icon: 25, action: "info:'25'",
                                    defaultValue: list[i].defaultValue, pattern: list[i].pattern, oldPattern: list[i].pattern
                                };
                                infoActions.push(infoAction);
                            }
                        }
                    }
                    else {
                        var action = "";
                        switch (info.value) {
                            case 33:
                                action = "periodname:'" + list[i].value + "'";
                                if (!c1) {
                                    c1 = true;
                                    infoActions.push({
                                        name: "دوره مالی/مقایسه ای",
                                        icon: 33,
                                        header: true,
                                        defaultValue: list[i].defaultValue,
                                        pattern: list[i].pattern,
                                        oldPattern: list[i].pattern,
                                        action: action,
                                        inner: false
                                    });
                                }
                                list[i].icon = 33;       
                                list[i].action = action;           
                                list[i].header = false;                                
                                list[i].inner = true;
                                infoActions.push(list[i]);
                                break;
                            case 34:
                                action = "perioddate:'" + list[i].value + "'";
                                if (!c2) {
                                    c2 = true;
                                    infoActions.push({
                                        name: "تاریخ/دوره مقایسه ای",
                                        icon: 34,
                                        header: true,
                                        action: action,
                                        defaultValue: list[i].defaultValue,
                                        pattern: list[i].pattern,
                                        oldPattern: list[i].pattern,
                                        action: action,
                                        inner: false
                                    });
                                }
                                list[i].icon = 34;       
                                list[i].action = action;           
                                list[i].header = false;
                                list[i].inner = true;
                                infoActions.push(list[i]);
                                break;
                            case 35:
                                action = "periodyear:'" + list[i].value + "'";
                                if (!c3) {
                                    c3 = true;
                                    infoActions.push({
                                        name: "تاریخ/سال مقایسه ای",
                                        icon: 35,
                                        header: true,
                                        defaultValue: list[i].defaultValue,
                                        pattern: list[i].pattern,
                                        oldPattern: list[i].pattern,
                                        action: action,
                                        inner: false
                                    });
                                }
                                list[i].icon = 35;       
                                list[i].action = action;           
                                list[i].header = false;
                                list[i].inner = true;
                                infoActions.push(list[i]);
                                break;                                
                        }
                    }
                }
            }
            self.subMenuItems.push(new SubMenu({
                name: "اطلاعات",
                selected: false,
                actions: infoActions
            }));
            var actions = [];
            if (designItem.type() !== 4) {
                actions = [
                    { name: "جمع کلی", icon: 11, action: "TotalSum", operator: "Sum" },
                    { name: "جمع جزیی", icon: 12, action: "PartialSum", operator: "Sum" },
                    { name: "میانگین", icon: 13, action: "Average", operator: "Avg" },
                    { name: "بیشترین", icon: 14, action: "Max", operator: "Max" },
                    { name: "کمترین", icon: 15, action: "Min", operator: "Min" }
                ];
            }
            else {
                actions = [
                    { name: "جمع گروهی", icon: 26, action: "GroupSum", operator: "GSum" },
                    { name: "جمع ستونی", icon: 27, action: "ColumnSum", operator: "CSum" },
                ];
            }
            self.subMenuItems.push(new SubMenu({
                name: "محاسبات",
                selected: false,
                actions: actions
            }));
            self.toolItemDragFunctionality();
        });
    }
    self.onEdit = function (item) {
        item.editMode(true);
        item.selected(true);
    }
    self.getInfoMenuDataForm = function (callback) {
        ApiService.request(
            {
                url: "/api/tablestructure/getcustomreportinfo",
                data: model,
                success: function (list) {
                    callback(list);
                },
                error: function (data) {
                    callback(null);

                }
            });
    }
    self.setInfoMenuDataForm = function (item) {
        var array = [];
        for (var j = 0; j < item.actions().length; j++) {
            var action = item.actions()[j];
            array.push({
                value: action.value(),
                cellInfoType: action.icon(),
                pattern: action.pattern()
            });
        }
        var model = {
            list: array
        };
        ApiService.request(
            {
                url: "/api/tablestructure/postcustomreportinfo",
                data: model,
                success: function (data) {
                    item.editMode(false);
                    toast.custom('success', 'عملیات بروزرسانی بخش اطلاعات با موفقیت انجام شد');
                    self.toolItemDragFunctionality();

                },
                error: function (data) {
                    toast.custom('error', 'عملیات بروزرسانی بخش اطلاعات با خطا متوقف شد');

                }
            });
    }
    self.init = function () {
        self.fillMenuItems();
        setTimeout(function () {
            $(".left-menu-rg").draggable({
                scroll: true,
                handle: ".left-menu-drag-handle"
            });
        }, 150);
    }
}
export function DomChart(pa, newChart) {
    var self = this;
    self.parent = pa;
    self.randomId = _h.createRandomNumber();
    self.id = ko.observable("chart-" + self.randomId);
    self.showChart = ko.observable(false);
    self.originalChartType = ko.observable();
    self.chartType = ko.observable();
    self.originalChartType = ko.observable();
    self.dataSource = ko.observable();
    self.left = ko.observable();
    self.top = ko.observable();
    self.width = ko.observable(350);
    self.height = ko.observable(220);
    self.colorPalette = ko.observable("palette1");
    self.series = ko.observableArray();
    self.labels = ko.observableArray();
    self.fontSize = ko.observable("12px");
    self.fontFamily = ko.observable("Nazanin");
    self.mixedMode = ko.observable(false);
    self.legendPosition = ko.observable(1);
    self.dataLabelColor = ko.observable("#000000");
    self.labelFontWeight = ko.observable(false);
    self.chartObject = null;
    self.options = {
        series: [],
        chart: {
            type: "bar",
            width: self.width(),
            height: self.height(),
            stacked: false,
            animations: {
                enabled: false
            },
            zoom: {
                enabled: false
            },
            toolbar: {
                show: false,
                tools: {
                    download: false
                }
            },
            events: {
                legendClick: function (chartContext, seriesIndex, config) {

                }
            }
        },
        theme: {
            palette: "palette1"
        },
        title: {
            display: ko.observable(true),
            text: ko.observable(),
            align: 'center',
            style: {
                fontSize: self.fontSize(),
                fontFamily: self.fontFamily()
            }
        },
        legend: {
            show: ko.observable(true),
            position: 'bottom',
            fontFamily: self.fontFamily(),
            onItemClick: {
                toggleDataSeries: false
            }
        },
        tooltip: {
            enabled: false
        },
        dataLabels: {
            enabled: ko.observable(false),
            formatter: function (val, opt) {
                return _h.formatNumber(val, false);
            },
            style: {
                fontFamily: self.fontFamily(),
                fontWeight: "bold",
                colors: ["#000"]
            }
        },
        noData: {
            text: 'داده ای برای نمایش وجود ندارد',
            align: 'center',
            verticalAlign: 'middle',
            offsetX: 0,
            offsetY: 0,
            style: {
                color: undefined,
                fontSize: '13px',
                fontFamily: "IranSans"
            }
        },
        xaxis: {
            categories: [],
            labels: {
                style: {
                    fontFamily: self.fontFamily()
                }
            }
        },
        yaxis: {
            labels: {
                style: {
                    fontFamily: self.fontFamily()
                }
            }
        }
    };
    self.fillOptions = function (model) {
        if (model) {
            self.options.chart.width = self.width();
            self.options.chart.height = self.height();
            self.options.theme.palette = model.colorPalette;
            self.options.title.text(model.options.title.text);
            self.options.title.display(model.options.title.display);
            self.options.legend.show(model.options.legend.show);
            self.options.legend.position = model.options.legend.position;
            self.options.dataLabels.enabled(model.options.dataLabels.enabled);
            if (model.options.dataLabels["style"]) {
                self.options.dataLabels.style.fontFamily = self.fontFamily();
                self.options.dataLabels.style.fontWeight = model.options.dataLabels.style.fontWeight || "500";
                if (model.options.dataLabels.style.fontWeight === "bold") {
                    self.labelFontWeight(true);
                }
                self.options.dataLabels.style.colors = model.options.dataLabels.style.colors;
            }

            if (model.chartType === "pie")
                self.options.dataLabels.enabled(true);

            switch (model.originalChartType) {
                case "bar":
                    self.options.plotOptions = {
                        bar: {
                            horizontal: true,
                            columnWidth: "55%",
                            endingShape: "rounded"
                        }
                    };
                    break;
                case "column":
                    self.options.plotOptions = {
                        bar: {
                            horizontal: false,
                            columnWidth: "55%",
                            endingShape: "rounded"
                        }
                    };
                    break;
                case "pie":
                    self.options.dataLabels.enabled(true);
                    break;
            }
        }
    }
    self.fillModel = function (model) {
        self.id(model.id);
        if (_h.isEmpty(self.id())) {
            self.randomId = _h.createRandomNumber();
            self.id("chart-" + self.randomId);
        }
        self.mixedMode(model.mixedMode);
        self.toggleSuspendControls(true);
        self.dataSource(model.dataSource);
        self.fontSize(model.fontSize);
        self.fontFamily(model.fontFamily);
        self.left(model.left);
        self.top(model.top);
        self.width(model.width);
        self.height(model.height);
        self.colorPalette(model.colorPalette);
        self.legendPosition(model.legendPosition);
        self.fillOptions(model);
        self.originalChartType(model.originalChartType);
        self.chartType(model.chartType);
        if (self.options.dataLabels["style"])
            self.dataLabelColor(self.options.dataLabels.style.colors[0]);
        self.configTools();
        var list = self.getTargetCells();
        self.detectDataTable(list, model, true);
        self.toggleSuspendControls(false);
    }
    self.fillEmpty = function (itemType, count, list) {
        self.showChart(true);
        self.toggleSuspendControls(true);
        self.options.title.text("نمودار " + itemType.text + " " + count);
        var [minAddress, maxAddress] = _h.findMinMaxCells(list);
        self.dataSource("[" + minAddress + ":" + maxAddress + "]");
        switch (itemType.enText) {
            case "bar":
                self.chartType(itemType.enText);
                self.originalChartType(itemType.enText);
                self.options.plotOptions = {
                    bar: {
                        horizontal: true,
                        columnWidth: "55%",
                        endingShape: "rounded"
                    }
                };
                break;
            case "column":
                self.chartType("bar");
                self.originalChartType("column");
                self.options.plotOptions = {
                    bar: {
                        horizontal: false,
                        columnWidth: "55%",
                        endingShape: "rounded"
                    }
                };
                break;
            case "pie":
                self.chartType(itemType.enText);
                self.originalChartType(itemType.enText);
                self.options.dataLabels.enabled(true);
                break;
            default:
                self.originalChartType(itemType.enText);
                self.chartType(itemType.enText);
                break;
        }
        self.configTools();
        self.detectDataTable(list);
        self.toggleSuspendControls(false);
    }
    self.configTools = function () {
        if (self.top())
            $("#box" + self.id()).css("top", self.top());
        if (self.left())
            $("#box" + self.id()).css("left", self.left());
        $("#box" + self.id()).draggable({
            scroll: true,
            stop: function (event, ui) {

            }
        });
    }
    self.changePosition = function () {
        var target = $("#box" + self.id()).get(0);
        self.toggleSuspendControls(true);
        var left = parseFloat(target.style.left.replace("px", ""));
        var top = parseFloat(target.style.top.replace("px", ""));
        var width, height;
        var real = $(target).find(".chart-object");
        if (real.length) {
            width = parseFloat(real.css("width"));
            height = parseFloat(real.css("height"));
            if (self.chartType() === "pie") {
                height = height + 32;
            } else {
                height = height - 15;
            }
            self.width(width);
            self.height(height);
            if (self.height() === 0) {
                self.height(220);
            }
        }
        self.left(left);
        self.top(top);
        self.toggleSuspendControls(false);
    }
    self.detectDataTable = function (list, oldModel, editMode) {
        self.series.removeAll();
        self.labels.removeAll();
        var colorSet = chartColors.filter(a => a.text === self.colorPalette())[0];
        var isOfflineTable = list.filter(a => !_h.isEmpty(a.value)).length === 0;
        var [columns, rows] = _h.analyzeCells(list);
        var col, row, oldLabel;
        if (_h.any(columns))
            for (var i = 0; i < columns.length; i++) {
                var column = columns[i];
                if (!editMode) {
                    column.type = self.chartType();
                    column.originalChartType = self.originalChartType();
                    col = new ChartDataSet(column, self);
                    if (!col.color())
                        col.color(colorSet.values[i]);
                    self.series.push(col);
                } else {
                    var oldCol = oldModel.series.filter(a => a.address === column.address);
                    if (oldCol.length) {
                        col = new ChartDataSet(oldCol[0], self);
                        self.series.push(col);
                    }
                }
            }
        if (_h.any(rows))
            for (var j = 0; j < rows.length; j++) {
                if (!editMode) {
                    row = new ChartDataLabel(rows[j], self);
                    self.labels.push(row);
                } else {
                    oldLabel = oldModel.categories.filter(a => a.address === rows[j].address);
                    if (oldLabel.length) {
                        row = new ChartDataLabel(oldLabel[0], self);
                        self.labels.push(row);
                    }
                }
            }

        if (isOfflineTable)
            self.configChart();

    }
    self.createChartDataModel = function (onlineValue, empty) {
        self.options.series = [];
        self.options.xaxis.categories = [];
        self.options.labels = [];
        if (empty)
            return ko.toJS(self.options);
        var cells = self.getTargetCells();

        var invalidRows = self.labels().filter(a => !a.enable()).map(function (v) {
            return Number(v.address().replace(/^\D+/g, ""));
        });
        var labels = self.labels().filter(a => a.enable()).map(function (v) {
            if (!v.label()) {
                var cell = cells.filter(a => a.address === v.address());
                if (cell.length)
                    v.label(cell[0].text);
                return v.label();
            }
            return v.label();
        });
        if (self.chartType() === "pie")
            self.options.labels = labels;
        else
            self.options.xaxis.categories = labels;

        for (var i = 0; i < self.series().length; i++) {
            var target = self.series()[i];
            var number = target.address().replace(/^\D+/g, "");
            var letter = target.address().replace(number, "");
            var colNumber = _h.alphabetToNumber(letter);

            var colCells = cells.filter(a => a.col === colNumber && a.row !== Number(number));
            var values = colCells.map(function (v) {

                if (invalidRows.indexOf(v.row) === -1) {
                    try {
                        if (onlineValue) {
                            var dValue = _h.replaceAll(v.text, ",", "");
                            return parseFloat(dValue);
                        } else {
                            if (v.text)
                                return parseFloat(v.text);
                            return 0;
                        }
                    } catch (e) {
                        return 0;
                    }
                } else {
                    return "___Null___";
                }

            });
            if (target.enable()) {
                var dataSet;
                if (self.chartType() === "pie") {
                    dataSet = values.filter(a => a !== "___Null___");
                    self.options.series = dataSet;
                }
                else {
                    dataSet = {
                        name: target.label(),
                        data: values.filter(a => a !== "___Null___"),
                        type: target.type()
                    };
                    self.options.series.push(dataSet);
                }
            }

        }
        self.options.chart.width = self.width();
        self.options.chart.height = self.height();
        if (self.options.chart.height <= 0)
            self.options.chart.height = 220;

        self.options.theme.palette = self.colorPalette();
        self.options.chart.type = self.chartType();

        self.options.legend.fontFamily = self.fontFamily();
        self.options.dataLabels.style.colors = [];
        for (var j = 0; j < 10; j++) {
            self.options.dataLabels.style.colors.push(self.dataLabelColor());
        }
        if (self.labelFontWeight()) {
            self.options.dataLabels.style.fontWeight = "bold";
        } else {
            self.options.dataLabels.style.fontWeight = "300";
        }
        var data = ko.toJS(self.options);
        if (self.options.title.display()) {
            data.title.style.fontSize = self.fontSize();
            data.title.style.fontFamily = self.fontFamily();
            data.title.text = self.options.title.text();
        } else {
            data.title.text = undefined;
        }
        return data;
    }
    self.configChart = function (changeToMixedType) {
        if (changeToMixedType && !self.mixedMode()) {
            self.mixedMode(true);
            self.chartType("line");
        }
        if (self.mixedMode() && self.chartType() !== "line") {
            self.mixedMode(true);
            self.chartType("line");
        }
        var cells = self.getTargetCells();
        if (!cells.length)
            return;
        if (self.chartObject != null) {
            try {
                self.chartObject.destroy();
            } catch (e) {

            }
        }

        var isOfflineTable = cells.filter(a => !_h.isEmpty(a.value)).length === 0;
        var hasOnlineValue = cells.filter(a => a.hasDynamicValue).length > 0;

        var previewMode = self.parent.previewMode();
        var config;
        var element = document.querySelector("#" + self.id());
        if (isOfflineTable) {
            config = self.createChartDataModel();
            self.chartObject = new ApexCharts(element, config);
        } else if (previewMode && hasOnlineValue) {
            config = self.createChartDataModel(true);
            self.chartObject = new ApexCharts(element, config);
        } else {
            config = self.createChartDataModel(false, true);
            self.chartObject = new ApexCharts(element, config);
        }

        console.log(config);
        //        console.log(self.height());
        if (!element)
            return;
        self.chartObject.render();
    }
    self.changeChartColor = function (item, m) {
        self.colorPalette(item.text);
    }
    self.onChangeRange = function () {
        var cells = self.getTargetCells();
        self.detectDataTable(cells);
    }
    self.getTargetCells = function () {
        var text = self.dataSource().replace("[", "").replace("]", "");
        var splits = text.split(':');
        var numberA = splits[0].replace(/^\D+/g, '');
        var letterA = splits[0].replace(numberA, '');
        var colNumberA = _h.alphabetToNumber(letterA);
        var numberB = splits[1].replace(/^\D+/g, '');
        var letterB = splits[1].replace(numberB, '');
        var colNumberB = _h.alphabetToNumber(letterB);
        var list = [];
        for (var i = 0; i < numberB; i++) {
            for (var j = 0; j < colNumberB; j++) {
                var xi = i + 1;
                var xj = j + 1;
                if ((xi >= numberA && xi <= numberB) && (xj >= colNumberA && xj <= colNumberB)) {
                    list.push(_h.numberToAlphabet(xj) + xi);
                }
            }
        }
        var cells = self.parent.scope.find(".rp-gen").rg("selectGroupCells", list);
        return cells;
    }
    self.dataLabelColorsub = self.dataLabelColor.supsendableSubscribe(function (newValue) {
        if (!_h.isNullOrEmpty(newValue)) {
            self.configChart();
        }
    });
    self.fontSizesub = self.fontSize.supsendableSubscribe(function (newValue) {
        if (!_h.isNullOrEmpty(newValue)) {
            self.configChart();
        }
    });
    self.fontFamilysub = self.fontFamily.supsendableSubscribe(function (newValue) {
        if (!_h.isNullOrEmpty(newValue)) {
            self.configChart();
        }
    });
    self.displaysub = self.options.title.display.supsendableSubscribe(function (newValue) {
        if (!_h.isNullOrEmpty(newValue)) {
            self.configChart();
        }
    });
    self.colorPalettesub = self.colorPalette.supsendableSubscribe(function (newValue) {
        if (!_h.isNullOrEmpty(newValue)) {
            self.configChart();
        }
    });
    self.textsub = self.options.title.text.supsendableSubscribe(function (newValue) {
        if (!_h.isNullOrEmpty(newValue)) {
            self.configChart();
        }
    });
    self.showlegendsub = self.options.legend.show.supsendableSubscribe(function (newValue) {
        self.configChart();
    });
    self.positionlegendsub = self.legendPosition.supsendableSubscribe(function (newValue) {
        if (!_h.isEmpty(newValue)) {
            var item = _h.getEnumItem(positions, newValue);
            self.options.legend.position = item.enText;
            self.configChart();
        } else {
            self.options.legend.position = "bottom";
            self.configChart();
        }
    });
    self.dataLabelsenabledsub = self.options.dataLabels.enabled.supsendableSubscribe(function (newValue) {
        self.configChart();
    });
    self.dataLabelsfontWeightsub = self.labelFontWeight.supsendableSubscribe(function (newValue) {
        self.configChart();
    });
    self.dataLabelsColorsub = self.dataLabelColor.supsendableSubscribe(function (newValue) {
        self.configChart();
    });
    self.heightsub = self.height.supsendableSubscribe(function (newValue) {
        if (!_h.isNullOrEmpty(newValue)) {
            self.configChart();
        }
    });
    self.widthsub = self.width.supsendableSubscribe(function (newValue) {
        if (!_h.isNullOrEmpty(newValue)) {
            self.configChart();
        }
    });
    self.toggleSuspendControls = function (sta) {
        if (sta) {
            self.fontSizesub.suspend();
            self.fontFamilysub.suspend();
            self.displaysub.suspend();
            self.colorPalettesub.suspend();
            self.textsub.suspend();
            self.showlegendsub.suspend();
            self.positionlegendsub.suspend();
            self.dataLabelsenabledsub.suspend();
            self.dataLabelsfontWeightsub.suspend();
            self.dataLabelsColorsub.suspend();
            self.heightsub.suspend();
            self.widthsub.suspend();
        } else {
            self.fontSizesub.unsuspend();
            self.fontFamilysub.unsuspend();
            self.displaysub.unsuspend();
            self.colorPalettesub.unsuspend();
            self.textsub.unsuspend();
            self.showlegendsub.unsuspend();
            self.positionlegendsub.unsuspend();
            self.dataLabelsenabledsub.unsuspend();
            self.dataLabelsfontWeightsub.unsuspend();
            self.dataLabelsColorsub.unsuspend();
            self.heightsub.unsuspend();
            self.widthsub.unsuspend();
        };
    }
    self.toggleShow = function () {
        self.showChart(self.showChart());
        if (!self.showChart() && item.chartObject) {
            item.chartObject.destroy();
        } else {
            self.configTools();
        }
    }
    self.toServer = function () {
        var objChart = {
            showChart: false,
            id: self.id(),
            randomId: self.randomId,
            chartType: self.mixedMode() ? self.originalChartType() : self.chartType(),
            originalChartType: self.originalChartType(),
            dataSource: self.dataSource(),
            left: self.left(),
            top: self.top(),
            width: self.width(),
            height: self.height(),
            colorPalette: self.colorPalette(),
            fontSize: self.fontSize(),
            fontFamily: self.fontFamily(),
            mixedMode: self.mixedMode(),
            legendPosition: self.legendPosition(),
            categories: [],
            series: [],
            options: ko.toJS(self.options)
        };
        if (!objChart.top) {
            var top = $("#box" + self.id()).css("top");
            objChart.top = parseFloat(top.replace("px", ""));
        }
        for (var j = 0; j < self.labels().length; j++) {
            var label = self.labels()[j];
            objChart.categories.push({
                address: label.address(),
                label: label.label(),
                enable: label.enable()
            });
        }
        for (var j = 0; j < self.series().length; j++) {
            var item = self.series()[j];
            objChart.series.push({
                color: item.color(),
                address: item.address(),
                type: item.type(),
                typeNumber: item.typeNumber(),
                label: item.label(),
                borderColor: item.borderColor(),
                backgroundColor: item.backgroundColor(),
                fill: item.fill(),
                enable: item.enable()
            });
        }
        if (objChart.options.xaxis)
            objChart.options.xaxis.categories = [];
        objChart.options.labels = [];
        objChart.options.series = [];
        return objChart;
    }
}
export function ChartMenu() {
    var self = this;
    self.show = ko.observable(false);
    self.open = function (event, chartModel) {
        ko.utils.extend(self, chartModel);
        self.show(true);
        $(".chart-menu").draggable({
            scroll: true,
            handle: ".chart-setting-draghandler"
        });
        $(".chart-menu").position({
            my: 'center top',
            at: 'center bottom',
            of: $(event.target),
            offset: '0 5',
            collision: 'fit'
        });
    }
    self.close = function (item) {
        try {
            if (item.chartObject)
                item.chartObject.destroy();
        } catch (e) {

        }
        self.show(false);
    }
    self.categoryTagSelectTemplate = function (item) {
        var temp = '<div style="padding: 3px;">' +
            '<span class="item-title">' +
            '<span class="item-name">' +
            item.text +
            '</span>' +
            '</span>' +
            '<div class="label label-primary2 remove-tag" style="float: left;padding-top: 4px;background-color: #ccc;">حذف</div>' +
            '</div>';
        return temp;
    };
    self.onCheckItem = function (item) {
        item.enable(!item.enable());
    };
}
export function ChartTitle(model) {
    this.color = model.color ? model.color : '';
    this.align = model.align ? model.align : 'center';//'start' 'center' 'end'
    this.display = model.display;
    this.position = model.position ? model.position : 'bottom'; //'top'  'left'  'bottom'  'right'
    this.padding = model.padding ? model.padding : {
        top: 10,
        bottom: 10
    };
    this.text = model.text;
}
export function ChartDataSet(model, parent) {
    this.parent = parent;
    this.color = ko.observable(model.color);
    this.address = ko.observable(model.address);
    this.type = ko.observable(model.type);
    if (!model.typeNumber) {
        var x = _h.getEnumItemByText(chartTypes, model.originalChartType).value;
        this.typeNumber = ko.observable(x);
    } else {
        this.typeNumber = ko.observable(model.typeNumber);
    }
    this.label = ko.observable(model.label);
    this.data = ko.observable(model.data);
    this.borderColor = ko.observable(model.borderColor);
    this.backgroundColor = ko.observable(model.backgroundColor);
    this.fill = ko.observable(model.fill || true);
    this.enable = ko.observable(model.enable || true);
    this.enable.subscribe(function (newValue) {
        this.parent.configChart();
    }.bind(this));
    this.typeNumber.subscribe(function (newValue) {
        if (!_h.isNullOrEmpty(newValue)) {
            var item = _h.getEnumItem(chartTypes, newValue);
            this.type(item.enText);
            parent.configChart(this.address());
        }
    }.bind(this));
}
export function ChartDataLabel(model, parent) {
    this.parent = parent;
    this.address = ko.observable(model.address);
    this.label = ko.observable(model.label);
    this.enable = ko.observable(model.enable || true);
    this.enable.subscribe(function (newValue) {
        parent.configChart();
    });
}
export function XbrlConceptViewModel() {
    var self = this;
    self.treeOpenBranches = [];
    self.collectOpenBranches = function () {
        var tree = $("#xbrlconcept-tree-sec").find(".dmn-tree");
        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;
        return array;
    }
    ko.utils.extend(self, new BaseViewModel({
        entityName: "XbrlConcept",
        getList: false,
        apiService: {
            actionList: []
        },
        buttons: [
            { name: 'refresh', access: false, cMenu: false },
            { name: 'tools', access: false, cMenu: false }
        ],
        filters: [],
        tableStyle: "font-size: 11px;",
        sortDirection: "Ascending",
        sortProperty: "code",
        context: self,
        cols: treeInfoModelRes,
        searchKeyType: "enter",
        selectRow: true,
        saveState: true,
        contextMenu: false,
        isMultiSelectRows: false
    }));
    self.btnVisibility = ko.computed(function () {
        self.visrefresh(true);
        self.vistools(true);
    });
    self.init = function () {
        self.fillTableProperties();
        self.getRecords();
        self.iconSize("icon-image-small");
    }
    self.getRecords = function () {
        var filterModel = {
            searchKey: self.searchKey()
        };
        self.apiService.request({
            name: "getXbrlConcepts",
            data: filterModel,
            success: function (data) {
                if (data && _h.any(data.list)) {
                    self.records = data.list;
                }
                self.configTools();
            },
            messageType: 'getList',
            messageKey: self.entityName
        });
    }
    self.expandAll = function () {
        $("#xbrl_tree_view").treeView("expandAll");
    }
    self.collapseAll = function () {
        $("#xbrl_tree_view").treeView("collapseAll");
    }
    self.configTools = function () {
        $("#xbrl_tree_view").treeView({
            tType: self.entityName,
            location: self.entityName,
            nodes: self.records,
            rootId: "x",
            rootName: "XbrlConcept"
        });
        if (self.treeOpenBranches && self.treeOpenBranches.length)
            $("#xbrl_tree_view").treeView("expand", self.treeOpenBranches);
    }
}
export function DescCell(cell) {
    var self = this;
    self.cell = cell;
    self.input = ko.observable(cell.desc);
    self.input.subscribe(function (value) {
        var context = _h.kocnx();
        var templateModel = context.ttvm().getFocusDesignRecord();
        $("#rg-" + templateModel.id).rg("command", {
            value: value, id: "ChangeDesc", cell: self.cell
        });
        context.ttvm().focusDesignItem().refreshToolBar(true);
    });
}
export function CellRegion(model, parent) {
    var self = this;
    self.start = ko.observable(model.start);
    self.end = ko.observable(model.end);
    self.parent = parent;
    self.start.subscribe(function (val) {
        self.parent.subscribeRegions();
    });
    self.end.subscribe(function (val) {
        self.parent.subscribeRegions();
    });
}
export class TableTemplatePreview extends FormBuilder {
    constructor(viewModel, model) {
        super();
        this.parentVM = viewModel;
        this.fillModel(model);
        this.createForm();
        this.calculateWidthModel();
    }
    fillModel(model) {
        let paramList = [
            { name: "caption", type: "ob", val: _h.getLocalizedText('previewCaption') },
            { name: "htmlContent", type: "ob", val: model.data },
            { name: "oldResult", type: "ob" },
            { name: "showResult", type: "ob", val: false },
        ];
        _autoMapper.createPropsFromList(this, paramList);
    }
    calculateWidthModel() {
        var table = $("#prv-html").find("table");
        var width = table.width();
        $(".modal-box").css("width", width + 65);
        var screenWidth = $("body").width();
        var rest = (screenWidth - (width + 65)) / 2;
        $(".modal-box").css("left", rest + "px");
    }
    createForm() {
        const controls = [
            this.createLine({ t: 'tm', templateName: 'table-htmlcontent-form-t' }, undefined, this.visHtmlContent, 30, 0)
        ];

        this.formControls(controls);
        this.formButtons({
            name: 'footer-form-t', data: {
                buttons: [
                    { name: 'cancel', click: this.parentVM.closePreviewForm }
                ]
            }
        });
    }
}