require('./resource');
require('./model');

import { BaseViewModel } from '../master/baseViewModel';
import { PeriodSelectItem } from '../master/model';
import { HistoryViewModel, PeriodForm, ComparativePeriodsForm, SendPeriodForm, PeriodDeleteForm } from './model';

export function PeriodViewModel() {
    const self = this;
    self.selectList = ko.observableArray();
    self.filteredSelectList = ko.observableArray();
    self.getSelectList = function () {
        self.apiService.request({
            name: "/api/common/getperiodlist",
            data: { controllerName: this.controllerName },
            success: function (data) {
                self.selectList.removeAll();
                if (_h.any(data))
                    for (let j = 0; j < data.length; j++) {
                        var item = new PeriodSelectItem(data[j]);
                        self.selectList.push(item);
                    }
            },
            messageType: 'getSelectList',
            messageKey: self.entityName
        });
    };
    self.filterSelectList = function (notIncludeId) {
        self.filteredSelectList.removeAll();
        ko.utils.arrayFilter(self.selectList(),
            function (target) {
                if (target.value() !== notIncludeId)
                    self.filteredSelectList.push(target);
            });
    };
    self.toggleRight = function () {
        if (self.wideRight()) {
            if (self.isSelectedRecord()) {
                const selectedRecord = self.getSelectedRecord();
                self.wideRight(false);
                const model = new HistoryViewModel();
                model.periodId(selectedRecord.id());
                self.childModel(model);
                self.childModel().init();
                self.iconSize("icon-image-small");
            } else
                toast.custom("warning", _h.getApiMessage("firstSelectPeriodRecordWarning"));
        } else {
            self.wideRight(true);
            self.childModel(null);
            self.iconSize("icon-image");
        }
    };
    self.createBtn = function () {
        _h.kocnx()
            .openForm(new PeriodForm(self, false));
    };
    self.editBtn = function () {
        _h.kocnx()
            .openForm(new PeriodForm(self, true));
    };
    self.resetSelectedTableTemplate = function () {
        clientStorage.removeSetting("RepGenAutoSave");
        clientStorage.removeSetting("TableTemplateEditList");
    };
    self.getComparativesData = function (id, callback) {
        self.apiService.request({
            name: "getForComparatives",
            data: { id: id },
            success: function (data) {
                callback(data);
            },
            error: function (data) {
                toast.error(self.entityName, 'get', 'Comparatives');
                callback(null);
            },
            messageType: 'get',
            messageKey: "Comparatives"
        });
    };
    self.comparativesBtn = function () {
        const selectedRecord = self.getSelectedRecord();
        self.getComparativesData(selectedRecord.id(),
            function (data) {
                self.selectList.removeAll();
                if (_h.any(data.list))
                    for (let j = 0; j < data.list.length; j++) {
                        self.selectList.push(new PeriodSelectItem(data.list[j]));
                    }
                self.filterSelectList(selectedRecord.id());
                _h.kocnx()
                    .openForm(new ComparativePeriodsForm(self, data));
            });
    };
    self.editComparatives = function (parents, btnModel, e) {
        var item = parents[1];
        if (!item.validationObject.isValid()) {
            item.validationObject.errors.showAllMessages();
            return false;
        }
        const comparatives = item.toServer();
        self.apiService.request({
            splashId: e,
            name: "putComparatives",
            data: comparatives,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    self.afterUpdate(data.models);
                    _h.kocnx().closeForm();
                    toast.success(self.entityName, 'putUpdate', 'Comparatives');
                    self.updateExtraParams(data);
                }
            },
            messageType: 'putUpdate',
            messageKey: "Comparatives"
        });
    };
    self.closeBtn = function () {
        self.changeClosed(true);
    };
    self.openBtn = function () {
        self.changeClosed(false);
    };
    self.changeClosed = function (action) {
        const selectedRecord = self.getSelectedRecord();
        const model = {
            id: selectedRecord.id(),
            closed: action
        };
        self.apiService.request({
            name: "putClosed",
            data: model,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    toast.success(self.entityName, 'putUpdate', 'PeriodClosed');
                    selectedRecord.closed(action);
                }
            },
            messageType: 'putUpdate',
            messageKey: "PeriodClosed"
        });
    };
    self.sendBtn = function () {
        const selectedRecord = self.getSelectedRecord();
        _h.kocnx()
            .openForm(new SendPeriodForm(self,
                {
                    submittedMagazine: selectedRecord.submittedMagazine(),
                    id: selectedRecord.id()
                }));
    };
    self.send = function (parents, btnModel, e) {
        var item = parents[1];
        if (!item.validationObject.isValid()) {
            item.validationObject.errors.showAllMessages();
            return false;
        }
        self.changeSubmitState(1, item.magazineFileId());
    };
    self.tackBackBtn = function () {
        self.changeSubmitState(0);
    };
    self.changeSubmitState = function (action, magazineFileId) {
        const selectedRecord = self.getSelectedRecord();
        const model = {
            id: selectedRecord.id(),
            submitState: action,
            magazineFileId: magazineFileId
        };
        self.apiService.request({
            name: "putSubmit",
            data: model,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    _h.kocnx().closeForm();
                    toast.success(self.entityName, 'putUpdate', 'SubmitState');
                    selectedRecord.submitState(action);
                }
            },
            messageType: 'putUpdate',
            messageKey: "SubmitState"
        });
    };
    self.archiveBtn = function () {
        self.changeArchiveState(true);
    };
    self.unArchiveBtn = function () {
        self.changeArchiveState(false);
    };
    self.changeArchiveState = function (action) {
        const selectedRecord = self.getSelectedRecord();
        self.apiService.request({
            name: "putArchivePeriod",
            data: { id: selectedRecord.id() },
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    toast.success(self.entityName, 'putUpdate', 'PeriodArchive');
                    if (self.showArchived())
                        selectedRecord.archived(action);
                    else
                        self.records.remove(selectedRecord);
                }
            },
            messageType: 'putUpdate',
            messageKey: "PeriodArchive"
        });
    };
    self.copyBtn = function () {
        const selectedRecord = self.getSelectedRecord();
        self.getCopyDependencies(selectedRecord.id(), function (res) {
            _h.kocnx()
                .openForm(new PeriodForm(self, false, true, res));
        });
    };
    self.copy = function (parents, btnModel, e) {
        var item = parents[1];
        if (!item.validationObject.isValid()) {
            item.validationObject.errors.showAllMessages();
            if (item.periodCopyType() === 1 &&
                item.copyMode() === true &&
                !_h.isNullOrEmpty(item.destinationPeriodId())) {
                //
            } else {
                return false;
            }
        }
        const period = item.toServer();
        if (period === null) {
            return false;
        }
        self.apiService.request({
            splashId: e,
            name: "postCopy",
            data: period,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    _h.kocnx().closeForm();
                    self.afterCreate(data.models);
                    toast.success(self.entityName, 'custom', 'CopyPeriod');
                    const context = _h.kocnx();
                }
            },
            messageType: 'custom',
            messageKey: "CopyPeriod"
        });
    };
    self.getDeleteModel = function (id, callback) {
        self.apiService.request({
            name: "getPeriodSummary",
            data: { id: id },
            success: function (data) {
                callback(data);
            },
            error: function () {
                toast.error(self.entityName, 'get', 'PeriodSummary');
                callback(null);
            }
        });
    };
    self.getCopyDependencies = function (id, callback) {
        self.apiService.request({
            name: "getCopyDependancies",
            data: { id: id },
            success: function (data) {
                callback(data);
            },
            error: function () {
                toast.error(self.entityName, 'get', 'CopyDependencies');
                callback(null);
            },
            messageType: 'off'
        });
    };
    self.init = function () {
        self.fillTableProperties();
        self.getRecords();
        self.getSelectList();
    };
    ko.utils.extend(self, new BaseViewModel({
        entityName: "Period",
        getList: true,
        apiService: {
            actionList: ["filterby",
                "post", "put", "delete", "getforcomparatives",
                "putcomparatives", "putclosed"
                , "putsubmit", "putarchiveperiod", "getperiodsummary"
                , "getcopydependancies", "getsavedmagazines", "gethistory", "postcopy", "getparentperiodlist"]
        },
        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: 'comparatives', access: true, icon: 'Comparatives', cMenu: true },
            { name: 'close', access: true, icon: 'ClosePeriod', cMenu: true },
            { name: 'open', access: true, icon: 'OpenPeriod', cMenu: true },
            { name: 'send', access: true, icon: 'SendPeriod', cMenu: true },
            { name: 'tackBack', access: true, icon: 'TakebackPeriod', cMenu: true },
            { name: 'archive', access: true, icon: 'Archive', cMenu: true },
            { name: 'unArchive', access: true, icon: 'UnArchive', cMenu: true },
            { name: 'copy', access: true, icon: 'Copy', 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 }
        ],
        filters: [
            { name: 'auditState', type: "select", source: auditStates },
            { name: 'periodType', type: "select", source: periodTypes },
            { name: 'periodState', type: "select", source: periodStates },
            { name: 'submitState', type: "select", source: submitStates },
            { name: 'stateType', type: "select", source: stateTypes },
            { name: 'closed', type: "select", source: [{ text: 'بسته', value: 'true' }, { text: 'باز', value: 'false' }] },
            { name: 'year' },
            { name: 'month' },
            { name: 'day' },
            { name: 'fullDate', type: "template", template: "fulldatefilter-template" },
            { name: 'showArchived', type: "bool" },
        ],
        searchKeyType: "enter",
        styleRow: "styleRowValue",
        sortDirection: "Ascending",
        sortProperty: "id",
        tableClass: "table ko-tbl period-tbl",
        tableStyle: "font-size: 11px;",
        context: self,
        cols: periodModelRes,
        saveState: true,
        selectRow: true,
        contextMenu: true,
        resizable: true
    }));
    self.btnVisibility = ko.computed(function () {
        const isSelected = self.isSelectedRecord();
        const item = self.getSelectedRecord();
        if (isSelected) {
            const closed = item.closed();
            const archive = item.archived();
            const submitState = item.submitState();
            self.visedit(!closed);
            self.visdelete(!closed);
            self.visarchive(!archive && submitState !== 1);
            self.visunArchive(archive && submitState !== 1);
            self.visclose(!closed);
            self.visopen(closed && !archive && submitState !== 1 && submitState !== 2);
            self.vistackBack(submitState === 1);
            self.vissend(closed && (!archive && submitState === 0 || submitState === 3));
            self.viscomparatives(!closed);
            self.viscopy(true);
            self.visdisable(item.stateType() === 1);
            self.visenable(item.stateType() === 0);
        } else {
            self.visedit(false);
            self.visdelete(false);
            self.viscomparatives(false);
            self.visclose(false);
            self.visopen(false);
            self.vissend(false);
            self.vistackBack(false);
            self.visarchive(false);
            self.visunArchive(false);
            self.viscopy(false);
            self.visdisable(false);
            self.visenable(false);
        }
        self.viscreate(true);
        self.vishelp(true);
        self.visrefresh(true);
        self.vistools(true);
    });
    self.deleteBtn = function () {
        const selectedRecord = self.getSelectedRecord();
        self.getDeleteModel(selectedRecord.id(),
            function (data) {
                if (data !== null) {
                    _h.kocnx()
                        .openForm(new PeriodDeleteForm(self, selectedRecord, data));
                }
            });
    };
    self.delete = function (parents, btnModel, e) {
        var item = parents[1];
        const model = item.toServer();
        self.apiService.request({
            splashId: e,
            name: "delete",
            data: model,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    if (data.completeDelete === true) {
                        self.afterDelete(model.id, data.models);
                        const context = _h.kocnx();
                        context.headerSection.resetActiveSelectMenu();
                        toast.success(self.entityName, 'del');
                        self.selectedRecord(null);
                        self.selectedRowRecord(null);
                    } else {
                        toast.custom("success", _h.getApiMessage("PeriodHalfDeletedSuccess"));
                    }
                    _h.kocnx().closeForm();
                    self.resetSelectedTableTemplate();
                }
            },
            messageType: 'del',
            messageKey: self.entityName
        });
    };
}