var { BaseModel, BaseFormModel, FormBuilder } = require('../master/baseModels.js');
require('knockout.validation');
import { BaseViewModel } from '../master/baseViewModel.js';
import { ColumnSelectItem } from '../master/model.js';
import { PhraseTranslator } from '../master/phraseTranslator.js'
export class DynamicDocument extends BaseModel {
    constructor(model) {
        super(model);
        this.messageType = ko.observable(0);
        this.isEditable = ko.computed(function () {
            return this.stateType() !== 0;
        }.bind(this));
    }
}
export class DynamicDocumentForm extends BaseFormModel {
    constructor(viewModel, editMode, res) {
        super(viewModel, editMode);
        this.lastPriority = ko.observable();
        this.itemsCount = ko.observable();
        this.errorTree = ko.observableArray();
        this.section = ko.observable("general");
        this.documentProperties = ko.observable();
        this.dynamicDocumentType.subscribe(function (newValue) {
            var record = null;
            switch (newValue) {
                case 1:
                    record = new ComputationalDocumentProperties(this);
                    record.fillEmpty();
                    this.documentProperties(record);
                    break;
                case 2:
                case 3:
                    record = new ApportionmentDocumentProperties(this);
                    record.fillEmpty();
                    this.documentProperties(record);
                    break;
                case 4:
                    record = new AggregationDocumentProperties(this);
                    record.fillEmpty();
                    this.documentProperties(record);
                    break;
                case 5:
                    record = new ColumnDocumentProperties(this);
                    record.fillEmpty();
                    this.documentProperties(record);
                    break;
                case 6:
                    record = new DeleteCostDocumentProperties(this);
                    record.fillEmpty();
                    this.documentProperties(record);
                    break;
            }
        }.bind(this));
        if (editMode) {
            var model = viewModel.multiCommandExecute("selectedRowRecord");
            this.dynamicDocumentType(model.dynamicDocumentType());
            this.dynamicDocumentType.valueHasMutated()
            this.documentProperties().fillModel(model.documentProperties(), true);
            this.lastPriority(res);
        }
        else {
            this.itemsCount(0);
            this.stateType(1);
            this.priority(res + 1);
            this.lastPriority(res + 1);
        }
        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, "DynamicDocument", "title", "remotePlaceHolder"] }
            }),
            dynamicDocumentType: self.dynamicDocumentType.extend({
                required: true
            }),
            code: self.code.extend({
                required: {
                    onlyIf: function () {
                        return self.editMode() === true;
                    }
                },
                remoteIsUniqueRule: { params: [self.id, "DynamicDocument", "code", "remotePlaceHolder"] },
                numberOnly: null,
                maxLength: {
                    params: 5,
                    message: "کد سند باید حداکثر 5 کاراکتر عددی باشد"
                }
            }),
            priority: self.priority.extend({
                required: true,
                number: true
            }),
            documentProperties: self.documentProperties
        });
    }
    validateForm() {
        var array = [];
        for (var p2 in this.validationObject()) {
            if (this.validationObject().hasOwnProperty(p2)) {
                var target2 = this.validationObject()[p2];
                var text;
                try {
                    text = _h.getLocalizedText(p2);
                } catch (e) {
                    text = undefined;
                }
                if (!_h.isNullOrEmpty(text) && !_h.isNullOrEmpty(target2.error()))
                    array.push({ propName: p2, propFaName: text, error: target2.error() });

                if (p2 === "documentProperties" && !_h.isNullOrEmpty(target2())) {
                    var list = target2().validateForm();
                    for (var i = 0; i < list.length; i++) {
                        array.push(list[i]);
                    }
                }
                this.errorTree(array);
            }
        }

        if (!this.validationObject.isValid()) {
            this.validationObject.errors.showAllMessages();
            return false;
        }
        return true;
    };
    clickSection(model, event) {
        if (!event)
            return;
        var loc = $(event.target).attr("data-loc");
        this.section(loc);
    };
    toServer() {
        return {
            id: this.id(),
            code: this.code(),
            dynamicDocumentType: this.dynamicDocumentType(),
            stateType: this.stateType(),
            title: this.title(),
            priority: this.priority(),
            description: this.description(),
            folderId: this.folderId(),
            documentProperties: this.documentProperties().toServer()
        };
    }
    createForm() {
        const controls = [
            this.createLine({ t: 'tm', templateName: 'dynamicdocument-form-t' }, undefined, true, 30, 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() === true, click: this.parentVM.edit },
                    { name: 'cancel', click: _h.kocnx().closeForm }]
            }
        });
    }
}
export function ComputationalDocumentProperties(parent) {
    var self = this;
    self.parentForm = parent;
    self.sourceTableId = ko.observable();
    self.sourceTableCondition = ko.observable();
    self.sourceTableConditionModel = ko.observable();
    self.sourceFieldFormulas = ko.observableArray();
    self.sourceTableSelectList = {};
    self.sourceTableColSelectList = {};
    self.formulaColSelectList = [];
    self.formulaTarget = ko.observable();
    self.onSelect = function (controlName) {
        var item, target;
        switch (controlName) {
            case "sourceTableId":
                if (self.sourceTableId()) {
                    item = self.sourceTableSelectList[self.sourceTableId()];
                    self.sourceTableColSelectList = {};
                    self.formulaColSelectList = [];
                    if (_h.any(item.fields())) {
                        for (var i = 0; i < item.fields().length; i++) {
                            target = item.fields()[i];
                            self.sourceTableColSelectList[target.value()] = target;
                            if (target.dataType() === 0 || target.dataType() === 2 || target.dataType() === 3) {
                                self.formulaColSelectList.push(target);
                            }
                        }
                    }
                }
                self.sourceTableConditionModel().reset();
                self.sourceFieldFormulas.removeAll();
                break;
        }
    };
    self.fillModel = function (model) {
        self.fillLists();
        self.sourceTableId(model.sourceTableId);
        self.onSelect("sourceTableId");
        self.sourceTableCondition(model.sourceTableCondition);
        var translator = new PhraseTranslator();
        var sourceModel = translator.getModel(model.sourceTableCondition);
        var record = new TableConditionSet(self, "source");
        record.fillModel(sourceModel, model.sourceTableConditionAggregation);
        self.sourceTableConditionModel(record);
        if (_h.any(model.sourceFieldFormulas))
            for (var i = 0; i < model.sourceFieldFormulas.length; i++) {
                var rec = new SourceFieldFormula(self);
                rec.fillModel(model.sourceFieldFormulas[i]);
                self.sourceFieldFormulas.push(rec);
            }
    };
    self.fillEmpty = function (model) {
        var record = new TableConditionSet(self, "source");
        record.fillEmpty(undefined);
        self.sourceTableConditionModel(record);
        self.fillLists();
    };
    self.fillLists = function () {
        self.sourceTableSelectList = {};
        for (var i = 0; i < _h.kocnx().ddvm().allTableSelectList().length; i++) {
            var p = _h.kocnx().ddvm().allTableSelectList()[i];
            self.sourceTableSelectList[p.value()] = p;
        }
    };
    self.validationObject = ko.validatedObservable({
        sourceTableId: self.sourceTableId.extend({
            required: true,
        }),
        sourceFieldFormulas: self.sourceFieldFormulas.extend({
            atleastOnesourceFieldFormulas: true
        })
    });
    self.toServer = function () {
        var array = [];
        if (_h.any(self.sourceFieldFormulas()))
            for (var i = 0; i < self.sourceFieldFormulas().length; i++) {
                var target = self.sourceFieldFormulas()[i];
                array.push({ fieldOrder: target.fieldOrder(), computeType: target.computeType(), value: target.value() });
            }
        return {
            sourceTableId: self.sourceTableId(),
            sourceFieldFormulas: array,
            sourceTableCondition: self.sourceTableCondition()
        };
    };
    self.addSourceFieldFormula = function () {
        var rec = new SourceFieldFormula(self);
        self.sourceFieldFormulas.push(rec);
    };
    self.showResultBtn = ko.computed(function () {
        return !_h.isNullOrEmpty(self.sourceTableId());
    });
    self.validateForm = function () {
        var array = [];
        for (var p2 in self.validationObject()) {
            if (self.validationObject().hasOwnProperty(p2)) {
                var target2 = self.validationObject()[p2];
                var text;
                try {
                    text = _h.getLocalizedText(p2);
                } catch (e) {
                    text = undefined;
                }
                if (!_h.isNullOrEmpty(text) && !_h.isNullOrEmpty(target2.error()))
                    array.push({ propName: p2, propFaName: text, error: target2.error() });
                if (_h.isNullOrEmpty(text) && !_h.isNullOrEmpty(target2())
                    && !_h.isNullOrEmpty(target2()["validateForm"])) {
                    array.push({ propName: p2, propFaName: text, children: target2().validateForm() });
                }
            }
        }

        if (self.sourceTableConditionModel().conditions().length > 1) {
            array.push({
                propName: "sourceTableConditionModel", propFaName: "شروط مبدا",
                children: self.sourceTableConditionModel().validateForm()
            });
        }
        return array;
    };
}
export function DestinationAccountCode(parent) {
    var self = this;
    self.parentForm = parent;
    self.value = ko.observable();
    self.accountCode = ko.observable();
    self.accountName = ko.observable();
    self.withFlow = ko.observable();
    self.defaultItem = ko.observable();
    self.onSelectAutocomplete = function (name, value) {
        self.accountCode(value);
    };
    self.toggleWithFlow = function () {
        self.withFlow(!self.withFlow());
    };
    self.fillModel = function (model) {
        self.value(model.value);
        self.accountCode(model.accountCode);
        self.accountName(model.accountName);
        self.withFlow(model.withFlow);
        self.defaultItem(model.default);
    };
}
export function ComputationalTableCondition(parent, parentSet, target) {
    var self = this;
    self.parentForm = parent;
    self.parentSet = parentSet;
    self.target = target;
    self.leftListName = "sourceTableColSelectList";
    self.leftSideDataType = ko.observable();
    self.rightSideDataTypes = ko.observableArray([]);
    self.rightSideDataType = ko.observable();
    self.rightSide = ko.observable();
    self.leftSide = ko.observable();
    self.operator = ko.observable();
    self.enumItems = {};
    self.rightSideItems = ko.observableArray();
    self.onSelect = function (controlName) {
        switch (controlName) {
            case "leftSide":
                if (!_h.isEmpty(self.leftSide())) {
                    var item = self.parentForm.sourceTableColSelectList[self.leftSide()];
                    self.leftSideDataType(item.dataType());
                }
                else {
                    self.leftSideDataType(undefined);
                }
                self.rightSideDataType(undefined);
                self.rightSide(undefined);
                self.operator(undefined);
                self.parentSet.translatePhrase();
                break;
            case "operator":
                self.rightSideDataTypes.removeAll();
                self.rightSideDataType(undefined);
                self.rightSide(undefined);
                if (!_h.isNullOrEmpty(self.operator())) {
                    switch (self.operator()) {
                        case 1:
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                        case 6:
                            var selected = null;
                            for (var i = 0; i < tableconditiondataTypes.length; i++) {
                                if (tableconditiondataTypes[i].value === self.leftSideDataType()) {
                                    selected = tableconditiondataTypes[i];
                                }
                            }

                            if (selected && selected.value === 7)
                                self.refreshEnumItems();


                            if (self.leftSideDataType() === 0 || self.leftSideDataType() === 2 || self.leftSideDataType() === 3) {
                                self.rightSideDataTypes.push(selected);
                                self.rightSideDataTypes.push(tableconditiondataTypes[15]);
                            } else {
                                self.rightSideDataType(selected.value);
                            }
                            break;
                        case 7:
                        case 8:
                        case 9:
                        case 10:
                            self.rightSideDataType(13);
                            break;
                        case 11:
                            self.rightSideDataType(1);
                            break;
                        case 12:
                        case 13:
                            if (!_h.isNullOrEmpty(self.leftSideDataType())) {
                                var dataTypeItem = _h.getEnumItem(dataTypes, self.leftSideDataType());
                                switch (dataTypeItem.value) {
                                    case 0:
                                        self.rightSideDataTypes.push(tableconditiondataTypes[0]);
                                        self.rightSideDataTypes.push(tableconditiondataTypes[12]);
                                        break;
                                    case 1:
                                        self.rightSideDataType(9);
                                        break;
                                    case 4:
                                        self.rightSideDataType(10);
                                        break;
                                    case 7:
                                        self.rightSideDataType(12);
                                        self.refreshEnumItems();
                                        break;
                                }
                            }
                            break;
                        case 14:
                            self.rightSideDataType(15);
                            break;
                        case 15:
                        case 16:
                            self.rightSideDataType(20);
                            break;
                    }
                }
                self.parentSet.translatePhrase();
                break;
        }
    };
    self.filterOperator = function (item) {
        return item.dataTypes.indexOf(self.leftSideDataType()) !== -1;
    };
    self.createCondtionPhrase = function () {
        var ph = "[table:'" + self.leftSide() + "']";
        ph += _h.getEnumEnText(dynamicConditionalOperators2, self.operator());
        var val = self.rightSideDataType();
        var right = "";
        switch (val) {
            case 0:
                right = "int:'";
                break;
            case 1:
                right = "text:'";
                break;
            case 2:
                right = "decimal:'";
                break;
            case 3:
                right = "money:'";
                break;
            case 4:
                right = "date:'";
                break;
            case 7:
                right = "enum:'";
                break;
            case 8:
                right = "table:'";
                break;
            case 9:
                right = "listtext:'";
                break;
            case 10:
                right = "listdate:'";
                break;
            case 12:
                right = "listenum:'";
                break;
            case 14:
                right = "listint:'";
                break;
            case 15:
                right = "pattern:'";
                break;
            case 20:
                right = "likepattern:'";
                break;
            case 21:
                right = "formula:'";
                break;
            case null:
            case undefined:
            case "":
            case "-":
            case 13:
                return ph;
        }
        if (self.rightSide() !== undefined)
            ph += "[" + right + self.rightSide() + "']";
        else
            ph += "[" + right + "']";
        return ph;
    };
    self.fillModel = function (model) {
        if (model) {
            self.leftSide(Number(model.leftSide));
            if (!_h.isEmpty(self.leftSide())) {
                var item = self.parentForm.sourceTableColSelectList[self.leftSide()];
                self.leftSideDataType(item.dataType());
            }
            self.operator(model.operator.value);
            self.rightSideDataType(model.rightSide.type);
            self.rightSide(model.rightSide.value);
            if (model.rightSide.type === 12) {
                var values = _h.splitStringList(model.rightSide.value);
                self.rightSideItems(values);
            }
        }
    }
    self.rightSide.subscribe(function () {
        self.parentSet.translatePhrase();
    });
    self.refreshEnumItems = function () {
        self.enumItems = {};
        var keys = Object.keys(self.parentForm.sourceTableColSelectList);
        if (keys && keys.length)
            for (var j = 0; j < keys.length; j++) {
                var k = self.parentForm.sourceTableColSelectList[keys[j]];
                if (k.value() === self.leftSide() && k.enumValues().length) {
                    for (var l = 0; l < k.enumValues().length; l++) {
                        var target = k.enumValues()[l];
                        self.enumItems[target.value()] = target;
                    }
                }
            }
        self.rightSide(undefined);
    };
    self.rightSideDataType.subscribe(function () {
        self.parentSet.translatePhrase();
    });
    self.rightSideItems.subscribe(function (newValue) {
        if (!_h.isNullOrEmpty(newValue)) {
            var value = _h.concatStringList(newValue);
            self.rightSide(value);
        }
    });
    self.validationObject = ko.validatedObservable({
        rightSide: self.rightSide.extend({
            required: {
                onlyIf: function () {
                    var hasLeftSideValue = !_h.isNullOrEmpty(self.leftSide()) && self.leftSide() !== "";
                    var hasOperatorValue = !_h.isNullOrEmpty(self.operator()) && self.operator() !== "";
                    var reqiureVal = !_h.isNullOrEmpty(self.rightSideDataType()) &&
                        self.rightSideDataType() !== "" && self.rightSideDataType() !== 13;
                    return (hasLeftSideValue || hasOperatorValue) && reqiureVal;
                }
            }
        }),
        operator: self.operator.extend({
            required: {
                onlyIf: function () {
                    return !_h.isNullOrEmpty(self.leftSide()) && self.leftSide() !== "";
                }
            }
        })
    });
    self.reset = function () {
        self.leftSide(undefined);
        self.leftSideDataType(undefined);
        self.operator(undefined);
        self.rightSideDataType(undefined);
        self.rightSide(undefined);
    };
    self.onChangeFormula = function (value, name) {
        self.rightSide(value);
    };
}
export function SourceFieldFormula(parent) {
    var self = this;
    self.parentForm = parent;
    self.fieldOrder = ko.observable();
    self.value = ko.observable();
    self.values = ko.observableArray();
    self.computeType = ko.observable();
    self.leftFilterTypes = [];
    self.onSelect = function (controlName) {
        var item, target;
        switch (controlName) {
            case "fieldOrder":
                self.computeType(undefined);
                self.value(undefined);
                break;
            case "computeType":
                item = self.parentForm.sourceTableColSelectList[self.fieldOrder()];
                if (self.computeType() === 1) {
                    switch (item.dataType()) {
                        case 0:
                            self.leftFilterTypes = [0];
                            break;
                        case 2:
                            self.leftFilterTypes = [2];
                            break;
                        case 3:
                            self.leftFilterTypes = [3];
                            break;
                        case 1:
                            self.leftFilterTypes = [0, 1, 2, 3];
                            break;
                    }
                }
                self.value(undefined);
                break;
        }
    };
    self.fillModel = function (model) {
        self.fieldOrder(model.fieldOrder);
        self.computeType(model.computeType);
        self.onSelect("computeType");
        switch (model.computeType) {
            case 0:
                self.value(model.value);
                break;
            case 1:
                if (_h.any(model.value) && model.computeType === 1)
                    for (var i = 0; i < model.value.length; i++) {
                        self.values.push(model.value[i]);
                    }
                break;
        }
    };
    self.values.subscribe(function (newValue) {
        if (!_h.isNullOrEmpty(newValue)) {
            self.value(newValue);
        } else {
            self.value(undefined);
        }
    });
    self.onChangeFormula = function (value, name) {
        self.value(value);
    };
    self.filterLeft = function (item) {
        return self.leftFilterTypes.indexOf(item.dataType) !== -1;
    };
}
export function TableConditionOperator(model) {
    var self = this;
    self.id = model.id;
    self.text = model.text;
    self.data = model.data;
    self.after = model.after;
    self.enabled = ko.observable(false);
}
export function SourceTableData(model) {
    var self = this;
    self.selected = ko.observable(false);
    self.id = ko.observable(model.id);
    self.stateType = ko.observable(model.stateType);
    for (var j = 0; j < model.cells.length; j++) {
        var field = model.cells[j];
        self[field.order] = field.value;
    }
    self.createTagId = ko.pureComputed(function () {
        return "SourceTableTD-" + self.id();
    });
    self.styleRowValue = ko.pureComputed(function () {
        if (self.stateType() === 0)
            return 'color: #ccc;';
        return '';
    });
}
export function SourceTableDataViewModel(dataModel) {
    var self = this;
    self.caption = ko.observable();
    self.clickCounter = ko.observable(0);
    self.hasDetailPart = ko.observable(true);
    self.dataModel = dataModel;
    self.init = function () {
        self.tableName(self.dataModel.sourceTable.text());
        self.tableCode(self.dataModel.sourceTable.code());
        self.sourceTableId(self.dataModel.sourceTable.value());
        self.sourceTableCondition(self.dataModel.sourceTableCondition);
        self.dynamicDocumentType(self.dataModel.type);
        switch (self.dataModel.type) {
            case 1:
                self.caption(_h.getLocalizedText("sourceTable"));
                self.hasDetailPart(false);
                break;
            case 4:
                self.caption(_h.getLocalizedText("calculationTable"));
                self.sourcePeriodId(self.dataModel.sourcePeriodId);
                self.calculationPeriodId(self.dataModel.calculationPeriodId);
                break;
            default:
                self.caption(_h.getLocalizedText("expenseCenterTable"));
                self.treeId(self.dataModel.treeId);
                self.nodeIdList(self.dataModel.nodeIdList);
                self.documentCode(self.dataModel.documentCode);
                break;
        }
        self.fillTableProperties();
        self.getRecords();
    };
    self.createExcelFileBtn = function () {
        var filterModel = self.createFilterByModel();
        var cols = [];
        ko.utils.arrayFilter(self.tableProperties(), function (item) {
            if (item.visibleCol())
                cols.push(item.name);
        });
        var model = {
            controllerName: 50,
            inputData: filterModel
        };
        model.inputData.columns = cols;
        _h.kocnx().createExcel(model);
    }
    self.createFiltersList = function () {
        var array;
        switch (self.dataModel.type) {
            case 1:
                array = [
                    { name: "sourceTableId" },
                    { name: "sourceTableCondition" },
                    { name: "dynamicDocumentType" }
                ];
                break;
            case 4:
                array = [
                    { name: "sourceTableId" },
                    { name: "sourceTableCondition" },
                    { name: "sourcePeriodId" },
                    { name: "calculationPeriodId" },
                    { name: "dynamicDocumentType" }
                ];
                break;
            default:
                array = [
                    { name: "sourceTableId" },
                    { name: "documentCode" },
                    { name: "sourceTableCondition" },
                    { name: "treeId" },
                    { name: "nodeIdList", type: "list" },
                    { name: "dynamicDocumentType" }
                ];
                break;
        }

        return array;
    }
    self.createColList = function () {
        var table = self.dataModel.sourceTable;
        var array = [];
        if (!_h.isNullOrEmpty(table.fields())) {
            var objId = {
                fa: '#',

                colName: 'id',
                tablecol: false,
                visibleCol: false,
                sortDir: "None",
                alias: null,
                type: "template",
                templateName: "checkbox-table-template"
            };
            array.push(objId);
            for (var i = 0; i < table.fields().length; i++) {
                var field = table.fields()[i];
                var obj = {
                    fa: field.text(),

                    colName: field.value().toString(),
                    tablecol: true,
                    visibleCol: true,
                    sortDir: "None",
                    alias: null,
                    type: "string"
                };
                if (i === 0)
                    obj.sortDir = "Ascending";
                if (i === 0 || i === 1 || i === 2)
                    obj.visibleItem = true;
                array.push(obj);
            }
        }
        return array;
    }
    self.changeChildModel = function (target) {
        if (!self.dataModel.expenseCenterTable ||
            _h.isNullOrEmpty(self.dataModel.expenseCenterTable.value())) {
            self.hasDetailPart(false);
            self.showType("Table");
            self.showBlockType("fullMaster");
            self.iconSize("icon-image");
            return;
        }

        if (self.dataModel.type === 1)
            return;
        var model = new ExpenseCenterTableDataViewModel(self.dataModel);
        model.tableName(self.dataModel.expenseCenterTable.text());
        model.tableCode(self.dataModel.expenseCenterTable.code());
        model.sourceTableId(self.dataModel.sourceTable.value());
        model.sourceTableCondition(self.dataModel.sourceTableCondition);
        model.sourceRowId(target.id());
        var warning = false;
        switch (self.dataModel.type) {
            case 4:
                model.calculationTableId(self.dataModel.expenseCenterTable.value());
                model.calculationTableCondition(self.dataModel.expenseCenterTableCondition);
                model.sourcePeriodId(self.dataModel.sourcePeriodId);
                model.calculationPeriodId(self.dataModel.calculationPeriodId);
                if (!_h.isNullOrEmpty(model.calculationTableId())) {
                    self.childModel(model);
                    self.childModel().init();
                } else {
                    warning = true;
                }
                break;
            default:
                model.documentCode(self.dataModel.documentCode);
                model.treeId(self.dataModel.treeId);
                model.nodeIdList(self.dataModel.nodeIdList);
                if (_h.any(self.dataModel.destinationAccountCodes))
                    for (var i = 0; i < self.dataModel.destinationAccountCodes.length; i++) {
                        var targetp = self.dataModel.destinationAccountCodes[i];
                        model.destinationAccountCodes.push({
                            value: targetp.value(),
                            accountCode: targetp.accountCode(),
                            withFlow: targetp.withFlow(),
                            default: targetp.defaultItem()
                        });
                    }
                model.expenseCenterTableId(self.dataModel.expenseCenterTable.value());
                model.expenseCenterTableCondition(self.dataModel.expenseCenterTableCondition);
                if (!_h.isNullOrEmpty(self.dataModel.expenseCenterTable.value())) {
                    self.childModel(model);
                    self.childModel().init();
                }
                else {
                    warning = true;
                }
                break;
        }
        if (warning && self.clickCounter() < 2) {
            self.clickCounter(self.clickCounter() + 1);
            var text = _h.getApiMessage("ShowExpenseCenterTableCondition");
            _h.failToast(text);
        }
    };
    ko.utils.extend(self, new BaseViewModel({
        entityName: "SourceTableData",
        apiService: {
            actionList: []
        },
        buttons: [
            { name: 'createExcelFile', access: false, icon: 'ExportExcel', cMenu: false },
            { name: 'refresh', access: false, cMenu: false },
            { name: 'tools', access: false, cMenu: false }
        ],
        filters: self.createFiltersList(),
        sortDirection: "Ascending",
        sortProperty: "",
        context: self,
        dynamicCols: true,
        cols: self.createColList(),
        extraParams: [],

        getList: true,
        searchKeyType: "enter",
        styleRow: "styleRowValue",
        tableClass: "table ko-tbl ko-tbl-master",
        tableStyle: "width: 200%; margin-top: 10px; table-layout: initial;font-size:11px;white-space: nowrap;",
        saveState: false,
        selectRow: true
    }));
    self.btnVisibility = ko.computed(function () {
        self.visrefresh(true);
        self.vistools(true);
        self.viscreateExcelFile(true);
    });
}
export function ExpenseCenterTableData(model) {
    var self = this;
    self.selected = ko.observable(false);
    self.id = ko.observable(model.id);
    self.stateType = ko.observable(model.stateType);
    for (var j = 0; j < model.cells.length; j++) {
        var field = model.cells[j];
        self[field.order] = field.value;
    }
    self.createTagId = ko.pureComputed(function () {
        return "ExpenseCenterTD-" + self.id();
    });
    self.styleRowValue = ko.pureComputed(function () {
        if (self.stateType() === 0)
            return 'color: #ccc;';
        return '';
    });
}
export function ExpenseCenterTableDataViewModel(dataModel) {
    var self = this;
    self.dataModel = dataModel;
    self.createExcelFileBtn = function () {
        var filterModel = self.createFilterByModel();
        var cols = [];
        ko.utils.arrayFilter(self.tableProperties(),
            function (item) {
                if (item.visibleCol())
                    cols.push(item.name);
            });
        var model = {
            controllerName: 50,
            inputData: filterModel
        };
        model.inputData.columns = cols;
        _h.kocnx().createExcel(model);
    };
    self.createFiltersList = function () {
        var array;
        if (self.dataModel.type !== 4) {
            array =
                [
                    { name: "sourceTableId" },
                    { name: "documentCode" },
                    { name: "sourceTableCondition" },
                    { name: "treeId" },
                    { name: "nodeIdList", type: "list" },
                    { name: "expenseCenterTableId" },
                    { name: "expenseCenterTableCondition" },
                    { name: "sourceRowId" },
                    { name: "destinationAccountCodes", type: "list" }
                ];
        } else {
            array = [
                { name: "sourceTableId" },
                { name: "sourceTableCondition" },
                { name: "calculationTableId" },
                { name: "calculationTableCondition" },
                { name: "sourceRowId" },
                { name: "sourcePeriodId" },
                { name: "calculationPeriodId" }
            ];
        }
        return array;
    };
    self.createColList = function () {
        var table = self.dataModel.expenseCenterTable;
        var array = [];
        if (!_h.isNullOrEmpty(table.fields())) {
            var objId = {
                fa: '#',

                colName: 'id',
                tablecol: false,
                visibleCol: false,
                sortDir: "None",
                alias: null,
                type: "template",
                templateName: "checkbox-table-template"
            };
            array.push(objId);
            for (var i = 0; i < table.fields().length; i++) {
                var field = table.fields()[i];
                var obj = {
                    fa: field.text(),

                    colName: field.value().toString(),
                    tablecol: true,
                    visibleCol: true,
                    sortDir: "None",
                    alias: null,
                    type: "string"
                };
                if (i === 0)
                    obj.sortDir = "Ascending";

                array.push(obj);
            }
        }


        return array;
    };
    self.init = function () {
        self.fillTableProperties();
        self.getRecords();
    };
    ko.utils.extend(self, new BaseViewModel({
        entityName: "ExpenseCenterTableData",
        apiService: {
            actionList: []
        },
        buttons: [
            { name: 'createExcelFile', access: false, icon: 'ExportExcel', cMenu: false },
            { name: 'refresh', access: false, cMenu: false },
            { name: 'tools', access: false, cMenu: false }
        ],
        filters: self.createFiltersList(),
        sortDirection: "",
        sortProperty: "",
        context: self,
        dynamicCols: true,
        cols: self.createColList(),
        extraParams: [],
        saveState: true,
        searchKeyType: "enter",
        tableClass: "table ko-tbl ko-tbl-child",
        styleRow: "styleRowValue",
        tableStyle: "width: 200%; margin-top: 10px; table-layout: initial;font-size:11px;white-space: nowrap;",
        getList: true,
        selectRow: true
    }));
    self.btnVisibility = ko.computed(function () {
        self.vistools(true);
        self.visrefresh(true);
        self.viscreateExcelFile(true);
    });
}
$(document).on("shown.bs.tab", '.dynamic-document-tab a[data-toggle="tab"]', function () {
    return false;
});
export function AggregationDocumentProperties(parent) {
    var self = this;
    self.parentForm = parent;
    self.sourceTableId = ko.observable();
    self.destinationCalculationType = ko.observable();
    self.sourceTableCondition = ko.observable();
    self.sourceTableConditionModel = ko.observable();
    self.calculationTableId = ko.observable();
    self.calculationTableCondition = ko.observable();
    self.calculationTableConditionModel = ko.observable();
    self.destinationTableId = ko.observable();
    self.destinationTableCondition = ko.observable();
    self.destinationTableConditionModel = ko.observable();
    self.sourcePeriodId = ko.observable();
    self.calculationPeriodId = ko.observable();
    self.destinationValues = ko.observableArray();
    self.destinationKeys = ko.observableArray();
    self.sourceTableSelectList = {};
    self.calculationTableSelectList = {};
    self.destinationTableSelectList = {};
    self.sourceTableColSelectList = {};
    self.calculationTableColSelectList = {};
    self.destinationTableColSelectList = {};
    self.onSelect = function (controlName) {
        var item, target;
        switch (controlName) {
            case "sourceTableId":
                self.sourceTableColSelectList = {};
                if (self.sourceTableId()) {
                    item = self.sourceTableSelectList[self.sourceTableId()];
                    if (_h.any(item.fields())) {
                        for (var i = 0; i < item.fields().length; i++) {
                            target = item.fields()[i];
                            self.sourceTableColSelectList[target.value()] = target;
                        }
                    }
                }
                self.sourceTableConditionModel().reset();
                self.calculationTableConditionModel().reset();
                self.refreshDestinationValues("source");
                self.destinationTableConditionModel().reset("source");
                break;
            case "calculationTableId":
                self.calculationTableColSelectList = {};
                if (self.calculationTableId()) {
                    item = self.calculationTableSelectList[self.calculationTableId()];

                    if (_h.any(item.fields())) {
                        for (var k = 0; k < item.fields().length; k++) {
                            target = item.fields()[k];
                            self.calculationTableColSelectList[target.value()] = target;
                        }
                    }
                }
                self.calculationTableConditionModel().reset();
                self.destinationTableConditionModel().reset("calculation");
                self.refreshDestinationValues("calculation");
                break;
            case "destinationTableId":
                self.destinationTableColSelectList = {};
                if (self.destinationTableId()) {
                    item = self.destinationTableSelectList[self.destinationTableId()];
                    if (_h.any(item.fields())) {
                        for (var l = 0; l < item.fields().length; l++) {
                            target = item.fields()[l];
                            self.destinationTableColSelectList[target.value()] = target;
                        }
                    }
                }
                self.destinationTableConditionModel().reset();
                self.destinationValues.removeAll();
                self.destinationKeys.removeAll();
                break;
        }
    };
    self.destinationKeyFilter = function (item) {
        return self.destinationCalculationType() === 1;
    };
    self.fillEmpty = function () {
        self.fillLists();
        self.destinationCalculationType(1);
        var record = new TableConditionSet(self, "source");
        record.fillEmpty(undefined);
        self.sourceTableConditionModel(record);
        record = new TableConditionSet(self, "calculation");
        record.fillEmpty(undefined);
        self.calculationTableConditionModel(record);
        record = new TableConditionSet(self, "destination");
        record.fillEmpty(undefined);
        self.destinationTableConditionModel(record);
    };
    self.fillModel = function (model) {
        self.fillLists();
        self.sourceTableId(model.sourceTableId);
        self.onSelect("sourceTableId");
        self.calculationTableId(model.calculationTableId);
        self.onSelect("calculationTableId");
        self.destinationTableId(model.destinationTableId);
        self.onSelect("destinationTableId");
        self.destinationCalculationType(model.destinationCalculationType);
        self.onSelect("destinationCalculationType");
        self.sourceTableCondition(model.sourceTableCondition);
        self.calculationTableCondition(model.calculationTableCondition);
        self.destinationTableCondition(model.destinationTableCondition);
        var translator = new PhraseTranslator();
        var sourceModel = translator.getModel(model.sourceTableCondition);
        var calculationModel = translator.getModel(model.calculationTableCondition);
        var destinationModel = translator.getModel(model.destinationTableCondition);

        var record = new TableConditionSet(self, "source");
        record.fillModel(sourceModel, model.sourceTableConditionAggregation);
        self.sourceTableConditionModel(record);
        record = new TableConditionSet(self, "calculation");
        record.fillModel(calculationModel, model.calculationConditionAggregation);
        self.calculationTableConditionModel(record);

        record = new TableConditionSet(self, "destination");
        record.fillModel(destinationModel, model.destinationConditionAggregation);
        self.destinationTableConditionModel(record);

        if (_h.any(model.destinationValues))
            for (var i = 0; i < model.destinationValues.length; i++) {
                var rec = new DestinationValueProperty(self);
                rec.fillModel(model.destinationValues[i]);
                self.destinationValues.push(rec);
            }
        self.destinationKeys(model.destinationKeys);
        self.sourcePeriodId(model.sourcePeriodId);
        self.calculationPeriodId(model.calculationPeriodId);
    };
    self.fillLists = function () {
        self.sourceTableSelectList = {};
        self.destinationTableSelectList = {};
        self.calculationTableSelectList = {};
        for (var i = 0; i < _h.kocnx().ddvm().allTableSelectList().length; i++) {
            var p = _h.kocnx().ddvm().allTableSelectList()[i];
            self.sourceTableSelectList[p.value()] = p;
            self.destinationTableSelectList[p.value()] = p;
            self.calculationTableSelectList[p.value()] = p;
        }
    };
    self.validationObject = ko.validatedObservable({
        sourceTableId: self.sourceTableId.extend({
            required: true,
        }),
        destinationTableId: self.destinationTableId.extend({
            required: true,
        }),
        destinationCalculationType: self.destinationCalculationType.extend({
            required: true
        }),
        destinationValues: self.destinationValues.extend({
            atleastOneDestinationValues: true
        })
    });
    self.refreshDestinationValues = function (loc) {
        if (_h.any(self.destinationValues()))
            for (var i = 0; i < self.destinationValues().length; i++) {
                var target = self.destinationValues()[i];
                if (loc === "source" && target.calculationValueType() === 3)
                    target.resetValue("source");
                if (loc === "calculation" && target.calculationValueType() === 4)
                    target.resetValue("calculation");
            }
    };
    self.addDestinationValue = function () {
        var rec = new DestinationValueProperty(self);
        self.destinationValues.push(rec);
    };
    self.showResultBtn = ko.computed(function () {
        return !_h.isNullOrEmpty(self.sourceTableId());
    });
    self.toServer = function () {
        var dValues = [];
        for (var i = 0; i < self.destinationValues().length; i++) {
            var target = self.destinationValues()[i];
            dValues.push({
                destinationField: target.destinationField(),
                calculationValueType: target.calculationValueType(),
                value: target.value(),
                valueFrom: target.valueFrom(),
                valueTo: target.valueTo()
            });
        }
        return {
            sourceTableId: self.sourceTableId(),
            sourceTableCondition: self.sourceTableCondition(),
            calculationTableId: self.calculationTableId(),
            calculationTableCondition: self.calculationTableCondition(),
            destinationTableId: self.destinationTableId(),
            destinationTableCondition: self.destinationTableCondition(),
            destinationValues: dValues,
            destinationCalculationType: self.destinationCalculationType(),
            destinationKeys: self.destinationKeys(),
            sourcePeriodId: self.sourcePeriodId(),
            calculationPeriodId: self.calculationPeriodId()
        };
    };
    self.validateForm = function () {
        var array = [];
        for (var p2 in self.validationObject()) {
            if (self.validationObject().hasOwnProperty(p2)) {
                var target2 = self.validationObject()[p2];
                var text;
                try {
                    text = _h.getLocalizedText(p2);
                    if (p2 === "destinationValues") {
                        text = "مقادیر مقصد";
                    }

                } catch (e) {
                    text = undefined;
                }
                if (!_h.isNullOrEmpty(text) && !_h.isNullOrEmpty(target2.error()))
                    array.push({ propName: p2, propFaName: text, error: target2.error() });
                if (_h.isNullOrEmpty(text) && !_h.isNullOrEmpty(target2())
                    && !_h.isNullOrEmpty(target2()["validateForm"])) {
                    array.push({ propName: p2, propFaName: text, children: target2().validateForm() });
                }
            }
        }

        var errors;
        if (self.sourceTableConditionModel().conditions().length > 1) {
            errors = self.sourceTableConditionModel().validateForm();
            if (errors.length)
                array.push({
                    propName: "sourceTableConditionModel",
                    propFaName: "شروط مبدا",
                    children: errors
                });
        }

        if (self.calculationTableConditionModel().conditions().length > 1) {
            errors = self.calculationTableConditionModel().validateForm();
            if (errors.length)
                array.push({
                    propName: "calculationTableConditionModel", propFaName: "شروط محاسبات",
                    children: errors
                });
        }
        if (self.destinationTableConditionModel().conditions().length > 1) {
            errors = self.destinationTableConditionModel().validateForm();
            if (errors.length)
                array.push({
                    propName: "destinationTableConditionModel", propFaName: "شروط مقصد",
                    children: errors
                });
        }

        return array;
    };
}
export function DestinationValueProperty(parent) {
    var self = this;
    self.parentForm = parent;
    self.destinationField = ko.observable();
    self.destinationFieldDataType = ko.observable();
    self.calculationValueType = ko.observable();
    self.value = ko.observable();
    self.leftCaption = ko.observable();
    self.leftState = ko.observable(false);
    self.leftControl = ko.observable();
    self.valueFrom = ko.observable();
    self.valueTo = ko.observable();
    self.onSelect = function (controlName) {
        switch (controlName) {
            case "destinationField":
                var item = self.parentForm.destinationTableColSelectList[self.destinationField()];
                if (item)
                    self.destinationFieldDataType(item.dataType());
                self.leftState(false);
                self.leftControl(0);
                self.calculationValueType(undefined);
                self.value("");
                break;
            case "calculationValueType":
                switch (self.calculationValueType()) {
                    case 1:
                    case 2:
                        self.leftState(false);
                        self.leftControl(0);
                        break;
                    case 3:
                        self.leftCaption("جدول مبدا");
                        self.leftState(true);
                        self.leftControl(1);
                        if (_h.isNullOrEmpty(self.value()))
                            self.value(null);
                        break;
                    case 4:
                    case 5:
                    case 6:
                    case 8:
                    case 9:
                        self.leftCaption("جدول محاسبات");
                        self.leftControl(3);
                        self.leftState(true);
                        if (_h.isNullOrEmpty(self.value()))
                            self.value(null);
                        break;
                    case 7:
                        self.leftControl(2);
                        self.leftState(true);
                        self.leftCaption("مقدار");
                        break;
                }
                break;
        }
    };
    self.filterCalculationValueType = function (item) {
        if (item.dataTypes.indexOf(self.destinationFieldDataType()) !== -1)
            return true;
        if (item.value === 1 && self.parentForm.destinationCalculationType() === 1)
            return true;
        return false;
    };
    self.filterValue = function (item) {
        if (self.destinationFieldDataType() === item.dataType) {
            return true;
        }
        return false;
    };
    self.fillModel = function (model) {
        self.destinationField(model.destinationField);
        self.onSelect("destinationField");
        var item = self.parentForm.destinationTableColSelectList[self.destinationField()];
        if (item)
            self.destinationFieldDataType(item.dataType());
        self.calculationValueType(model.calculationValueType);
        self.onSelect("calculationValueType");
        self.value(model.value);
        self.valueFrom(model.valueFrom);
        self.valueTo(model.valueTo);
    };
    self.showFunctionsBtn = ko.computed(function () {
        if (!_h.isNullOrEmpty(self.destinationField()) &&
            (self.calculationValueType() === 3 || self.calculationValueType() === 4)) {
            var item = self.parentForm.destinationTableColSelectList[self.destinationField()];
            return item.dataType() === 1;
        }
        return false;
    });
    self.resetValue = function () {
        self.value(undefined);
    };
}
export function ApportionmentDocumentProperties(parent) {
    var self = this;
    self.parentForm = parent;
    self.effectiveDate = ko.observable();
    self.sourceTableId = ko.observable();
    self.sourceTableCondition = ko.observable();
    self.sourceTableConditionModel = ko.observable();
    self.treeId = ko.observable();
    self.nodeIdList = ko.observableArray();
    self.nodes = ko.observableArray();
    self.expenseCenterTableId = ko.observable();
    self.expenseCenterTableCondition = ko.observable();
    self.expenseCenterTableConditionModel = ko.observable();
    self.apportionBase = ko.observable();
    self.destinationTableId = ko.observable();
    self.otherFields = ko.observableArray();
    self.destinationAccountCodes = ko.observableArray();
    self.referenceColumn = ko.observable();
    self.apportionAccountType = ko.observable();
    self.onSelect = function (controlName) {
        var item, target;
        switch (controlName) {
            case "sourceTableId":
                if (self.sourceTableId()) {
                    item = self.sourceTableSelectList[self.sourceTableId()];
                    self.sourceTableColSelectList = {};
                    if (item && _h.any(item.fields())) {
                        for (var i = 0; i < item.fields().length; i++) {
                            target = item.fields()[i];
                            self.sourceTableColSelectList[target.value()] = target;
                        }
                    }
                }
                self.sourceTableConditionModel().reset();
                self.expenseCenterTableConditionModel().reset();
                self.checkotherFieldsSource();
                break;
            case "expenseCenterTableId":
                item = self.expenseCenterTableSelectList[self.expenseCenterTableId()];
                if (!_h.isNullOrEmpty(item)) {
                    self.expenseCenterTableColSelectList = {};
                    self.apportionBaseTableSelectList = {};
                    self.apportionBaseTableSelectList[0] =
                        new ColumnSelectItem({ text: "تساوی", value: 0, primary: false, dataType: 10 });
                    if (item && _h.any(item.fields())) {
                        for (var k = 0; k < item.fields().length; k++) {
                            target = item.fields()[k];
                            self.expenseCenterTableColSelectList[target.value()] = target;
                            if (target.dataType() === 0 || target.dataType() === 2 || target.dataType() === 3)
                                self.apportionBaseTableSelectList[target.value()] = target;
                        }
                    }
                }
                if (self.destinationAccountCodes().length > 1) {
                    var defItem1 = self.destinationAccountCodes()[0];
                    self.destinationAccountCodes.removeAll();
                    self.destinationAccountCodes.push(defItem1);
                }
                self.expenseCenterTableConditionModel().reset();
                self.checkotherFieldsSource();
                break;
            case "destinationTableId":
                if (self.destinationTableId()) {
                    item = self.destinationTableSelectList[self.destinationTableId()];
                    self.destinationTableColSelectList = {};
                    if (_h.any(item.fields())) {
                        for (var j = 0; j < item.fields().length; j++) {
                            target = item.fields()[j];
                            self.destinationTableColSelectList[target.value()] = target;
                        }
                    }
                }
                self.otherFields.removeAll();
                self.checkotherFieldsSource();
                break;
        }
    };
    self.fillModel = function (model) {
        self.fillLists();
        self.effectiveDate(model.effectiveDate);
        self.sourceTableId(model.sourceTableId);
        self.onSelect("sourceTableId");
        self.expenseCenterTableId(model.expenseCenterTableId);
        self.onSelect("expenseCenterTableId");
        self.sourceTableCondition(model.sourceTableCondition);
        self.expenseCenterTableCondition(model.expenseCenterTableCondition);
        self.destinationTableId(model.destinationTableId);
        self.onSelect("destinationTableId");
        if (_h.isNullOrEmpty(model.referenceColumn) || model.referenceColumn === 0)
            self.referenceColumn(null);
        else {
            self.referenceColumnsub.suspend();
            self.referenceColumn(model.referenceColumn);
            self.referenceColumnsub.unsuspend();
        }
        self.treeId(model.treeId);
        self.nodeIdList(model.nodeIdList);
        self.nodes(model.nodes);
        self.apportionBase(model.apportionBase);
        var translator = new PhraseTranslator();
        var sourceModel = translator.getModel(model.sourceTableCondition);
        var expenseModel = translator.getModel(model.expenseCenterTableCondition);
        var record = new TableConditionSet(self, "source");
        record.fillModel(sourceModel, model.sourceTableConditionAggregation);
        self.sourceTableConditionModel(record);
        record = new TableConditionSet(self, "expenseCenter");
        record.fillModel(expenseModel, model.expenseTableConditionAggregation);
        self.expenseCenterTableConditionModel(record);
        self.destinationAccountCodes.removeAll();
        if (_h.any(model.destinationAccountCodes))
            for (var i = 0; i < model.destinationAccountCodes.length; i++) {
                var desacc = new DestinationAccountCode(self);
                desacc.fillModel(model.destinationAccountCodes[i]);
                self.destinationAccountCodes.push(desacc);
            }
        else {
            var defRec = new DestinationAccountCode(self);
            defRec.defaultItem(true);
            defRec.value("پیش فرض");
            self.destinationAccountCodes.push(defRec);
        }

        if (_h.any(model.otherFields)) {
            for (var j = 0; j < model.otherFields.length; j++) {
                var tag = new DestinationFieldProperties(self);
                tag.fillModel(model.otherFields[j]);
                self.otherFields.push(tag);
            }
            self.checkotherFieldsSource();
        }
        self.apportionAccountType(model.apportionAccountType);
    };
    self.addDestinationAccountCode = function () {
        var record = new DestinationAccountCode(self);
        record.defaultItem(false);
        self.destinationAccountCodes.push(record);
    }
    self.removeDestinationAccountCode = function (item) {
        if (!item.defaultItem())
            self.destinationAccountCodes.remove(item);
    }
    self.fillEmpty = function () {
        var activePeriod = _h.kocnx().periodItem();
        self.effectiveDate(activePeriod.te);
        self.fillLists();
        var record = new TableConditionSet(self, "source");
        record.fillEmpty(undefined);
        self.sourceTableConditionModel(record);
        record = new TableConditionSet(self, "expenseCenter");
        record.fillEmpty(undefined);
        self.expenseCenterTableConditionModel(record);
        self.apportionAccountType(0);
        var defRec = new DestinationAccountCode(self);
        defRec.defaultItem(true);
        defRec.value("پیش فرض");
        self.destinationAccountCodes.push(defRec);

    };
    self.onNodeSelect = function (name, list) {
        self.nodeIdList.removeAll();
        self.nodes.removeAll();
        if (_h.any(list))
            for (var i = 0; i < list.length; i++) {
                self.nodeIdList.push(list[i].value);
                self.nodes.push(list[i]);
            }
    };
    self.sourceTableSelectList = {};
    self.destinationTableSelectList = {};
    self.apportionBaseTableSelectList = {};
    self.expenseCenterTableSelectList = {};
    self.sourceTableColSelectList = {};
    self.expenseCenterTableColSelectList = {};
    self.destinationTableColSelectList = {};
    self.fillLists = function () {
        self.sourceTableSelectList = {};
        self.destinationTableSelectList = {};
        self.expenseCenterTableSelectList = {};
        if (self.parentForm.dynamicDocumentType() === 3)
            self.destinationTableSelectList[""] = { text: "هیچکدام", value: "", tableRole: 0 };

        for (var i = 0; i < _h.kocnx().ddvm().allTableSelectList().length; i++) {
            var p = _h.kocnx().ddvm().allTableSelectList()[i];
            if (p.tableRole() === 1 || p.tableRole() === 2)
                self.sourceTableSelectList[p.value()] = p;
            if (p.tableRole() === 2)
                self.destinationTableSelectList[p.value()] = p;
            if (p.tableRole() === 3)
                self.expenseCenterTableSelectList[p.value()] = p;

        }
    };
    self.referenceColumnsub = self.referenceColumn.supsendableSubscribe(function (newValue) {
        if (newValue !== undefined && newValue !== null) {
            if (self.destinationAccountCodes().length > 1) {
                var defItem = self.destinationAccountCodes()[0];
                self.destinationAccountCodes.removeAll();
                self.destinationAccountCodes.push(defItem);
            }
        }
        if (newValue === undefined || newValue === null) {
            if (self.destinationAccountCodes().length > 1) {
                var defItem1 = self.destinationAccountCodes()[0];
                self.destinationAccountCodes.removeAll();
                self.destinationAccountCodes.push(defItem1);
            }
        }
    });
    self.addOtherField = function () {
        var model = new DestinationFieldProperties(self);
        model.fillEmpty(self.sourceTableId(), self.expenseCenterTableId());
        self.otherFields.push(model);
    };
    self.removeOtherField = function (item) {
        self.otherFields.remove(item);
    };
    self.otherFieldsSourceSelectList = ko.observableArray();
    self.checkotherFieldsSource = function () {
        if (self.otherFieldsSourceSelectList().length > 0)
            self.otherFieldsSourceSelectList.removeAll();
        var hasSourceValue = !_h.isNullOrEmpty(self.sourceTableId()) && self.sourceTableId() !== "";
        var hasexpenseCenterValue =
            !_h.isNullOrEmpty(self.expenseCenterTableId()) && self.expenseCenterTableId() !== "";
        if (hasSourceValue)
            self.otherFieldsSourceSelectList.push(new SelectItem({ text: "جدول مبدا", value: self.sourceTableId() }));
        if (hasexpenseCenterValue)
            self.otherFieldsSourceSelectList.push(new SelectItem({
                text: "جدول هزینه",
                value: self.expenseCenterTableId()
            }));
    };
    self.validationObject = ko.validatedObservable({
        effectiveDate: self.effectiveDate.extend({
            required: true,
            validation: [{
                validator: function (val, someOtherVal) {
                    var activePeriod = _h.kocnx().periodItem();
                    var start = new Date(activePeriod.ts);
                    var timeEnd = new Date(activePeriod.te);
                    var date = new Date(val);
                    return date >= start && date <= timeEnd;
                },
                message: 'تاریخ موثر سند باید در بازه تاریخ شروع و پایان دوره مالی جاری باشد'
            }]
        }),
        sourceTableId: self.sourceTableId.extend({
            required: true,
        }),
        expenseCenterTableId: self.expenseCenterTableId.extend({
            required: {
                onlyIf: function () { return self.parentForm.dynamicDocumentType() === 2; }
            },
        }),
        destinationTableId: self.destinationTableId.extend({
            required: true,
        }),
        apportionBase: self.apportionBase.extend({
            required: {
                onlyIf: function () { return self.parentForm.dynamicDocumentType() === 2; }
            },
        })
    });
    self.showResultBtn = ko.computed(function () {
        return !_h.isNullOrEmpty(self.sourceTableId());
    });
    self.toServer = function () {
        var destinationACodes = [];
        if (_h.any(self.destinationAccountCodes()))
            for (var i = 0; i < self.destinationAccountCodes().length; i++) {
                var target = self.destinationAccountCodes()[i];
                destinationACodes.push({
                    value: target.value(),
                    accountCode: target.accountCode(),
                    withFlow: target.withFlow(),
                    default: target.defaultItem()
                });
            }
        var otherFields = [];
        if (_h.any(self.otherFields()))
            for (var j = 0; j < self.otherFields().length; j++) {
                var otherField = self.otherFields()[j];
                var json = ko.toJS(otherField);
                json.parentForm = null;
                otherFields.push(json);
            }
        return {
            destinationAccountCodes: destinationACodes,
            effectiveDate: self.effectiveDate(),
            sourceTableId: self.sourceTableId(),
            sourceTableCondition: self.sourceTableCondition(),
            treeId: self.treeId(),
            nodeIdList: self.nodeIdList(),
            referenceColumn: self.referenceColumn(),
            expenseCenterTableId: self.expenseCenterTableId(),
            expenseCenterTableCondition: self.expenseCenterTableCondition(),
            apportionBase: self.apportionBase(),
            destinationTableId: self.destinationTableId(),
            otherFields: otherFields,
            apportionAccountType: self.apportionAccountType()
        };
    };
    self.validateForm = function () {
        var array = [];
        for (var p2 in self.validationObject()) {
            if (self.validationObject().hasOwnProperty(p2)) {
                var target2 = self.validationObject()[p2];
                var text;
                try {
                    text = _h.getLocalizedText(p2);
                } catch (e) {
                    text = undefined;
                }
                if (!_h.isNullOrEmpty(text) && !_h.isNullOrEmpty(target2.error()))
                    array.push({ propName: p2, propFaName: text, error: target2.error() });
                if (_h.isNullOrEmpty(text) && !_h.isNullOrEmpty(target2())
                    && !_h.isNullOrEmpty(target2()["validateForm"])) {
                    array.push({ propName: p2, propFaName: text, children: target2().validateForm() });
                }
            }
        }


        if (self.sourceTableConditionModel().conditions().length > 1) {
            array.push({
                propName: "sourceTableConditionModel", propFaName: "شروط مبدا",
                children: self.sourceTableConditionModel().validateForm()
            });
        }

        if (self.expenseCenterTableConditionModel().conditions().length > 1) {
            array.push({
                propName: "expenseCenterTableConditionModel", propFaName: "شروط هزینه",
                children: self.expenseCenterTableConditionModel().validateForm()
            });
        }

        return array;
    };
    self.showApportionAccountType = ko.computed(function () {
        var item = self.sourceTableSelectList[self.sourceTableId()];
        return item && item.tableRole() === 2;
    });
}
export function DeleteCostDocumentProperties(parent) {
    var self = this;
    self.parentForm = parent;
    self.sourceTableId = ko.observable();
    self.sourceTableCondition = ko.observable();
    self.sourceTableConditionModel = ko.observable();
    self.destinationValues = ko.observableArray();
    self.sourceTableSelectList = {};
    self.sourceTableColSelectList = {};
    self.onSelect = function (controlName) {
        switch (controlName) {
            case "sourceTableId":
                if (self.sourceTableId()) {
                    var item = self.sourceTableSelectList[self.sourceTableId()];
                    self.sourceTableColSelectList = {};
                    if (_h.any(item.fields())) {
                        for (var i = 0; i < item.fields().length; i++) {
                            var target = item.fields()[i];
                            self.sourceTableColSelectList[target.value()] = target;
                        }
                    }
                }
                self.sourceTableConditionModel().reset();
                self.destinationValues.removeAll();
                break;
        }
    };
    self.fillModel = function (model, editForm) {
        self.fillLists();
        self.sourceTableId(model.sourceTableId);
        self.onSelect("sourceTableId");

        self.sourceTableCondition(model.sourceTableCondition);
        var translator = new PhraseTranslator();
        var sourceModel = translator.getModel(model.sourceTableCondition);
        var record = new TableConditionSet(self, "source");
        record.fillModel(sourceModel, model.sourceTableConditionAggregation);
        self.sourceTableConditionModel(record);
        if (_h.any(model.destinationValues))
            for (var i = 0; i < model.destinationValues.length; i++) {
                var rec = new DeleteCostDestinationValueProperty(self);
                rec.fillModel(model.destinationValues[i]);
                self.destinationValues.push(rec);
            }
    }
    self.fillEmpty = function () {
        self.fillLists();
        var record = new TableConditionSet(self, "source");
        record.fillEmpty(undefined);
        self.sourceTableConditionModel(record);
    };
    self.fillLists = function () {
        self.sourceTableSelectList = {};
        for (var i = 0; i < _h.kocnx().ddvm().allTableSelectList().length; i++) {
            var p = _h.kocnx().ddvm().allTableSelectList()[i];
            if (p.tableRole() === 2) {
                self.sourceTableSelectList[p.value()] = p;
            }
        }
    };
    self.addDeleteCostDestinationValue = function () {
        self.destinationValues.push(new DeleteCostDestinationValueProperty(self));
    };
    self.removeDeleteCostDestinationValue = function (item) {
        self.destinationValues.remove(item);
    };
    self.toServer = function () {
        var array = [];
        for (var i = 0; i < self.destinationValues().length; i++) {
            var target = self.destinationValues()[i];
            array.push({
                sourceFieldOrder: target.sourceFieldOrder(),
                destinationFieldOrder: target.destinationFieldOrder()
            });
        }
        return {
            sourceTableId: self.sourceTableId(),
            destinationValues: array,
            sourceTableCondition: self.sourceTableCondition()
        };
    };
    self.validationObject = ko.validatedObservable({
        sourceTableId: self.sourceTableId.extend({
            required: true
        }),
        destinationValues: self.destinationValues.extend({
            atleastOneDeleteCostDestinationValues: true
        })
    });
    self.validateForm = function () {
        var array = [];
        for (var p2 in self.validationObject()) {
            if (self.validationObject().hasOwnProperty(p2)) {
                var target2 = self.validationObject()[p2];
                var text;
                try {
                    text = _h.getLocalizedText(p2);
                } catch (e) {
                    text = undefined;
                }
                if (!_h.isNullOrEmpty(text) && !_h.isNullOrEmpty(target2.error()))
                    array.push({ propName: p2, propFaName: text, error: target2.error() });


            }
        }

        if (self.sourceTableConditionModel().conditions().length > 1) {
            array.push({
                propName: "sourceTableConditionModel", propFaName: "شروط مبدا",
                children: self.sourceTableConditionModel().validateForm()
            });
        }


        return array;
    };
}
export function ColumnDocumentProperties(parent) {
    var self = this;
    self.parentForm = parent;
    self.sourceTableId = ko.observable();
    self.sourceTableCondition = ko.observable();
    self.sourceTableConditionModel = ko.observable();
    self.destinationValues = ko.observableArray();
    self.treeId = ko.observable();
    self.sourceTableSelectList = {};
    self.sourceTableColSelectList = {};
    self.destinationValuesTableColSelectList = {};
    self.onSelect = function (controlName) {
        switch (controlName) {
            case "sourceTableId":
                if (self.sourceTableId()) {
                    var item = self.sourceTableSelectList[self.sourceTableId()];
                    self.sourceTableColSelectList = {};
                    if (item && _h.any(item.fields())) {
                        for (var i = 0; i < item.fields().length; i++) {
                            var target = item.fields()[i];
                            self.sourceTableColSelectList[target.value()] = target;
                            if (target.dataType() === 0 || target.dataType() === 2 || target.dataType() === 3) {
                                self.destinationValuesTableColSelectList[target.value()] = target;
                            }
                        }
                    }
                }
                self.destinationValues.removeAll();
                self.sourceTableConditionModel().reset();
                break;
        }
    };
    self.fillLists = function () {
        self.sourceTableSelectList = {};
        for (var i = 0; i < _h.kocnx().ddvm().allTableSelectList().length; i++) {
            var p = _h.kocnx().ddvm().allTableSelectList()[i];
            self.sourceTableSelectList[p.value()] = p;
        }
    };
    self.toServer = function () {
        var dValues = [];
        for (var i = 0; i < self.destinationValues().length; i++) {
            var target = self.destinationValues()[i];
            dValues.push({
                nodeId: target.nodeId(),
                columnFunction: target.columnFunction(),
                fieldOrder: target.fieldOrder()
            });
        }
        return {
            sourceTableId: self.sourceTableId(),
            sourceTableCondition: self.sourceTableCondition(),
            destinationValues: dValues,
            treeId: self.treeId()
        };
    }
    self.fillModel = function (model, editForm) {
        self.fillLists();
        self.treeId(model.treeId);
        self.sourceTableId(model.sourceTableId);
        self.onSelect("sourceTableId");
        self.sourceTableCondition(model.sourceTableCondition);
        var translator = new PhraseTranslator();
        var sourceModel = translator.getModel(model.sourceTableCondition);
        var record = new TableConditionSet(self, "source");
        record.fillModel(sourceModel, model.sourceTableConditionAggregation);
        self.sourceTableConditionModel(record);
        if (_h.any(model.destinationValues))
            for (var i = 0; i < model.destinationValues.length; i++) {
                var rec = new ColumnDestinationValueProperty(self);
                rec.fillModel(model.destinationValues[i]);
                self.destinationValues.push(rec);
            }
    }
    self.fillEmpty = function () {
        self.fillLists();
        var record = new TableConditionSet(self, "source");
        record.fillEmpty(undefined);
        self.sourceTableConditionModel(record);
    };
    self.addColumnDestinationValue = function () {
        var rec = new ColumnDestinationValueProperty(self);
        self.destinationValues.push(rec);
    }
    self.validationObject = ko.validatedObservable({
        sourceTableId: self.sourceTableId.extend({
            required: true,
        }),
        treeId: self.treeId.extend({
            required: true,
        }),
        destinationValues: self.destinationValues.extend({
            atleastOneColumnDestinationValues: true
        })
    });
    self.validateForm = function () {
        var array = [];
        for (var p2 in self.validationObject()) {
            if (self.validationObject().hasOwnProperty(p2)) {
                var target2 = self.validationObject()[p2];
                var text;
                try {
                    text = _h.getLocalizedText(p2);
                } catch (e) {
                    text = undefined;
                }
                if (!_h.isNullOrEmpty(text) && !_h.isNullOrEmpty(target2.error()))
                    array.push({ propName: p2, propFaName: text, error: target2.error() });

                if (_h.isNullOrEmpty(text) && !_h.isNullOrEmpty(target2())
                    && !_h.isNullOrEmpty(target2()["validateForm"])) {
                    array.push({ propName: p2, propFaName: text, children: target2().validateForm() });
                }
            }
        }

        if (self.sourceTableConditionModel().conditions().length > 1) {
            array.push({
                propName: "sourceTableConditionModel", propFaName: "شروط مبدا",
                children: self.sourceTableConditionModel().validateForm()
            });
        }
        return array;
    };
    self.showResultBtn = ko.computed(function () {
        return !_h.isNullOrEmpty(self.sourceTableId());
    });
}
export function DestinationFieldProperties(parent) {
    var self = this;
    self.parentForm = parent;
    self.destinationField = ko.observable();
    self.destinationFieldDataType = ko.observable();
    self.selectedTable = ko.observable();
    self.selectedField = ko.observable();
    self.onSelect = function (controlName) {
        switch (controlName) {
            case "destinationField":
                var item = self.parentForm.destinationTableColSelectList[self.destinationField()];
                if (self.destinationField())
                    self.destinationFieldDataType(item.dataType());
                self.selectedField(undefined);
                break;
        }
    };
    self.fillModel = function (model) {
        self.destinationField(model.destinationField);
        self.destinationFieldDataType(model.dataType);
        self.onSelect("destinationField");
        self.selectedTable(model.selectedTable);
        self.selectedField(model.selectedField);

    };
    self.fillEmpty = function (sourceTableId, expenseCenterTableId) {
        if (sourceTableId && expenseCenterTableId) {
            self.selectedTable(sourceTableId);
        }
        if (sourceTableId && !expenseCenterTableId) {
            self.selectedTable(sourceTableId);
        }
        if (!sourceTableId && expenseCenterTableId) {
            self.selectedTable(expenseCenterTableId);
        }

    };
    self.filterSelectedField = function (item) {
        if (self.destinationFieldDataType() === item.dataType) {
            return true;
        }
        return false;
    };
}
export function DeleteCostDestinationValueProperty(parent) {
    var self = this;
    self.parentForm = parent;
    self.sourceFieldOrder = ko.observable();
    self.sourceFieldType = ko.observable();
    self.destinationFieldOrder = ko.observable();
    self.fillModel = function (model) {
        self.sourceFieldOrder(model.sourceFieldOrder);
        self.onSelect("sourceFieldOrder");
        var item = self.parentForm.sourceTableColSelectList[self.sourceFieldOrder()];
        self.sourceFieldType(item.dataType());
        self.destinationFieldOrder(model.destinationFieldOrder);
    };
    self.onSelect = function (controlName) {
        switch (controlName) {
            case "sourceFieldOrder":
                if (self.sourceFieldOrder()) {
                    var item = self.parentForm.sourceTableColSelectList[self.sourceFieldOrder()];
                    self.sourceFieldType(item.dataType());
                }
                self.destinationFieldOrder(undefined);
                break;
        }
    };
    self.filterDataType = function (item) {
        if (item.dataType === self.sourceFieldType()) {
            return true;
        }
        return false;
    };
}
export function ColumnDestinationValueProperty(parent) {
    var self = this;
    self.parentForm = parent;
    self.nodeId = ko.observable();
    self.columnFunction = ko.observable();
    self.fieldOrder = ko.observable();
    self.nodeName = "";
    self.fillModel = function (model) {
        self.nodeId(model.nodeId);
        self.nodeName = model.nodeName + " ( " + model.nodeCode + " )";
        self.columnFunction(model.columnFunction);
        self.fieldOrder(model.fieldOrder);
    };
    self.onNodeSelect = function (name, value) {
        switch (name) {
            case "nodeId":
                self.nodeId(value);
                break;
        }
    };
}
export function TableConditionSet(parentForm, target) {
    var self = this;
    self.parentForm = parentForm;
    self.target = target;
    self.operatorsList = [];
    self.showDropDown = ko.observable(false);
    self.conditions = ko.observableArray();
    self.shortcuts = ko.observableArray();
    self.result = ko.observable("");
    self.text = ko.observable("");
    self.translatePhrase = function () {
        if (self.conditions().length === 1) {
            self.parentForm[self.target + "TableCondition"]("");
            if (self.conditions()[0].leftSide() &&
                self.conditions()[0].leftSide() !== "" &&
                self.conditions()[0].operator() &&
                self.conditions()[0].operator() !== "") {
                var phrase = self.conditions()[0].createCondtionPhrase();
                self.result("[cs1:" + phrase + "]");
                self.parentForm[self.target + "TableCondition"](self.result());
            }
        }
        if (!_h.isNullOrEmpty(self.text()) && self.text() !== "") {
            if (self.conditions().length > 1) {
                var text = self.text();
                self.parentForm[self.target + "TableCondition"]("");
                for (var i = 0; i < self.conditions().length; i++) {
                    var target = self.conditions()[i];
                    var ph = target.createCondtionPhrase();
                    var cName = "Cs" + (i + 1);
                    if (self.text().indexOf(cName) !== -1) {
                        var condStr = "[cs" + (i + 1) + ":" + ph + "]";
                        text = text.replace(cName, condStr);
                        self.result(text);
                    }
                }
                self.parentForm[self.target + "TableCondition"](self.result());
            }
        }
        if (self.target === "destination" && self.conditions().length > 1) {
            var condStrD = "";
            for (var b = 0; b < self.conditions().length; b++) {
                var targetD = self.conditions()[b];
                var phD = targetD.createCondtionPhrase();
                condStrD += "[cs" + (b + 1) + ":" + phD + "]";
                if (self.conditions().length !== b + 1)
                    condStrD += "&&";
            }
            self.parentForm[self.target + "TableCondition"](condStrD);
        }
    };
    self.fillModel = function (conditions, agr) {
        self.init(conditions, agr);
    };
    self.fillEmpty = function () {
        self.init(undefined);
    };
    self.addCondition = function () {
        var record = self.getConditionModel();
        record.fillModel(undefined);
        self.conditions.push(record);
    };
    self.removeCondition = function (item) {
        if (self.conditions().length > 1) {
            self.conditions.remove(item);
            $('a[href="#cond-0"]').trigger('click');
            self.translatePhrase();
        }
    };
    self.init = function (conditions, agr) {
        var record = null;
        if (_h.any(conditions))
            for (var i = 0; i < conditions.length; i++) {
                var condition = conditions[i];
                record = self.getConditionModel();
                record.fillModel(condition);
                self.conditions.push(record);
            }
        else {
            record = self.getConditionModel();
            record.fillModel(undefined);
            self.conditions.push(record);
        }
        if (!_h.isNullOrEmpty(agr)) {
            agr = agr.replace(/[c]/g, "C");
            self.text(agr);
        }
        self.operatorsList = {
            1000: { text: "Cs", data: "Cs", keyCode: 1000, enabled: ko.observable(false), after: [38, 124, 41] },
            40: { text: "(", data: "(", keyCode: 40, enabled: ko.observable(false), after: [40, 1000] },
            41: { text: ")", data: ")", keyCode: 41, enabled: ko.observable(false), after: [38, 124, 41] },
            38: { text: "و (AND)", data: "&&", keyCode: 38, enabled: ko.observable(false), after: [1000, 40] },
            124: { text: "یا (OR)", data: "||", keyCode: 124, enabled: ko.observable(false), after: [1000, 40] }
        };
        self.updateOperatorState();
        self.translatePhrase();
    };
    self.getConditionModel = function () {
        if (self.target === "destination")
            return new AggregationTableCondition(self.parentForm, self, self.target);
        else if (self.parentForm.parentForm.dynamicDocumentType() === 1) {
            return new ComputationalTableCondition(self.parentForm, self, self.target);
        } else
            return new TableCondition(self.parentForm, self, self.target);
    };
    self.lastOperator = ko.observable();
    self.middleTyping = ko.observable();
    self.updateOperatorState = function () {
        if (_h.isNullOrEmpty(self.lastOperator()) || self.lastOperator() === "") {
            self.operatorsList[40].enabled(true);
            self.operatorsList[1000].enabled(true);
        } else {
            var last = self.operatorsList[self.lastOperator()];
            for (const prop in self.operatorsList) {
                if (self.operatorsList.hasOwnProperty(prop)) {
                    var target = self.operatorsList[prop];
                    if (last.after.indexOf(target.keyCode) !== -1) {
                        if (target.keyCode !== 41)
                            target.enabled(true);
                        else {
                            var rs = self.isAllowAddRightParentheses();
                            target.enabled(rs);
                        }
                    } else {
                        target.enabled(false);
                    }

                }
            }
        }
    };
    self.clickOperator = function (item) {
        self.text(self.text() + item.value.data);
        self.lastOperator(item.value.keyCode);
        self.updateOperatorState();
        self.translatePhrase();
    };
    self.clickCondition = function (model, index, cond) {
        self.text(self.text() + "Cs" + index);
        self.lastOperator(self.operatorsList[1000].keyCode);
        self.updateOperatorState();
        self.translatePhrase();
    };
    self.isAllowAddRightParentheses = function () {
        var lPCount = self.text().replace(/[^(]/g, "").length;
        var rPCount = self.text().replace(/[^)]/g, "").length;
        if (lPCount === 0)
            return false;
        if (lPCount === rPCount)
            return false;
        if (lPCount > rPCount) {
            return true;
        }
        return false;
    };
    self.proxyKeyDown = function (data, event) {
        var itemOperator = self.operatorsList[event.keyCode];
        if (itemOperator && itemOperator.enabled()) {
            self.text(self.text() + self.operatorsList[event.keyCode].data);
            self.lastOperator(self.operatorsList[event.keyCode].keyCode);
            self.updateOperatorState();
        } else {
            if (event.keyCode === 67 && !self.middleTyping()) {
                self.middleTyping(true);
                if (self.operatorsList[1000].enabled()) {
                    self.text("Cs");
                }
            }
            if (event.keyCode >= 49 && event.keyCode <= 57 && self.middleTyping()) {
                var condition = self.conditions()[event.keyCode - 48];
                if (condition && condition.validationObject.isValid()) {
                    self.text(self.text() + "Cs" + (event.keyCode - 48));
                    self.middleTyping(false);
                    self.lastOperator(1000);
                }
            }
            if (event.keyCode === 46) {
                event.preventDefault();
                self.text("");
                self.lastOperator(undefined);
                self.updateOperatorState();
            }
            if (event.keyCode === 8) {
                event.preventDefault();
                if (!self.middleTyping())
                    self.clearOnStep();
                else {
                    var rest = self.text().substring(0, self.text().length - 2);
                    self.text(rest);
                    self.middleTyping(false);
                }
            }
        }
        self.translatePhrase();
    };
    self.refreshShortcuts = ko.computed(function () {
        if (self.conditions().length > 1) {
            self.shortcuts.removeAll();
            var and = "";
            var or = "";
            ko.utils.arrayForEach(self.conditions(), function (f, index) {
                if (f.validationObject.isValid()) {
                    if (index + 1 !== self.conditions().length) {
                        and += "Cs" + (index + 1) + "&&";
                        or += "Cs" + (index + 1) + "||";
                    } else {
                        and += "Cs" + (index + 1);
                        or += "Cs" + (index + 1);
                    }
                }
            });
            self.shortcuts.push(and);
            self.shortcuts.push(or);
        } else {
            self.shortcuts.removeAll();
        }
    });
    self.clickShortcut = function (item) {
        self.text("");
        self.text(item);
        self.lastOperator(1000);
        self.updateOperatorState();
        self.translatePhrase();
    };
    self.clearOnStep = function () {
        var last = self.lastOperator();
        if (last !== undefined && last !== "") {
            var itemOperator = self.operatorsList[last];
            var lastChar = "";
            var rest = self.text().substring(0, self.text().lastIndexOf(itemOperator.data));
            self.text(rest);
            lastChar = self.text().substring(self.text().length - 1);
            self.guessLastOperator(lastChar);

        }
    };
    self.guessLastOperator = function (lastChar) {
        if (lastChar === undefined || lastChar === "")
            self.lastOperator(undefined);
        else if ($.isNumeric(lastChar))
            self.lastOperator(1000);
        else if (lastChar === "(")
            self.lastOperator(40);
        else if (lastChar === ")")
            self.lastOperator(41);
        else if (lastChar === "&")
            self.lastOperator(38);
        else if (lastChar === " |")
            self.lastOperator(124);

    };
    if (self.target !== "destination")
        self.validationObject = ko.validatedObservable({
            conditions: self.conditions,
            text: self.text.extend({
                required: {
                    onlyIf: function () {
                        return self.conditions().length > 1;
                    },
                },
                isAllConditionsUse: {
                    params: self.conditions
                },
                isConditionsUseValid: {
                    params: self.conditions
                },
                remoteIsValidExpression: {
                    onlyIf: function () {
                        return self.conditions().length > 1 && self.text() !== undefined && self.text() !== "";
                    },
                    params: [true, false, 50]
                }
            })
        });
    if (self.target === "destination")
        self.validationObject = ko.validatedObservable({
            conditions: self.conditions
        });
    self.reset = function (loc) {
        var zero = self.conditions()[0];
        zero.reset(loc);
        self.conditions.removeAll();
        self.conditions.push(zero);
    };
    self.formulaTarget = ko.observable();
    self.openformula = function (model, e) {
        self.formulaTarget(model.rightSide);
        var config = {
            parentForm: self,
            percentage: false,
            column: true,
            columnList: self.parentForm.furmolaColSelectList,
            node: true,
            branchSelectable: true,
            controllerName: 50,
            value: model.rightSide(),
            trees: _h.kocnx().ddvm().treeFormulaList()
        };
        _h.kocnx().calculator().init(config);
    };
    self.returnFormulaValue = function (value) {
        var control = self.formulaTarget();
        control(value);
        self.formulaTarget(null);
    };
    self.validateForm = function () {
        var array = [];
        for (var i = 0; i < self.conditions().length; i++) {
            var target = self.conditions()[i];
            var condArray = { propFaName: "شرط " + (i + 1), propName: "Condition " + (i + 1), children: [] };
            for (var p in target.validationObject()) {
                if (target.validationObject().hasOwnProperty(p)) {
                    var valObj = target.validationObject()[p];
                    var text;
                    try {
                        text = _h.getLocalizedText(p);
                    } catch (e) {
                        text = "";
                    }
                    if (!_h.isNullOrEmpty(text) && !_h.isNullOrEmpty(valObj.error()))
                        condArray.children.push({ propName: p, propFaName: text, error: valObj.error() });
                }

            }
            if (condArray.children.length > 0)
                array.push(condArray);
        }
        var sourceLoc = "";
        switch (self.target) {
            case "source":
                sourceLoc = "مبدا";
                break;
            case "destination":
                sourceLoc = "مقصد";
                break;
            case "calculation":
                sourceLoc = "محاسبات";
                break;
            case "expenseCenter":
                sourceLoc = "هزینه";
                break;
        }

        if (!_h.isNullOrEmpty(self.text.error()))
            array.push({
                propName: self.target + "ConditionAggregation",
                propFaName: "تجمیع شروط " + sourceLoc,
                error: self.text.error()
            });
        return array;
    };
}
export function TableCondition(parent, parentSet, target) {
    var self = this;
    self.parentForm = parent;
    self.parentSet = parentSet;
    self.target = target;
    self.leftListName = self.target + "TableColSelectList";
    self.leftSourceListName = "sourceTableColSelectList";
    self.rightSideDataTypes = ko.observableArray([]);
    self.rightSideDataType = ko.observable();
    self.rightSide = ko.observable();
    self.leftSide = ko.observable();
    self.leftSideDataType = ko.observable();
    self.operator = ko.observable();
    self.operators = ko.observableArray();
    self.dynamicTableConditionalOperators = ko.observableArray();
    self.enumItems = {};
    self.rightSideItems = ko.observableArray();
    self.onSelect = function (controlName) {
        switch (controlName) {
            case "leftSide":
                if (!_h.isEmpty(self.leftSide())) {
                    var item = self.parentForm[self.leftListName][self.leftSide()];
                    self.leftSideDataType(item.dataType());
                } else {
                    self.leftSideDataType(undefined);
                }
                self.rightSideDataType(undefined);
                self.rightSide(undefined);
                self.operator(undefined);
                self.parentSet.translatePhrase();
                break;
            case "operator":
                self.rightSideDataTypes.removeAll();
                self.rightSideDataType(undefined);
                self.rightSide(undefined);
                if (!_h.isNullOrEmpty(self.operator())) {
                    switch (self.operator()) {
                        case 1:
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                        case 6:
                            var selected = null;
                            for (var i = 0; i < tableconditiondataTypes.length; i++) {
                                if (tableconditiondataTypes[i].value === self.leftSideDataType()) {
                                    selected = tableconditiondataTypes[i];
                                }
                            }
                            self.rightSideDataTypes.push(selected);
                            if (!_h.isNullOrEmpty(selected) && selected.value === 7)
                                self.refreshEnumList(self.target);

                            self.rightSideDataType(self.leftSideDataType());
                            if (self.target !== "source")
                                self.rightSideDataTypes.push(tableconditiondataTypes[7]);
                            break;
                        case 7:
                        case 8:
                        case 9:
                        case 10:
                            self.rightSideDataType(13);
                            break;
                        case 11:
                            self.rightSideDataType(1);
                            break;
                        case 12:
                        case 13:
                            if (!_h.isNullOrEmpty(self.leftSideDataType())) {
                                var item2 = _h.getEnumItem(dataTypes, self.leftSideDataType());
                                switch (item2.value) {
                                    case 0:
                                        self.rightSideDataTypes.push(tableconditiondataTypes[0]);
                                        self.rightSideDataTypes.push(tableconditiondataTypes[12]);
                                        if (self.target !== "source")
                                            self.rightSideDataTypes.push(tableconditiondataTypes[7]);
                                        break;
                                    case 1:
                                        self.rightSideDataType(9);
                                        break;
                                    case 4:
                                        self.rightSideDataType(10);
                                        break;
                                    case 7:
                                        self.rightSideDataType(12);
                                        self.refreshEnumList("source");
                                        break;
                                }
                            }
                            break;
                        case 14:
                            self.rightSideDataType(15);
                            break;
                        case 15:
                        case 16:
                            self.rightSideDataType(20);
                            break;
                    }
                }
                self.parentSet.translatePhrase();
                break;
        }
    };
    self.filterOperator = function (item) {
        return item.dataTypes.indexOf(self.leftSideDataType()) !== -1;
    };
    self.filterRightSide = function (item) {
        return item.dataType === self.leftSideDataType();
    };
    self.rightSideDataType.subscribe(function (newValue) {
        self.parentSet.translatePhrase();
    });
    self.rightSide.subscribe(function (newValue) {
        self.parentSet.translatePhrase();
    });
    self.refreshEnumList = function (loc) {
        self.enumItems = {};
        var keys = Object.keys(self.parentForm[loc + "TableColSelectList"]);
        if (keys && keys.length)
            for (var j = 0; j < keys.length; j++) {
                var k = self.parentForm[loc + "TableColSelectList"][keys[j]];
                if (k.value() === self.leftSide() && k.enumValues().length) {
                    for (var l = 0; l < k.enumValues().length; l++) {
                        var target = k.enumValues()[l];
                        self.enumItems[target.value()] = target;
                    }
                }
            }
        self.rightSide(undefined);
    };
    self.validationObject = ko.validatedObservable({
        rightSide: self.rightSide.extend({
            required: {
                onlyIf: function () {
                    var conditionCount = self.parentSet !== "" && self.parentSet.conditions().length > 1;
                    var hasLeftSideValue = self.leftSide && self.leftSide() !== "";
                    var hasOperatorValue = self.operator && self.operator() !== "";
                    var reqiureVal = self.rightSideDataType && self.rightSideDataType() !== "" && self.rightSideDataType() !== 13;

                    return conditionCount && (hasLeftSideValue || hasOperatorValue) && reqiureVal;
                }
            }
        }),
        leftSide: self.leftSide.extend({
            required: {
                onlyIf: function () {
                    return self.parentSet !== "" && self.parentSet.conditions().length > 1;
                }
            }
        }),
        operator: self.operator.extend({
            required: {
                onlyIf: function () {
                    var conditionCount = self.parentSet !== "" && self.parentSet.conditions().length > 1;
                    var hasLeftSideValue = self.leftSide && self.leftSide() !== "";
                    return conditionCount && hasLeftSideValue;
                }
            }
        })
    });
    self.rightSideItems.subscribe(function (newValue) {
        if (!_h.isNullOrEmpty(newValue)) {
            var value = _h.concatStringList(newValue);
            self.rightSide(value);
        }
    });
    self.fillModel = function (model) {
        if (model) {
            self.leftSide(Number(model.leftSide));
            if (!_h.isEmpty(self.leftSide())) {
                var item = self.parentForm[self.leftListName][self.leftSide()];
                self.leftSideDataType(item.dataType());
            }
            self.operator(model.operator.value);
            self.rightSideDataType(model.rightSide.type);
            self.rightSide(model.rightSide.value);
            if (model.rightSide.type === 12) {
                var values = _h.splitStringList(model.rightSide.value);
                self.rightSideItems(values);
            }
            if (model.rightSide.type === 7) {
                self.refreshEnumList(self.target);
                self.rightSide(model.rightSide.value);
            }
        }
    };
    self.createCondtionPhrase = function () {
        var ph = "[table:'" + self.leftSide() + "']";
        ph += _h.getEnumEnText(dynamicConditionalOperators2, self.operator());
        var val = self.rightSideDataType();
        var right = "";
        switch (val) {
            case 0:
                right = "int:'";
                break;
            case 1:
                right = "text:'";
                break;
            case 2:
                right = "decimal:'";
                break;
            case 3:
                right = "money:'";
                break;
            case 4:
                right = "date:'";
                break;
            case 7:
                right = "enum:'";
                break;
            case 8:
                right = "table:'";
                break;
            case 9:
                right = "listtext:'";
                break;
            case 10:
                right = "listdate:'";
                break;
            case 12:
                right = "listenum:'";
                break;
            case 14:
                right = "listint:'";
                break;
            case 15:
                right = "pattern:'";
                break;
            case 20:
                right = "likepattern:'";
                break;
            case null:
            case undefined:
            case "":
            case "-":
            case 13:
                return ph;
        }
        if (self.rightSide() !== undefined)
            ph += "[" + right + self.rightSide() + "']";
        else
            ph += "[" + right + "']";
        return ph;
    };
    self.reset = function () {
        self.leftSide(undefined);
        self.leftSideDataType(undefined);
        self.operator(undefined);
        self.rightSideDataType(undefined);
        self.rightSide(undefined);
    };
}
export function AggregationTableCondition(parent, parentSet, target) {
    var self = this;
    self.parentForm = parent;
    self.parentSet = parentSet;
    self.target = target;
    self.leftListName = "destinationTableColSelectList";
    self.rightSideDataTypes = [
        { text: "مقدار ثابت", value: 16 },
        { text: "ستون جدول مبدا", value: 17 },
        { text: "ستون جدول محاسبات", value: 18 }];
    self.operators = [
        { text: "=", enText: "=", value: 3 },
        { text: "بدون مقدار", enText: "IsNull", value: 7 }];
    self.rightSideDataType = ko.observable(null);
    self.leftSideDataType = ko.observable();
    self.rightSide = ko.observable();
    self.leftSide = ko.observable();
    self.operator = ko.observable();
    self.onSelect = function (controlName) {
        switch (controlName) {
            case "leftSide":
                if (!_h.isEmpty(self.leftSide())) {
                    var item = self.parentForm[self.leftListName][self.leftSide()];
                    self.leftSideDataType(item.dataType());
                } else {
                    self.leftSideDataType(undefined);
                }
                self.operator(undefined);
                self.rightSideDataType(undefined);
                self.showRightSide(true);
                self.rightSide(undefined);
                break;
            case "operator":
                if (!_h.isNullOrEmpty(self.operator())) {
                    switch (self.operator()) {
                        case 7:
                            self.rightSideDataType(null);
                            self.showRightSide(false);
                            self.rightSide(null);
                            self.parentSet.translatePhrase();
                            break;
                        default:
                            self.showRightSide(true);
                            break;
                    }
                }
                break;

            case "rightSideDataType":
                break;
        }
    };
    self.showRightSide = ko.observable(true);
    self.filterRightSide = function (item) {
        return item.dataType === self.leftSideDataType();
    };
    self.rightSide.subscribe(function () {
        self.parentSet.translatePhrase();
    });
    self.fillModel = function (model) {
        if (model) {
            self.leftSide(Number(model.leftSide));
            if (!_h.isEmpty(self.leftSide())) {
                var item = self.parentForm[self.leftListName][self.leftSide()];
                self.leftSideDataType(item.dataType());
            }
            self.operator(model.operator.value);
            self.onSelect("operator");
            self.rightSideDataType(model.rightSide.type);
            self.rightSide(model.rightSide.value);
        }
    };
    self.createCondtionPhrase = function () {
        var ph = "[table:'" + self.leftSide() + "']";
        ph += _h.getEnumEnText(dynamicConditionalOperators2, self.operator());
        var val = self.rightSideDataType();
        var right = "";
        switch (val) {
            case 16:
                right = "value:'";
                break;
            case 17:
                right = "sourcetable:'";
                break;
            case 18:
                right = "calculationtable:'";
                break;
            case 13:
            case "":
            case undefined:
            case null:
                return ph;
        }
        if (self.rightSide() !== undefined)
            ph += "[" + right + self.rightSide() + "']";
        else
            ph += "[" + right + "']";
        return ph;
    }
    self.validationObject = ko.validatedObservable({
        rightSide: self.rightSide.extend({
            required: {
                onlyIf: function () {
                    return self.parentForm.destinationCalculationType() === 2 && self.operator && self.operator() !== "" && self.operator() !== 7;
                }
            }
        }),
        leftSide: self.leftSide.extend({
            onlyIf: function () {
                return self.parentForm.destinationCalculationType() === 2;
            }
        }),
        operator: self.operator.extend({
            onlyIf: function () {
                return self.parentForm.destinationCalculationType() === 2;
            }
        }),
        rightSideDataType: self.rightSideDataType.extend({
            onlyIf: function () {
                return self.parentForm.destinationCalculationType() === 2 && self.operator && self.operator() !== "" && self.operator() !== 7;
            }
        })
    });
    self.reset = function () {
        self.leftSide(undefined);
        self.leftSideDataType(undefined);
        self.rightSideDataType(null);
        self.showRightSide(false);
        self.rightSide(null);
    };
}