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

export class Consolidate extends BaseModel {
    constructor(model) {
        super(model);
        this.companies = ko.observableArray();
        if (_h.any(model.companies))
            for (var j = 0; j < model.companies.length; j++) {
                var record = new Consolidate(model.companies[j]);
                this.companies.push(record);
            }
        this.childrenShow = ko.observable(false);
    }
    refreshModel(model) {
        this.companies.removeAll();
        var companies = ko.toJS(model.companies);
        delete model["companies"];
        _autoMapper.fillModel(this, model);
        if (_h.any(companies))
            for (let j = 0; j < companies.length; j++) {
                var record = new Consolidate(companies[j]);
                this.companies.push(record);
            }
    }
}

export class OwnershipModel extends BaseSecondaryForm {
    constructor(viewModel, model) {
        super(viewModel, [
            { name: "ownerId", type: "ob", val: model.ownerId },
            { name: "ownerName", type: "ob", val: model.ownerName },
            { name: "companies", type: "obar" },
        ],
            "setPercentOwnershipCaption");
        this.width = "600px";
        if (_h.any(model.companies)) {
            for (var j = 0; j < model.companies.length; j++) {
                var target = model.companies[j];
                var record = new OwnershipCompany(target);
                this.companies.push(record);
            }
        }
        this.createForm();
    }

    checkValidCompanies() {
        var res = true;
        ko.utils.arrayFilter(this.companies(), function (company) {
            if (!company.validationObject.isValid()) {
                company.validationObject.errors.showAllMessages();
                res = false;
            }
        });
        return res;
    }

    toServer() {
        var model = {
            ownerId: this.ownerId(),
            ownerName: this.ownerName(),
            companies: []
        }
        ko.utils.arrayFilter(this.companies(), function (company) {
            model.companies.push({
                affiliateId: company.affiliateId(),
                affiliateName: company.affiliateName(),
                directOwnership: company.directOwnership()
            });
        });
        return model;
    }

    createForm() {
        const controls = [
            this.createLine({ t: 'tm', templateName: 'ownership-content-form-t' }, undefined, true, 30, 30),
        ];
        this.formControls(controls);
        this.formButtons({
            name: 'footer-form-t', data: {
                buttons: [
                    { name: 'custom', resText: "editFormBtn", vis: true, click: this.parentVM.setPercentOwnership },
                    { name: 'cancel', click: _h.kocnx().closeForm }]
            }
        });
    }
}

export class OwnershipCompany extends BaseInnerModel {
    constructor(model) {
        super(model);
        this.acceptableValue = model.acceptableValue;
        this.setValidationObject();
    }

    setValidationObject() {
        var self = this;
        this.validationObject = ko.validatedObservable({
            directOwnership: self.directOwnership.extend({
                onlyDecimal: true,
                max: 100
            })
        });
    }
}

