require('./model');
require('./resource');
var { BaseViewModel } = require('../master/baseViewModel');
import { SelectItem, TreeMapSelect, TreeAdjustmentSelectItem } from '../master/model';

import { AdjustmentDocumentForm, AdjustmentDocumentItemViewModel } from './model';



export function AdjustmentDocumentViewModel(mode) {
    var self = this
    self.caption = ko.observable()
    self.viewMode = ko.observable(mode !== undefined ? mode : "Edit")
    self.trees = ko.observableArray()
    self.users = ko.observableArray()
    self.balancesheets = ko.observableArray()
    self.companies = ko.observableArray()
    self.consolidatedCompanies = ko.observableArray()
    self.getAdjustmentOptions = function () {
        self.apiService.request({
            name: "getAdjustmentOptions",
            success: function (data) {
                self.balancesheets.removeAll();
                self.companies.removeAll();
                self.trees.removeAll();
                self.consolidatedCompanies.removeAll();
                if (_h.any(data.balanceSheets))
                    for (var j = 0; j < data.balanceSheets.length; j++) {
                        var target = data.balanceSheets[j];
                        self.balancesheets.push(new TreeMapSelect(target));
                    }
                if (!_h.isNullOrEmpty(self["balanceSheetId"]) && self.viewMode() === "Edit")
                    self.balanceSheetId(null);

                if (_h.any(data.companies))
                    for (var m = 0; m < data.companies.length; m++) {
                        var company = data.companies[m];
                        self.companies.push(new SelectItem(company));
                    }
                if (!_h.isNullOrEmpty(self["companyId"]) && self.viewMode() === "Edit")
                    self.companyId(null);


                if (_h.any(data.trees))
                    for (var k = 0; k < data.trees.length; k++) {
                        var tree = data.trees[k];
                        self.trees.push(new TreeAdjustmentSelectItem(tree));
                    }

                if (_h.any(data.users))
                    for (var a = 0; a < data.users.length; a++) {
                        var user = data.users[a];
                        self.users.push(new SelectItem(user));
                    }

                if (_h.any(data.consolidatedCompanies))
                    for (var b = 0; b < data.consolidatedCompanies.length; b++) {
                        var consolidatedCompany = data.consolidatedCompanies[b];
                        self.consolidatedCompanies.push(new SelectItem(consolidatedCompany));
                    }


                if (!_h.isNullOrEmpty(self["treeId"]) && self.viewMode() === "Edit")
                    self.treeId(null);

            },
            error: function (message, level) {
            }
        });
    }
    self.copyBtn = function () {
        var item = self.multiCommandExecute("selectedRowRecord");
        var idList = [];
        idList.push(item.id());
        self.copyItems(idList);
    }
    self.copiesBtn = function () {
        var idList = self.multiCommandExecute("selectedItemIds");
        if (idList.length === 0) {
            var text = _h.getApiMessage("ActionSelectListEmptyError");
            _h.warningToast(text);
        } else {
            self.copyItems(idList);
        }
    }
    self.copyItems = function (idList) {
        var model = {
            idList: idList
        };
        self.apiService.request({
            name: "postCopy",
            data: model,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    if (idList.length === 1)
                        toast.success(self.entityName, 'custom', 'Copy');
                    if (idList.length > 1)
                        toast.success(self.entityName, 'custom', 'Copies');
                    self.afterCreate(data.models);
                }
            },
            error: function (message, status, xhr) {
                if (idList.length === 1)
                    toast.error(self.entityName, 'custom', 'Copy');
                if (idList.length > 1)
                    toast.error(self.entityName, 'custom', 'Copies');
            }
        });
    }
    self.createBtn = function () {
        self.getLastPriority(function (res) {
            _h.kocnx()
                .openForm(new AdjustmentDocumentForm(self, false, res));
        });
    }
    self.editBtn = function () {
        self.getLastPriority(function (res) {
            _h.kocnx()
                .openForm(new AdjustmentDocumentForm(self, true, res));
        });
    }
    self.temporaryBtn = function () {
        var item = self.multiCommandExecute("selectedRowRecord");
        var idList = [];
        idList.push(item.id());
        self.confirmList(idList, 1);
    }
    self.confirmedBtn = function () {
        var item = self.multiCommandExecute("selectedRowRecord");
        var idList = [];
        idList.push(item.id());
        self.confirmList(idList, 2);
    }
    self.temporarysBtn = function () {
        var idList = self.multiCommandExecute("selectedItemIds");
        if (idList.length === 0) {
            var text = _h.getApiMessage("ActionSelectListEmptyError");
            _h.warningToast(text);
        } else {
            self.confirmList(idList, 1);
        }
    }
    self.confirmedsBtn = function () {
        var idList = self.multiCommandExecute("selectedItemIds");
        if (idList.length === 0) {
            var text = _h.getApiMessage("ActionSelectListEmptyError");
            _h.warningToast(text);
        } else {
            self.confirmList(idList, 2);
        }
    }
    self.confirmList = function (ids, action) {
        var model = {
            idList: ids,
            confirmationState: action
        };
        self.apiService.request({
            name: "putConfirmationType",
            data: model,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    self.multiCommandExecute("changesLocalConfirmState", action, ids, data);
                }
            },
            error: function (message, status, xhr) {
            }
        });
    }
    self.createPdfBtn = function () {
        var item = self.multiCommandExecute("selectedRowRecord");
        if (item.itemsCount() <= 0) {
            toast.custom("error", _h.getApiMessage("RequiredItemCount" + self.entityName));
            return;
        }
        var model = {
            controllerName: 10,
            inputData: {
                id: item.id()
            }
        };
        _h.kocnx().createPdf(model);
    }
    self.toggleShowAll = function () {
        self.showAll(!self.showAll());
        self.getRecords();
    }
    self.callBackItemCountData = function (itemsCount) {
        self.selectedRowRecord().itemsCount(itemsCount);
    }
    self.createFiltersList = function () {
        var array;
        if (self.viewMode() === "Edit") {
            array = [
                { name: 'treeId' },
                { name: 'codeRange' },
                { name: 'userId' },
                { name: 'displayType' },
                { name: 'stateType' },
                { name: 'companyId' },
                { name: 'balanceSheetId' },
                { name: 'justIneffective', type: "bool" },
                { name: 'empty', type: "bool" },
                { name: 'withVariance', type: "bool" },
                { name: 'tags', type: "list", def: [] }
            ];
        } else {
            array = [
                { name: 'treeId', clear: true },
                { name: 'nodeId', clear: true },
                { name: 'userId' },
                { name: 'amountType', clear: true },
                { name: 'codeRange' },
                { name: 'isCreditor', clear: true },
                { name: 'displayType' },
                { name: 'showAll', def: false },
                { name: 'withVariance', type: "bool" },
                { name: 'justIneffective', type: "bool" },
                { name: 'empty', type: "bool" },
                { name: 'tags', type: "list", def: [] }
            ];
            if (_h.kocnx().loginCompanyType() === 0)
                array.push({ name: 'companyId', clear: true });
            else
                array.push({ name: 'balanceSheetId', clear: true });
        }
        return array;
    }
    self.createColList = function () {
        var array = [];
        for (var p in adjustmentdocumentModelRes) {
            if (adjustmentdocumentModelRes.hasOwnProperty(p)) {
                var target = adjustmentdocumentModelRes[p];
                if (_h.kocnx().loginCompanyType() === 0) {
                    if (target.colName !== "balanceSheetName")
                        array.push(target);
                } else {
                    if (target.colName !== "defaultCompanyName" && target.colName !== "amendmentType")
                        array.push(target);
                }
            }
        }
        return array;
    }
    self.createButtonList = function () {
        var array;
        if (self.viewMode() === "Edit") {
            array = [
                { 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: 'temporary', access: true, icon: 'DocTemporary', cMenu: true },
                { name: 'confirmed', access: true, icon: 'DocConfirm', cMenu: true },
                { name: 'temporarys', access: true, icon: 'DocsTemporary', cMenu: true },
                { name: 'confirmeds', access: true, icon: 'DocsConfirm', cMenu: true },
                { name: 'up', access: true, icon: 'Up', cMenu: true },
                { name: 'down', access: true, icon: 'Down', cMenu: true },
                { name: 'createPdf', access: true, icon: 'ExportPdf', cMenu: true },
                { name: 'help', access: false, cMenu: false },
                { name: 'refresh', access: false, cMenu: false },
                { name: 'tools', access: false, cMenu: false },
                { name: 'create', access: true, cMenu: false }
            ];
        } else {
            array = [
                { name: 'showAllSw', access: false, cMenu: false, templateName: "showAll-button-template" },
                { name: 'help', access: false, cMenu: false },
                { name: 'refresh', access: false, cMenu: false },
                { name: 'tools', access: false, cMenu: false }
            ];
        }
        return array;
    }
    self.changeChildModel = function (target, force) {
        if (self.childModel() && self.childModel().adjustmentId() === target.id() && !force)
            return;
        var adjustmentModel = new AdjustmentDocumentItemViewModel(self.viewMode());
        adjustmentModel.treeId(target.treeId());
        adjustmentModel.adjustmentId(target.id());
        adjustmentModel.adjustmentName(target.title());
        adjustmentModel.ineffective(target.ineffective());
        if (self["amountType"])
            adjustmentModel.amountType(self.amountType());
        adjustmentModel.displayType(self.displayType());
        adjustmentModel.parentModel = self;

        if (_h.kocnx().loginCompanyType() === 0) {
            adjustmentModel.companyId(self.companyId());
            if (!_h.isNullOrEmpty(target.defaultCompanyId()) && target.defaultCompanyId() > 0)
                adjustmentModel.defaultCompanyId(target.defaultCompanyId());
        }
        if (_h.kocnx().loginCompanyType() === 1) {
            adjustmentModel.balanceSheetId(target.balanceSheetId());
        }
        adjustmentModel.parentConfirmationState(target.confirmationState());
        if (target.stateType() === 0 || target.confirmationState() === 2)
            adjustmentModel.isRightEdit(false);
        else
            adjustmentModel.isRightEdit(true);
        if (self.viewMode() !== "Edit") {
            adjustmentModel.nodeId(self.nodeId());
        }

        self.childModel(adjustmentModel);
        self.childModel().init();
        if (self.viewMode() !== "Edit")
            self.caption(_h.getLocalizedText("reportBalanceAmendmentItemCaption") + target.title());
        self.childModel().iconSize("icon-image-small");
        if (!_h.isNullOrEmpty(self.groupProperty())) {
            ko.utils.arrayFilter(self.tableProperties(), function (item) {
                if (item.name === self.groupProperty()) {
                    item.visibleItem(true);
                }
            });
        }
    }
    ko.utils.extend(self, new BaseViewModel({
        entityName: "AdjustmentDocument",
        getList: true,
        apiService: {
            actionList: ["filterby",
                "post", "put", "getadjustmentoptions", "postcopy",
                "putconfirmationtype", "delete"]
        },
        filters: self.createFiltersList(),
        buttons: self.createButtonList(),
        extraParams: ["lastPriority", "searchProfiles"],
        sortDirection: "Ascending",
        sortProperty: "priority",
        context: self,
        saveState: true,
        filterBoxTemplate: "adjustment-filter-box-template",
        isMultiSelectRows: self.viewMode() === "Edit",
        cols: self.createColList(),
        selectRow: true,
        contextMenu: true,
        searchKeyType: "enter",
        tableClass: "table ko-tbl ko-tbl-master",
        styleRow: "styleRowValue",
        folderManagement: true,
        tableStyle: "margin-top:10px;font-size: 11px;",
        resizable: true
    }))
    if (self.viewMode() === "Edit") {
        self.btnVisibility = ko.computed(function () {
            var context = _h.kocnx();
            var permitPeriodEdit = context.permitPeriodEdit();
            var inListView = self.showType() === "List";
            var data = self.multiCommandExecute("btnVisibilityData2");
            if (_h.isNullOrEmpty(data))
                return;
            var temp = data[0];
            var enableCount = data[1];
            var disableCount = data[2];
            var selectedList = data[3];
            var temporaryCount = data[4];
            var confirmCount = data[5];
            if (selectedList === 0) {
                self.viscreate(permitPeriodEdit && !inListView);
                self.vistools(!inListView);
                self.visedit(false);
                self.visdelete(false);
                self.visup(false);
                self.visdown(false);
                self.viscreatePdf(false);
                self.vistemporarys(false);
                self.visconfirmeds(false);
                self.visdisables(false);
                self.visenables(false);
                self.vistemporary(false);
                self.visconfirmed(false);
                self.visdisable(false);
                self.visenable(false);
                self.viscopy(false);
                self.viscopies(false);
            }
            if (selectedList === 1) {
                var item = self.getSelectedRecord();
                if (item === null || item === undefined)
                    item = temp;
                var isEditable = item.isEditable();
                self.viscreate(permitPeriodEdit && !inListView);
                self.vistools(!inListView);
                self.visedit(permitPeriodEdit && isEditable && !inListView);
                self.visdelete(permitPeriodEdit && item.confirmationState() !== 2 && !inListView);
                self.visup(permitPeriodEdit && isEditable && item.priority() > 1 && !inListView);
                self.visdown(permitPeriodEdit && isEditable && self.lastPriority() !== item.priority() && !inListView);
                self.viscreatePdf(!inListView);
                self.vistemporarys(false);
                self.visconfirmeds(false);
                self.visdisables(false);
                self.visenables(false);
                self.vistemporary(permitPeriodEdit && temporaryCount >= 0 && confirmCount > 0 && !inListView);
                self.visconfirmed(permitPeriodEdit && temporaryCount >= 0 && confirmCount === 0 && !inListView);
                self.visdisable(permitPeriodEdit && disableCount >= 0 && enableCount > 0 && !inListView && item.confirmationState() !== 2);
                self.visenable(permitPeriodEdit && disableCount >= 0 && enableCount === 0 && !inListView && item.confirmationState() !== 2);
                self.viscopy(permitPeriodEdit && !inListView);
                self.viscopies(false);
            }
            if (selectedList > 1) {
                self.viscreate(false);
                self.vistools(!inListView);
                self.visedit(false);
                self.visdelete(false);
                self.visup(false);
                self.visdown(false);
                self.viscreatePdf(false);
                self.vistemporary(false);
                self.visconfirmed(false);
                self.visdisable(false);
                self.visenable(false);
                self.vistemporarys(permitPeriodEdit && temporaryCount >= 0 && confirmCount > 0 && !inListView);
                self.visconfirmeds(permitPeriodEdit && temporaryCount >= 0 && confirmCount === 0 && !inListView);
                self.visdisables(permitPeriodEdit && disableCount >= 0 && enableCount > 0 && !inListView);
                self.visenables(permitPeriodEdit && disableCount >= 0 && enableCount === 0 && !inListView);
                self.viscopy(false);
                self.viscopies(permitPeriodEdit && !inListView);
            }
            self.vishelp(!inListView);
            self.visrefresh(!inListView);
            self.vistools(true);
        });
    }
    else {
        self.getRecords = function () {
            var model = self.createFilterByModel();
            self.apiService.request({
                name: "filterBy",
                data: model,
                success: function (data) {
                    if (!_h.isNullOrEmpty(data)) {
                        self.records.removeAll();
                        var hasRec = false;
                        if (_h.any(data.list)) {
                            for (var j = 0; j < data.list.length; j++) {
                                var target = data.list[j];
                                var record = self.getInstance(target);
                                self.records.push(record);
                            }
                            hasRec = true;
                            _h.kocnx().showBalanceAdjustmentDocumentForm(true);
                        }
                        if (_h.any(data.groupList)) {
                            for (var k = 0; k < data.groupList.length; k++) {
                                var target2 = data.groupList[k];
                                var object = {
                                    title: target2.title,
                                    vis: ko.observable(false),
                                    list: ko.observableArray()
                                };
                                if (_h.any(target2.list))
                                    for (var i = 0; i < target2.list.length; i++) {
                                        var record2 = self.getInstance(target2.list[i]);
                                        object.list.push(record2);
                                    }
                                self.records.push(object);
                            }
                            hasRec = true;
                            _h.kocnx().showBalanceAdjustmentDocumentForm(true);
                            setTimeout(function () {
                                self.renderedHandler();
                            }, 300)
                        }
                        if (!hasRec) {
                            if (self.firstView === true) {
                                var text = _h.getApiMessage("GetAdjustmentDocumentDataFail");
                                _h.warningToast(text);
                                self.firstView = false;
                            }
                        } else {
                            self.firstView = false;
                        }
                        if (self.selectedRowRecord() !== null && self.selectedRowRecord() !== undefined)
                            self.selectedRowRecord().selected(false);
                        self.selectedRowRecord(null);
                        self.childModel(null);
                        self.total(data.total);
                    }
                    _h.initResizeTable();
                    _h.fixLabelsSize();
                },
                error: function (message, status, xhr) {
                    toast.error(self.entityName, 'getList');
                }
            });
        }
        self.btnVisibility = ko.computed(function () {
            self.vishelp(true);
            self.visrefresh(true);
            self.vistools(true);
        });
    }
    self.init = function () {
        self.fillTableProperties();
        self.getRecords();
        self.childModel(null);
        if (self.viewMode() === "Edit") {
            self.getAdjustmentOptions();
            self.getFolderList();
        } else {
            self.getAdjustmentOptions();
        }
    };
}