require('./model');
require('./resource');
import { BaseViewModel } from '../master/baseViewModel.js';
import { SelectItem, PeriodSelectItem } from '../master/model';
import { MagazineForm, MagazinePreview, MagazineFileViewModel } from './model';
import { RichTextEditor } from './richtextEditor.js';

export function MagazineViewModel() {
    var self = this;
    self.designMode = ko.observable(false);
    self.designSelectedModel = ko.observable();
    self.showDesignForm = ko.observable(false);
    self.designFormMagazineModel = ko.observable();
    self.currentPeriodId = ko.observable();
    self.currentPeriodTitle = ko.observable();
    self.firstComparativePeriod = ko.observable();
    self.secondComparativePeriod = ko.observable();
    self.thirdComparativePeriod = ko.observable();
    self.periodSelectedList = ko.observableArray();
    self.treeSelectList = ko.observableArray();
    self.getPeriodInfo = function (callback) {
        self.apiService.request({
            name: "getPeriodsInfo",
            data: model,
            success: function (data) {
                self.periodSelectedList.removeAll();
                if (_h.any(data.selectivePeriods))
                    for (var j = 0; j < data.selectivePeriods.length; j++) {
                        self.periodSelectedList.push(new PeriodSelectItem(data.selectivePeriods[j]));
                    }
                if (!_h.isNullOrEmpty(data.currentPeriodId))
                    self.currentPeriodId(data.currentPeriodId);
                if (!_h.isNullOrEmpty(data.currentPeriodTitle))
                    self.currentPeriodTitle(data.currentPeriodTitle);
                callback(data);
            },
            error: function (message, status, xhr) {
                var text = _h.getApiMessage("ErrorLoadPeriod");
                _h.failToast(text);
            }
        });
    };
    self.getTreeSelectList = function () {
        var model = {
            controllerName: 7,
            mappingType: 0
        };
        self.apiService.request({
            name: "getMappingTreeList",
            data: model,
            success: function (data) {
                self.treeSelectList.removeAll();
                if (_h.any(data))
                    for (var j = 0; j < data.length; j++) {
                        var target = data[j];
                        self.treeSelectList.push(new SelectItem(target));
                    }
            },
            error: function () {
                toast.error("Tree", 'getSelectList');
            }
        });
    }
    self.createBtn = function () {
        self.getPeriodInfo(function (data) {
            _h.kocnx()
                .openForm(new MagazineForm(self, false, data));
        });
    }
    self.editBtn = function () {
        self.getPeriodInfo(function (data) {
            _h.kocnx()
                .openForm(new MagazineForm(self, true, data));
        });
    }
    self.createPdfBtn = function () {
        var model = {};
        var data = clientStorage.getSetting("MagazinePdf");
        if (!_h.isEmpty(data)) {
            model = JSON.parse(data);
        }
        _h.kocnx()
            .openForm(new MagazinePreview(self, model));
    };
    self.createPdf = function (parents, btnModel, e) {
        var item = parents[1];
        var model = item.toServer();
     


        self.apiService.request({
            name: "/api/filegenerator/postmagazinepdf",
            data: model,
            success: function (data) {
                _h.kocnx().checkProcessQueue();
                localStorage.setItem("ProcessToken", "");
                _h.kocnx().closeForm();
            },
            error: function (message, status, xhr) {

            }
        });
    };
    self.createPdfSaveSetting = function (parents, btnModel, e) {
        var item = parents[1];
        var model = item.toServer();
        clientStorage.setSetting([{
            key: "MagazinePdf", value: JSON.stringify({
                displayType: model.displayType,
                amountType: model.amountType,
                pdfSaveState: model.pdfSaveState,
                magazinePageSelectionType: model.magazinePageSelectionType
            })
        }]);
        var text = _h.getApiMessage("MagazinePdfPageSaveMessage");
        _h.successToast(text);
    }
    self.designBtn = function () {
        self.getPagesMagazine(function (res) {
            if (res) {
                self.designSelectedModel(new RichTextEditor());
                self.designSelectedModel().magazine(self.selectedRowRecord());
                self.designSelectedModel().fillModel(res);
                self.designSelectedModel().init();
                self.designMode(true);
                window.resSecondDomain = 'pageeditor';
            }
        });
    };
    self.getPagesMagazine = function (callback) {
        var model = {
            id: self.selectedRowRecord().id()
        };
        self.apiService.request({
            name: "getPages",
            data: model,
            success: function (data) {
                callback(data);
            },
            error: function (message, status, xhr) {
                callback(null);
            }
        });
    }
    self.getSavedMagazinesBtn = function () {
        _h.kocnx()
            .openForm(new MagazineFileViewModel(self));
    }
    self.createHtmlBtn = function () {
        _h.kocnx().createHtml(7, self.selectedRowRecord().id());
    };
    ko.utils.extend(self, new BaseViewModel({
        entityName: "Magazine",
        getList: true,
        apiService: {
            actionList: ["filterby",
                "post", "put", "delete", "getpages", "getperiodsinfo"]
        },
        buttons: [
            { name: 'edit', access: true, icon: 'Edit', cMenu: true },
            { name: 'delete', access: true, icon: 'Delete', cMenu: true },
            { name: 'createPdf', access: true, icon: 'ExportPdf', cMenu: true },
            { name: 'createHtml', access: true, cMenu: true, icon: 'ExportHtml' },
            { name: 'design', access: true, icon: 'ReportDesign', cMenu: true },
            { name: 'getSavedMagazines', access: true, icon: 'FileList', 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 }
        ],
        filters: [{ name: 'companyType' }, { name: 'state' }, { name: 'currencyType' }],
        sortDirection: "Ascending",
        sortProperty: "id",
        context: self,
        saveState: true,
        searchKeyType: "enter",
        cols: magazineModelRes,
        selectRow: true,
        folderManagement: true,
        contextMenu: true,
        resizable: true
    }));
    self.btnVisibility = ko.computed(function () {
        var isSelected = self.isSelectedRecord();
        var permit = _h.kocnx().permitPeriodEdit();
        var isPeriodActive = _h.kocnx().periodItem().st === 1;
        if (isSelected) {
            self.visedit(permit);
            self.visdelete(permit);
            self.viscreatePdf(isPeriodActive);
            self.viscreateHtml(isPeriodActive);
            self.visdesign(isPeriodActive);
            self.visgetSavedMagazines(true);
        } else {
            self.visedit(false);
            self.visdelete(false);
            self.viscreatePdf(false);
            self.viscreateHtml(false);
            self.visdesign(false);
            self.visgetSavedMagazines(false);
        }
        self.viscreate(permit);
        self.vishelp(true);
        self.visrefresh(true);
        self.vistools(true);
    });
    self.backToTable = function () {
        self.designMode(false);
        window.resSecondDomain = '';
        self.designSelectedModel(null);
        $("body").css("overflow", "");
    };
    self.init = function () {
        self.fillTableProperties();
        self.getRecords();
        self.getTreeSelectList();
        self.getFolderList();
    }
}