export class ConsolidatePeriodsForm extends BaseSecondaryForm {
    constructor(viewModel, list) {
        super(viewModel, [
            { name: "inProgress", type: "ob", val: false },
            { name: "percent", type: "ob", val: 0 },
            { name: "processStatus", type: "ob" },
            { name: "processItem", type: "", val: null },
            { name: "searchKey", type: "ob" },
            { name: "resultList", type: "obar" },
            { name: "companies", type: "obar" }
        ], "updateConsolidateCaption");
        this.width = "800px";
        if (_h.any(list)) {
            for (var j = 0; j < list.length; j++) {
                var target = list[j];
                var record = new CompanySelectivePeriods(target);
                this.companies.push(record);
            }
            if (this.companies().length) {
                var first = this.companies()[0];
                first.visible(true);
            }
        }

        this.searchKey.subscribe(function (newVal) {
            ko.utils.arrayFilter(this.companies(), function (company) {
                if (company.companyName().indexOf(newVal) !== -1 || _h.isNullOrEmpty(newVal))
                    company.searchRes(true);
                else
                    company.searchRes(false);
            });
        }.bind(this));
        this.isNotProgressMode = ko.pureComputed(function () {
            return this.inProgress() === false;
        }.bind(this));
        this.inProgressMode = ko.pureComputed(function () {
            return this.inProgress() === true;
        }.bind(this));

        this.createForm();
    }
    expandAll() {
        ko.utils.arrayFilter(this.companies(), function (company) {
            company.visible(true);
        });
    }
    collapseAll() {
        ko.utils.arrayFilter(this.companies(), function (company) {
            company.visible(false);
        });
    }
    fillInProgress(model) {
        this.processItem = model.item;
        this.percent(model.percent);
        this.processStatus(model.processStatus);
        this.resultList.removeAll();
        if (model.output && model.output.length > 0)
            for (var i = 0; i < model.output.length; i++) {
                var item = new ConsolidationProcessStep(model.output[i]);
                this.resultList.push(item);
            }
        this.inProgress(true);
    }
    onClickNodes(val) {
        var ul = $("#group_step").find("ul");
        if (ul) {
            ul.find("li").removeClass("dsb-active");
            var liList = ul.find("li");
            for (var i = 0; i < liList.length; i++) {
                if ($(liList[i]).attr("data-id") === "" + val)
                    $(liList[i]).addClass("dsb-active");
            }
        }

        if (this.companies().length)
            for (var j = 0; j < this.companies().length; j++) {
                var target = this.companies()[j];
                if (target.periods().length === 1) {
                    target.periods()[0].step(Number(val));
                    target.periods()[0].changeStep(Number(val));
                    target.visible(true);
                }

                if (target.periods().length > 1) {
                    for (var k = 0; k < target.periods().length; k++) {
                        if (target.periods()[k].step() > 0) {
                            target.periods()[k].step(Number(val));
                            target.periods()[k].changeStep(Number(val));
                            target.visible(true);
                        }
                    }
                }

            }
    }
    toServer = function () {
        var array = [];
        ko.utils.arrayFilter(this.companies(),
            function (company) {
                var list = company.collectData();
                $.each(list, function (i, p) {
                    array.push(p);
                });
            });
        return array;
    };
    onCancel() {
        _h.kocnx().processManagement().cancelBtn(this.processItem);
    }
    createForm() {
        const controls = [
            this.createLine({ t: 'tm', templateName: 'consolidateperiods-form-t' }, undefined, true, 30, 30),
        ];
        this.formControls(controls);
        this.formButtons({
            name: 'footer-form-t', data: {
                buttons: [
                    { name: 'custom', resText: "editFormBtn", vis: this.isNotProgressMode, click: this.parentVM.updateConsolidate },
                    { name: 'custom', resText: "cancelProgressBtn", vis: this.inProgressMode, click: this.onCancel.bind(this) },
                    { name: 'cancel', click: _h.kocnx().closeForm }]
            }
        });
    }
}

export function CompanySelectivePeriods(model) {
    var self = this;
    self.searchRes = ko.observable(true);
    self.visible = ko.observable(false);
    self.selectedPeriod = ko.observable();
    self.count = ko.observable(model.count);
    self.companyId = ko.observable(model.companyId);
    self.companyName = ko.observable(model.companyName);
    self.periods = ko.observableArray();
    self.periodSelectedText = ko.computed(function () {
        if (_h.isNullOrEmpty(self.selectedPeriod()))
            return "";
        return self.selectedPeriod().title().replace("سال مالی منتهی به", "") + " - " +
            _h.getEnumText(consolidationSteps, self.selectedPeriod().step());
    });
    if (_h.any(model.periods)) {
        for (var j = 0; j < model.periods.length; j++) {
            var record = new ConfirmedPeriod(model.periods[j], self);
            self.periods.push(record);
            if (record.step() > 0)
                self.selectedPeriod(record);
        }
    }
    self.collectData = function () {
        var array = [];
        ko.utils.arrayFilter(self.periods(), function (period) {
            array.push({ id: period.id(), step: period.step() });
        });
        return array;
    };
    self.changePeriodItemSelect = function (id) {
        if (_h.any(self.periods()))
            for (var i = 0; i < self.periods().length; i++) {
                if (self.periods()[i].id() !== id) {
                    self.periods()[i].step(0);
                } else {
                    if (self.periods()[i].step() > 0)
                        self.selectedPeriod(self.periods()[i]);
                }

            }
    }
    self.toggleVisible = function () {
        self.visible(!self.visible());
    }
}

export class ConfirmedPeriod extends BaseInnerModel {
    constructor(model, parent) {
        super(model);
        this.eId = "step_" + _h.createRandomNumber();
        this.parent = parent;
        this.description = model.description;
        this.stepsub = this.step.supsendableSubscribe(function (newValue) {
            this.parent.changePeriodItemSelect(this.id());
        }.bind(this));
        setTimeout(function () {
            this.changeStep(this.step());
        }.bind(this), 300);
    }

    onClickNode(val) {
        this.step(Number(val));
        this.changeStep(this.step());
    }

    changeStep(val) {
        if (!val)
            val = 0;
        var ul = $("#" + this.eId).find("ul");
        if (ul) {
            ul.find("li").removeClass("dsb-active");
            var liList = ul.find("li");
            for (var i = 0; i < liList.length; i++) {
                if ($(liList[i]).attr("data-id") === "" + val)
                    $(liList[i]).addClass("dsb-active");
            }
        }
    }
}

export class ConsolidationProcessStep extends BaseInfoModel {
    constructor(model) {
        super(model);
    }
}