import { BaseViewModel } from '../master/baseViewModel.js';
import { SelectItem } from '../master/model';
import { ConsolidatePeriodsForm, OwnershipModel } from './model';
require('./model');
require('./resource');
export function ConsolidateViewModel() {
    var self = this;
    self.companySelectList = ko.observableArray();
    self.getCompanySelectList = function () {
        self.apiService.request({
            name: "/api/common/getcompanylist",
            data: { controllerName: 39 },
            success: function (data) {
                self.companySelectList.removeAll();
                if (_h.any(data))
                    for (var j = 0; j < data.length; j++) {
                        var target = data[j];
                        self.companySelectList.push(new SelectItem(target));
                    }
                self.companyId(null);
            },
            error: function (message, level) {
                toast.error("Company", 'getSelectList', "GroupCompanies");
            }
        });
    }
    self.updateConsolidateBtn = function () {
        self.getFormData(function (list) {
            if (Array.isArray(list)) {
                _h.kocnx()
                    .openForm(new ConsolidatePeriodsForm(self, list));
            } else {
                var message = _h.getApiMessage(list);
                _h.warningToast(message);
            }
        });
    }
    self.getFormData = function (callback) {
        self.apiService.request({
            name: "getSelectivePeriods",
            success: function (data) {
                callback(data);
            },
            error: function (message, level) {
                toast.error(self.entityName, 'get', "SelectivePeriods");
                callback(null);
            }
        });
    };
    self.updateConsolidate = function (parents, btnModel, e) {
        var formModel = parents[1];
        var list = formModel.toServer();
        if (list.length === 0)
            return;
        var model = {
            periodList: list
        };
        self.apiService.request({
            splashId: e,
            name: "post",
            data: model,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    _h.kocnx().checkProcessQueue(true);
                    localStorage.setItem("ProcessToken", "");
                }
            },
            error: function (message, level) {
                toast.error(self.entityName, 'putUpdate', "PostConsolidate");
            }
        });
    };
    self.toggleChildren = function (item) {
        if (item.childrenShow() === false) {
            item.childrenShow(true);
        } else {
            item.childrenShow(false);
        }
    };
    self.getOwnershipModel = function (item, callback) {
        self.apiService.request({
            name: "getOwnerShips",
            data: { companyId: item.companyId() },
            success: function (data) {
                callback(data);
            },
            error: function (message, level) {
                toast.error(self.entityName, 'get', "Ownership");
                callback(null);
            }
        });
    }
    self.setPercentOwnershipBtn = function () {
        var item = self.getSelectedRecord();
        self.getOwnershipModel(item, function (data) {
            if (data) {
                _h.kocnx()
                    .openForm(new OwnershipModel(self, data));
            }
        });
    }
    self.setPercentOwnership = function (parents, btnModel, e) {
        var item = parents[1];
        if (!item.checkValidCompanies())
            return;
        var model = item.toServer();
        self.apiService.request({
            splashId: e,
            name: "putOwnership",
            data: model,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    _h.kocnx().closeForm();
                    self.afterUpdate(data.models);
                    toast.success(self.entityName, 'putUpdate', "Ownership");
                }
            },
            error: function (message, level) {
                toast.error(self.entityName, 'putUpdate', "Ownership");
            }
        });
    };
    self.init = function () {
        self.fillTableProperties();
        self.getRecords();
        self.getCompanySelectList();
    };
    ko.utils.extend(self, new BaseViewModel({
        entityName: "Consolidate",
        getList: true,
        apiService: {
            actionList: ["filterby", "post", "getselectiveperiods", "getownerships", "putownership"]
        },
        extraParams: [],
        buttons: [
            { name: 'setPercentOwnership', access: true, icon: 'PercentOwnership', cMenu: true },
            { name: 'updateConsolidate', access: false, icon: 'Consolidate', cMenu: false },
            { name: 'help', access: false, cMenu: false },
            { name: 'refresh', access: false, cMenu: false },
            { name: 'tools', access: false, cMenu: false },
        ],
        filters: [
            { name: 'companyId', type: "select", source: self.companySelectList },
            { name: 'submitState' }
        ],
        sortDirection: "Ascending",
        sortProperty: "companyId",
        context: self,
        saveState: true,
        searchKeyType: "enter",
        cols: consolidateModelRes,

        selectRow: true,
        contextMenu: true,
        resizable: true

    }));
    self.btnVisibility = ko.computed(function () {
        var isSelected = self.isSelectedRecord();
        var permit = _h.kocnx().permitPeriodEdit();
        if (isSelected) {

            self.vissetPercentOwnership(permit);
        } else {
            self.vissetPercentOwnership(false);
        }
        self.vishelp(true);
        self.visrefresh(true);
        self.vistools(true);
        self.visupdateConsolidate(permit);
    });
    self.right = function () {
        var item = self.getSelectedRecord();
        if (!_h.isNullOrEmpty(item)) {
            if (item.childrenShow())
                item.childrenShow(false);
        }
    };
    self.left = function () {
        var item = self.getSelectedRecord();
        if (!_h.isNullOrEmpty(item)) {
            if (!item.childrenShow())
                item.childrenShow(true);
        }
    };
    self.consolidationProcessHandler = function (id, input, output, percent, title, processStatus, item) {
        var context = _h.kocnx();
        if (!context.showForm()) {
            _h.kocnx()
                .openForm(new ConsolidatePeriodsForm(self, null));
            context.formModel().fillInProgress({
                id: id,
                input: input,
                output: output,
                percent: percent,
                title: title,
                processStatus: processStatus,
                item: item
            });

        } else {
            context.formModel().fillInProgress({
                id: id,
                input: input,
                output: output,
                percent: percent,
                title: title,
                processStatus: processStatus,
                item: item
            });
        }
        if (percent === 100 || percent === "100")
            self.getRecords();
    }
}