var { BaseModel, BaseFormModel, FormBuilder, BaseSecondaryForm, BaseInnerModel } = require('../master/baseModels.js');
import { ApiService } from "../../util/apiService.js";
require('knockout.validation');
import { BaseViewModel } from '../master/baseViewModel.js';

export class TreeSmall extends BaseInnerModel {
    constructor(model) {
        super(model);
    }
}
export class Magazine extends BaseModel {
    constructor(model) {
        super(model);
    }
    shortName(name) {
        if (!name)
            return "";
        if (name.length < 20)
            return name;
        return name.substr(0, 17) + "...";
    };

    refreshModel(model) {
        _autoMapper.fillModel(this, model);
    }
}
export class MagazineForm extends BaseFormModel {
    constructor(viewModel, editMode, data) {
        super(viewModel, editMode);
        this.currentPeriodTitle = data.currentPeriodTitle;
        this.showComparativePeriod = ko.observable(true);
        this.oldList = data.comparativePeriods;
        this.periodsMax = data.comparativePeriods.length + 1;
        if (!editMode) {
            this.editMode(false);
            this.autoSetComparatives(false);
            this.periodsCount(1);
            this.periodId(data.currentPeriodId);
            this.startPageNumber(1);
            this.folderId(null);
            if (_h.any(data.comparativePeriods))
                for (var i = 0; i < data.comparativePeriods.length; i++) {
                    this[data.comparativePeriods[i].order + "ComparativePeriod"] = ko.observable(data.comparativePeriods[i].id);
                    this["visCP" + data.comparativePeriods[i].order] = ko.observable(true);
                }

            this.periodsCount(data.comparativePeriods.length + 1);
        }
        else {
            if (_h.any(data.comparativePeriods))
                for (var j = 0; j < data.comparativePeriods.length; j++) {
                    if (this.comparativePeriods() && this.comparativePeriods().length >= j + 1) {
                        this[data.comparativePeriods[j].order + "ComparativePeriod"] = ko.observable(this.comparativePeriods()[j].id);
                    } else {
                        this[data.comparativePeriods[j].order + "ComparativePeriod"] = ko.observable(data.comparativePeriods[j].id);
                    }
                    this["visCP" + data.comparativePeriods[j].order] = ko.observable(true);
                }

        }
        this.setVisComparativePeriods(this.periodsCount());
        this.periodsCount.subscribe(function (newValue) {
            if (newValue) {
                this.setVisComparativePeriods(newValue);
            }
        }, this);
        this.condFirst = ko.computed(function () {
            return this.magazineType() === 1;
        }, this);
        this.condSecond = ko.computed(function () {
            return this.magazineType() === 0;
        }, this);
        this.condThird = ko.computed(function () {
            return this.autoSetComparatives();
        }, this);

        if (!editMode) {
            this.setValidationObject(data.comparativePeriods);
        } else {
            this.setValidationObject(this.comparativePeriods());
        }

        this.createForm();
    }
    setVisComparativePeriods(newValue) {
        for (const key of Object.keys(this)) {
            var numb = key.match(/\d/g);
            if (numb && numb.length && key.indexOf("visCP") !== -1) {
                if (numb.length > 1) {
                    numb = numb[0] + numb[1];
                } else {
                    numb = numb[0];
                }
                numb = Number(numb);
                if (numb < Number(newValue)) {
                    this[key](true);
                } else {
                    this[key](false);
                }
            }
        }
        if (this.showComparativePeriod()) {
            $(".cp-box").css("display", "block");
        } else {
            $(".cp-box").css("display", "none");
        }
    }
    setValidationObject(comparativePeriods) {
        var self = this;
        var obj = {
            title: self.title.extend({
                required: true,
                minLength: 3,
                maxLength: 100,
                validCharacterName: true,
                remoteIsUniqueRule: { params: [self.id, "Magazine", "title", "remotePlaceHolder"] }
            }),
            magazineType: self.magazineType.extend({
                required: true
            }),
        };


        for (var i = 0; i < comparativePeriods.length; i++) {
            var params = [];
            for (var j = 0; j < comparativePeriods.length; j++) {
                if (comparativePeriods[j].order !== comparativePeriods[i].order) {
                    params.push(self[comparativePeriods[j].order + "ComparativePeriod"]);
                }
            }
            obj[comparativePeriods[i].order + "ComparativePeriod"] = self[comparativePeriods[i].order + "ComparativePeriod"].extend({
                required: {
                    onlyIf: function () {
                        return self.magazineType() === 0 && self.periodsCount() > i;
                    }
                },
                noEqualPeriod: {
                    onlyIf: function () {
                        return self.magazineType() === 0 && self.periodsCount() > i;
                    },
                    params: { params: params }
                }
            });

        }


        self.validationObject = ko.validatedObservable(obj);
    }
    getLastOrder() {
        var number = 0;
        for (const key of Object.keys(this)) {
            const char = key.slice(0, 2);
            var numb = char.match(/\d/g);
            if (numb && numb.length && key.indexOf("ComparativePeriod") !== -1) {
                var number = parseFloat(char.replace(/[^0-9]/g, ''));
                this[key]();
            }
        }
        return number;
    }
    getComparativePeriodsList() {
        var array = [];
        var order = this.getLastOrder();
        for (var f = 0; f < order; f++) {
            array.push({ order: f + 1, id: this[(f + 1) + "ComparativePeriod"]() });
        }
        return array;
    }
    toogleShowComparativeperiod() {
        if (this.showComparativePeriod()) {
            this.showComparativePeriod(false);
            $(".cp-box").css("display", "none");
        } else {
            this.showComparativePeriod(true);
            $(".cp-box").css("display", "block");
        }
    }
    toggleAutoSetComparatives() {
        this.autoSetComparatives(!this.autoSetComparatives());
    }
    createForm() {
        const controls = [
            this.createLine({ t: 'txb', val: this.title },
                { t: 'slc', val: this.magazineType, options: magazineTypes, dis: this.editMode }),
            this.createLine({ t: 'slc', val: this.folderId, options: this.parentVM.folderList },
                { t: 'tsp', val: this.startPageNumber, min: 1, max: 1000 }, this.condFirst, 30),
            this.createLine({ t: 'slc', val: this.folderId, options: this.parentVM.folderList },
                null, this.condSecond, 30),
            this.createLine({ t: 'tsp', val: this.periodsCount, min: 1, max: this.periodsMax, dis: this.condThird },
                { t: 'chk', val: this.autoSetComparatives, click: this.toggleAutoSetComparatives }, this.condSecond, 30),
            this.createLine({ t: 'lbl', val: this.currentPeriodTitle },
                { t: 'tsp', val: this.startPageNumber, min: 1, max: 1000 }, this.condSecond, 30),
            this.createLine({ t: 'tm', templateName: 'show-comparativeperiod-form-t' }, undefined, this.condSecond, 30, 0)
        ];

        for (const key of Object.keys(this)) {
            const char = key.slice(0, 2);
            var numb = char.match(/\d/g);
            if (numb && numb.length && key.indexOf("ComparativePeriod") !== -1) {
                if (numb.length > 1) {
                    numb = numb[0] + numb[1];
                }
                controls.push(this.createLine({
                    t: 'slc', val: this[key],
                    options: this.parentVM.periodSelectedList,
                    renderFunc: _h.periodSelectRowTemplate,
                    dis: this.condThird
                }, null, this["visCP" + numb], 30, 0, "row cp-box"));
            }
        }
        this.formControls(controls);
        this.formButtons({
            name: 'footer-form-t', data: {
                buttons: [
                    { name: 'create', vis: !this.editMode(), click: this.parentVM.create },
                    { name: 'edit', vis: this.editMode, click: this.parentVM.edit },
                    { name: 'cancel', click: _h.kocnx().closeForm }]
            }
        });
        setTimeout(function () {
            this.toogleShowComparativeperiod();
        }.bind(this), 150)
    }
    toServer() {
        var array = [];
        for (const key of Object.keys(this)) {
            var numb = key.match(/\d/g);
            if (numb && numb.length && key.indexOf("visCP") !== -1) {
                if (numb.length > 1) {
                    numb = numb[0] + numb[1];
                } else {
                    numb = numb[0];
                }
                if (this[key]()) {
                    array.push({ order: numb, id: this[numb + "ComparativePeriod"]() });
                }
            }
        }

        return {
            id: this.id(),
            title: this.title(),
            folderId: this.folderId(),
            periodId: this.periodId(),
            periodsCount: this.periodsCount(),
            magazineType: this.magazineType(),
            startPageNumber: this.startPageNumber(),
            autoSetComparatives: this.autoSetComparatives(),
            comparativePeriods: array
        };
    }

}
export class MagazineFileViewModel extends FormBuilder {
    constructor() {
        super();
        this.width = "1000px";
        this.caption = ko.observable(" فهرست مجله های " + _h.kocnx().periodItem().t);
        ko.utils.extend(this, new BaseViewModel({
            entityName: "MagazineFile",
            getList: true,
            apiService: {
                actionList: ["filterby", "deletepdf"]
            },
            buttons: [
                { name: 'downloadPdf', access: true, icon: 'ExportPdf', cMenu: true },
                { name: 'deletePdf', access: true, icon: 'Delete', cMenu: true },
                { name: 'refresh', access: false, cMenu: false }
            ],
            filters: [{ name: 'magazineId' }],
            sortDirection: "Ascending",
            sortProperty: "magazineTitle",
            tableStyle: "table-layout: fixed;",
            context: this,
            searchKeyType: "enter",
            saveState: true,
            cols: savemagazineModelRes,
            selectRow: true,
            contextMenu: true
        }));
        this.btnVisibility = ko.computed(function () {
            var isSelected = this.isSelectedRecord();
            this.visdownloadPdf(isSelected);
            this.visdeletePdf(isSelected);
            this.visrefresh(true);
        }.bind(this));
        this.fillTableProperties();
        this.createForm();
        this.getRecords();
    }
    downloadPdfBtn() {
        var item = this.getSelectedRecord();
        _h.downloadFile(item.fileCode());
    }
    deletePdfBtn() {
        var item = this.getSelectedRecord();
        this.apiService.request({
            name: "deletePdf",
            data: {
                id: item.id()
            },
            success: function (data) {
                this.records.remove(item);
                var successText = _h.getApiMessage("DeleteMagazinePdfFileSuccess");
                _h.successToast(successText);
            }.bind(this),
            error: function (message, status, xhr) {
                var text = _h.getApiMessage("DeleteMagazinePdfFileError");
                _h.failToast(text);
            }
        });
    }
    createForm() {
        const controls = [
            this.createLine({ t: 'tm', templateName: 'savemagazine-form-t' }, undefined, true, 0, 0),
        ];
        this.formControls(controls);
        this.formButtons({
            name: 'footer-form-t', data: {
                buttons: [
                    { name: 'cancel', click: _h.kocnx().closeForm }]
            }
        });
    }
}
export class MagazineDownloadFile extends BaseSecondaryForm {
    constructor(viewModel, saveData) {
        super(viewModel,
            [
                { name: "displayType", type: "ob", val: 1 },
                { name: "amountType", type: "ob", val: 2 }
            ],
            "DownloadFileCaption");

        if (saveData.displayType)
            this.displayType(saveData.displayType);
        if (saveData.amountType)
            this.amountType(saveData.amountType);

        this.width = "400px";
        this.createForm();
    }
    createForm() {
        const controls = [
            this.createLine({ t: 'rdo', val: this.displayType, list: displayTypes2 },
                null, true, 30),
            this.createLine({ t: 'rdo', val: this.amountType, list: amountTypes },
                null, true, 30)
        ];
        this.formControls(controls);
        this.formButtons({
            name: 'footer-form-t', data: {
                buttons: [
                    { name: "custom", resText: 'downloadPdfBtn', vis: true, click: this.parentVM.toPdf },
                    { name: "custom", resText: 'SaveSettingExPdfBtn', vis: true, click: this.parentVM.toPdfSaveSetting },
                    { name: 'cancel', click: _h.kocnx().closeForm }
                ]
            }
        });
    }
}
export class MagazinePreview extends BaseSecondaryForm {
    constructor(viewModel, model) {
        super(viewModel,
            [
                { name: "id", type: "ob" },
                { name: "displayType", type: "ob", val: 1 },
                { name: "amountType", type: "ob", val: 2 },
                { name: "pdfSaveState", type: "ob", val: 1 },
                { name: "pageSelectionType", type: "ob", val: 1 },
                { name: "magazineType", type: "ob" },
                { name: "selectedPages", type: "ob" },
                { name: "title", type: "ob" },
                { name: "description", type: "ob" }

            ], "MagazinePreviewCaption");
        var selectedRecord = viewModel.getSelectedRecord();
        this.id(selectedRecord.id());
        this.magazineType(selectedRecord.magazineType());
        if (model.displayType)
            this.displayType(model.displayType);
        if (model.amountType)
            this.amountType(model.amountType);
        if (model.pdfSaveStates)
            this.pdfSaveStates(model.pdfSaveStates);
        if (model.pdfSaveStates)
            this.pdfSaveStates(model.pdfSaveStates);
        if (model.pageSelectionType)
            this.pageSelectionType(model.pageSelectionType);

        this.createForm();
    }
    createForm() {
        const controls = [
            this.createLine({ t: 'rdo', val: this.displayType, list: displayTypes2 },
                null, true, 30),
            this.createLine({ t: 'rdo', val: this.amountType, list: amountTypes },
                null, true, 30),
            this.createLine({ t: 'rdo', val: this.pdfSaveState, list: pdfSaveStates },
                null, true, 30),
            this.createLine({ t: 'tm', templateName: 'pdfSaveState-form-t' }, undefined, true, 0, 0),

            this.createLine({ t: 'rdo', val: this.pageSelectionType, list: pageSelectionTypeTypes },
                null, this.magazineType() === 0, 30),

            this.createLine({ t: 'tm', templateName: 'selectedPages-form-t' }, undefined, true, 0, 0),
        ];
        this.formControls(controls);
        this.formButtons({
            name: 'footer-form-t', data: {
                buttons: [
                    { name: "custom", resText: 'downloadPdfBtn', vis: true, click: this.parentVM.createPdf },
                    { name: "custom", resText: 'SaveSettingExPdfBtn', vis: true, click: this.parentVM.createPdfSaveSetting },
                    { name: 'cancel', click: _h.kocnx().closeForm }
                ]
            }
        });
    }
}