
require('./resource');
require('./resource.main.js');

import { BaseViewModel } from '../master/baseViewModel.js';
import { SelectItem, TreeSelectItem, TreeFormulaSelectItem, PeriodSelectItem, TableSelectItem } from '../master/model';
import { SourceTableDataViewModel, DynamicDocumentForm  } from './model';

export function DynamicDocumentViewModel() {
    var self = this;
    self.showResultsModal = ko.observable(false);
    self.resultsModel = ko.observable();
    self.showResults = function () {
        var item = _h.kocnx().formModel();
        var sTable = self.getTable(item.documentProperties().sourceTableId());
        var dataModel;
        switch (item.dynamicDocumentType()) {
            case 1:
            case 5:
                dataModel = {
                    sourceTable: sTable,
                    sourceTableCondition: _h.normalizeAmpersand(item.documentProperties().sourceTableCondition()),
                    type: item.dynamicDocumentType()
                };
                break;
            case 4:
                var cTable = self.getTable(item.documentProperties().calculationTableId());
                dataModel = {
                    sourceTable: sTable,
                    sourceTableCondition: _h.normalizeAmpersand(item.documentProperties().sourceTableCondition()),
                    expenseCenterTable: cTable,
                    expenseCenterTableCondition: _h.normalizeAmpersand(item.documentProperties().calculationTableCondition()),
                    type: item.dynamicDocumentType(),
                    sourcePeriodId: item.documentProperties().sourcePeriodId(),
                    calculationPeriodId: item.documentProperties().calculationPeriodId()
                };
                break;
            default:
                var eTable = self.getTable(item.documentProperties().expenseCenterTableId());
                dataModel = {
                    sourceTable: sTable,
                    documentCode: item.code(),
                    sourceTableCondition: _h.normalizeAmpersand(item.documentProperties().sourceTableCondition()),
                    treeId: item.documentProperties().treeId(),
                    nodeIdList: item.documentProperties().nodeIdList(),
                    expenseCenterTable: eTable,
                    expenseCenterTableCondition: _h.normalizeAmpersand(item.documentProperties().expenseCenterTableCondition()),
                    destinationAccountCodes: item.documentProperties().destinationAccountCodes(),
                    type: item.dynamicDocumentType()
                };
                break;
        }
        var model = new SourceTableDataViewModel(dataModel);
        self.resultsModel(model);
        self.resultsModel().init();
        self.showResultsModal(true);
        $(".preview-box").draggable({
            scroll: true,
            handle: ".panel-heading"
        });
    };
    self.hideRrsults = function () {
        self.showResultsModal(false);
        self.resultsModel(null);
    }
    self.getTable = function (id) {
        var table = null;
        for (var i = 0; i < self.allTableSelectList().length; i++) {
            var target = self.allTableSelectList()[i];
            if (target.value() === id)
                table = target;
        }
        return table;
    };
    self.allTableSelectList = ko.observableArray();
    self.treeList = ko.observableArray();
    self.treeColumnsList = ko.observableArray();
    self.periodSelectList = [];
    self.getTreeList = function () {
        self.apiService.request({
            name: "/api/common/getmappingtreelist",
            data: { controllerName: this.controllerName },
            success: function (data) {
                self.treeList.removeAll();
                self.treeColumnsList.removeAll();
                if (_h.any(data))
                    for (var j = 0; j < data.length; j++) {
                        var target = data[j];
                        if (target.assignmentType === 2 && target.valueType === 0)
                            self.treeList.push(new SelectItem({ text: target.name, value: target.id }));

                        if (_h.kocnx().loginCompanyType() === 1 &&
                            (target.treeType === 7 || target.treeType === 8 || target.treeType === 2 || target.treeType === 3))
                            self.treeColumnsList.push(new TreeSelectItem(target));

                        if (_h.kocnx().loginCompanyType() === 0 &&
                            (target.treeType === 7 || target.treeType === 8))
                            self.treeColumnsList.push(new TreeSelectItem(target));
                    }
            }
        });
    };
    self.treeFormulaList = ko.observableArray();
    self.getTreeFormulaSelectList = function () {
        self.apiService.request({
            name: "getGeneralTreeList",
            data: { controllerName: this.controllerName },
            success: function (data) {
                self.treeFormulaList.removeAll();
                if (!_h.isNullOrEmpty(data)) {
                    for (var j = 0; j < data.length; j++) {
                        var item = new TreeFormulaSelectItem(data[j]);
                        self.treeFormulaList.push(item);
                    }
                }
            },
            error: function () {
                var text = _h.getApiMessage("ErrorLoadTree");
                _h.failToast(text);
            }
        });
    };
    self.getPeriodList = function () {
        self.periodSelectList = [];
        self.apiService.request({
            name: "/api/common/getperiodlist",
            data: { controllerName: this.controllerName },
            success: function (data) {
                if (_h.any(data))
                    for (var i = 0; i < data.length; i++) {
                        self.periodSelectList.push(new PeriodSelectItem(data[i]));
                    }
            },
            error: function () {
                self.periodSelectList = [];
            }
        });
    };
    self.getDynamicTable = function () {
        self.apiService.request({
            name: "getTableList",
            data: { controllerName: self.controllerName },
            success: function (data) {
                self.allTableSelectList.removeAll();
                if (data !== null && data !== undefined && data.length > 0)
                    for (var j = 0; j < data.length; j++) {
                        var target = data[j];
                        self.allTableSelectList.push(new TableSelectItem(target));
                    }
            },
            error: function () {
                toast.error(self.entityName, "getSelectList", "TableList");
            }
        });
    };
    self.createBtn = function () {
        self.getLastPriority(function (res) {
            _h.kocnx()
                .openForm(new DynamicDocumentForm(self, false, res));
        });
    };
    self.editBtn = function () {
        var item = self.multiCommandExecute("selectedRowRecord");
        self.getLastPriority(function (res) {
            self.onlySelectedRow(item);
            _h.kocnx()
                .openForm(new DynamicDocumentForm(self, true, res));
        });
    };
    self.copyBtn = function () {
        var item = self.multiCommandExecute("selectedRowRecord");
        var idList = [];
        idList.push(item.id());
        self.copy(idList, 1);
    };
    self.copiesBtn = function () {
        var idList = self.multiCommandExecute("selectedItemIds");
        if (idList.length === 0) {
            var text = _h.getApiMessage("ActionSelectListEmptyError");
            _h.warningToast(text);
        } else {
            self.copy(idList, 0);
        }
    };
    self.copy = function (idList) {
        var model = { idList: idList };
        self.apiService.request({
            name: "postCopy",
            data: model,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    self.afterCreate(data.models);
                    self.updateExtraParams(data);
                    if (idList.length > 1)
                        toast.success(self.entityName, 'custom', "Copies");
                    if (idList.length === 1)
                        toast.success(self.entityName, 'custom', "Copy");
                }
            },
            error: function () {
                if (idList.length > 1)
                    toast.error(self.entityName, 'custom', "Copies");
                if (idList.length === 1)
                    toast.error(self.entityName, 'custom', "Copy");
            }
        });
    };
    self.calculateDocumentBtn = function () {
        var item = self.multiCommandExecute("selectedRowRecord");
        var idList = [];
        idList.push(item.id());
        var model = {
            idList: idList
        };
        self.startCalculateDocument(model);
    };
    self.calculateDocumentsBtn = function () {
        var idList = self.multiCommandExecute("selectedItemIds");
        if (idList.length === 0) {
            var text = _h.getApiMessage("ActionSelectListEmptyError");
            _h.warningToast(text);
        } else {
            var model = {
                idList: idList
            };
            self.startCalculateDocument(model);
        }
    };
    self.startCalculateDocument = function (model) {
        self.apiService.request({
            name: "postDocumentsCalculation",
            data: model,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    _h.kocnx().checkProcessQueue();
                    localStorage.setItem("ProcessToken", "");
                }
            },
            error: function () {

            }
        });
    };
    self.deleteCalculateDocumentBtn = function () {
        var idList = self.multiCommandExecute("selectedItemIds");
        model = {
            idList: idList
        };
        self.deleteCalculateDocuments(model);
    };
    self.deleteCalculateDocumentsBtn = function () {
        var idList = self.multiCommandExecute("selectedItemIds");
        if (idList.length === 0) {
            var text = _h.getApiMessage("ActionSelectListEmptyError");
            _h.warningToast(text);
        } else {
            model = {
                idList: idList
            };
            self.deleteCalculateDocuments(model);
        }
    };
    self.deleteCalculateDocuments = function (model) {
        self.apiService.request({
            name: "postRemoveCalculation",
            data: model,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    self.afterUpdate(data.models);
                    if (model.idList.length > 1)
                        toast.success(self.entityName, 'custom', "DeleteCalculateDocuments");
                    if (model.idList.length === 1)
                        toast.success(self.entityName, 'custom', "DeleteCalculateDocument");
                }
            },
            error: function () {
                if (model.idList.length > 1)
                    toast.error(self.entityName, 'custom', "DeleteCalculateDocuments");
                if (model.idList.length === 1)
                    toast.error(self.entityName, 'custom', "DeleteCalculateDocument");
            }
        });
    };
    self.changesLocalState = function (ids, action) {
        ko.utils.arrayFilter(self.records(),
            function (record) {
                if (ids.indexOf(record.id()) !== -1) {
                    record.stateType(action);
                    record.selected(false);
                }
            });
    };
    ko.utils.extend(self, new BaseViewModel({
        entityName: "DynamicDocument",
        apiService: {
            actionList: ["filterby",
                "post", "put", "delete",
                "gettreelist",
                "postdocumentscalculation", "getaccountcodeautocomplete",
                "postcopy", "postremovecalculation", "getfolderautocomplete",
                "getperiodlist"]
        },
        getList: true,
        buttons: [
            { name: 'edit', access: true, icon: 'Edit', cMenu: true },
            { name: 'delete', access: true, icon: 'Delete', cMenu: true },
            { name: 'disable', access: true, icon: 'DocDisable', cMenu: true },
            { name: 'enable', access: true, icon: 'DocEnable', cMenu: true },
            { name: 'disables', access: true, icon: 'DocsDisable', cMenu: true },
            { name: 'enables', access: true, icon: 'DocsEnable', cMenu: true },
            { name: 'copy', access: true, icon: 'Copy', cMenu: true },
            { name: 'copies', access: true, icon: 'Copy', cMenu: true },
            { name: 'calculateDocument', access: true, icon: 'CalculateDocument', cMenu: true },
            { name: 'calculateDocuments', access: true, icon: 'CalculateDocument', cMenu: true },
            { name: 'deleteCalculateDocument', access: true, icon: 'CalculateDocumentDelete', cMenu: true },
            { name: 'deleteCalculateDocuments', access: true, icon: 'CalculateDocumentDelete', cMenu: true },
            { name: 'help', access: false, cMenu: false },
            { name: 'refresh', access: false, cMenu: false },
            { name: 'tools', access: false, cMenu: false },
            { name: 'create', access: false, cMenu: false }
        ],
        extraParams: ["lastPriority"],
        filters: [],
        sortDirection: "Ascending",
        sortProperty: "id",
        context: self,
        saveState: true,
        isMultiSelectRows: true,
        cols: dynamicdocumentModelRes,
        searchKeyType: "enter",
        tableStyle: "table-layout: fixed;",
        selectRow: true,
        folderManagement: true,
        contextMenu: true,
        resizable: true
    }));
    self.btnVisibility = ko.computed(function () {
        var context = _h.kocnx();
        var permitPeriodEdit = context.permitPeriodEdit();
        var data = self.multiCommandExecute("btnVisibilityData");
        if (_h.isNullOrEmpty(data))
            return;
        var temp = data[0];
        var enableCount = data[1];
        var disableCount = data[2];
        var selectedList = data[3];
        var rightDocumentsCount = data[4];

        if (selectedList === 0) {
            self.viscreate(permitPeriodEdit);
            self.vistools(true);
            self.visedit(false);
            self.visdelete(false);
            self.visdisables(false);
            self.visenables(false);
            self.visdisable(false);
            self.visenable(false);
            self.viscalculateDocument(false);
            self.viscalculateDocuments(false);
            self.visdeleteCalculateDocument(false);
            self.visdeleteCalculateDocuments(false);
            self.viscopy(false);
            self.viscopies(false);
        }
        if (selectedList === 1) {
            var item = self.getSelectedRecord();
            if (item === undefined || item === null)
                item = temp;
            var isEditable = item.isEditable();
            self.viscreate(permitPeriodEdit);
            self.vistools(true);
            self.visedit(permitPeriodEdit && isEditable);
            self.visdelete(permitPeriodEdit && isEditable);
            self.visdisables(false);
            self.visenables(false);
            self.visdisable(permitPeriodEdit && disableCount >= 0 && enableCount > 0);
            self.visenable(permitPeriodEdit && disableCount >= 0 && enableCount === 0);
            self.viscalculateDocument(permitPeriodEdit && isEditable);
            self.viscalculateDocuments(false);
            self.visdeleteCalculateDocument(permitPeriodEdit && isEditable && rightDocumentsCount > 0);
            self.visdeleteCalculateDocuments(false);
            self.viscopy(true);
            self.viscopies(false);
        }
        if (selectedList > 1) {
            self.viscreate(false);
            self.vistools(true);
            self.visedit(false);
            self.visdelete(false);
            self.visdisable(false);
            self.visenable(false);
            self.viscalculateDocument(false);
            self.visdisables(permitPeriodEdit && disableCount >= 0 && enableCount > 0 && rightDocumentsCount > 0);
            self.visenables(permitPeriodEdit && disableCount >= 0 && enableCount === 0 && rightDocumentsCount > 0);
            self.viscalculateDocuments(permitPeriodEdit);
            self.visdeleteCalculateDocument(false);
            self.visdeleteCalculateDocuments(permitPeriodEdit && rightDocumentsCount > 0);
            self.viscopy(false);
            self.viscopies(true);
        }
        self.vishelp(true);
        self.visrefresh(true);
        self.vistools(true);
    });
    self.init = function () {
        self.fillTableProperties();
        self.getRecords();
        self.getDynamicTable();
        self.getTreeList();
        self.getPeriodList();
        self.getFolderList();
        setTimeout(function () {
            self.getTreeFormulaSelectList();
        }, 350);
    };
    self.changeCalculateDocumentsStatus = function (dataList) {
        var itemList = self.multiCommandExecute("selectedItems");
        if (itemList && itemList.length) {
            for (var j = 0; j < itemList.length; j++) {
                if (dataList && dataList.length)
                    for (var i = 0; i < dataList.length; i++) {
                        if (itemList[j].id() === dataList[i].id)
                            itemList[j].documentCalculationState(dataList[i].documentCalculationState);
                    }
            }
        }
    };
}

