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

export class BalanceReportData extends BaseModel {
    constructor(model) {
        super(model);
    }
}

export class BalanceReportDataViewModel extends FormBuilder {
    constructor(model, item) {
        super();
        var context = _h.kocnx();
        this.width = context.loginCompanyType() === 0 ? '96%' : '70%';
        var caption;
        if (context.loginCompanyType() === 0) {
            caption = _h.getLocalizedText("reportGroupBalanceDataCaption");
        }
        if (context.loginCompanyType() === 1) {
            caption = _h.getLocalizedText("reportBalanceDataCaption");
            caption = caption.replace("__", item.code);
        }

        this.caption = ko.observable(caption);
        ko.utils.extend(this, new BaseViewModel({
            entityName: "BalanceReportData",
            apiService: {
                actionList: ["filterby"]
            },
            filters: [{ name: 'balanceSheetId' },
            { name: 'companyId' }, { name: 'nodeCode' }, { name: 'nodeId' }, { name: 'treeId' },
            { name: 'amountType' }, { name: 'sheetSearchKey' }],
            extraParams: ["totalCreditor", "totalDebtor"],
            sortDirection: "Ascending",
            buttons: [
                { name: 'exportExcelFile', access: false, icon: 'ExportExcel', cMenu: false },
                { name: 'refresh', access: false, cMenu: false },
                { name: 'tools', access: false, cMenu: false }
            ],
            sortProperty: "code",
            context: this,
            cols: this.createColList(),
            getList: true,
            saveState: true,
            searchKeyType: "enter",
            selectRow: true,
            footerTemplate: "reportbalancedata-footertable-template",
            tableClass: "table ko-tbl ko-tbl-master",
            tableStyle: "table-layout: fixed;margin-top:10px;font-size: 11px;",
            contextMenu: false
        }));
        this.treeId(model.treeId());
        this.amountType(model.amountType());
        this.sheetSearchKey(model.sheetSearchKey());
        this.caption(caption);
        this.nodeId(item.id);
        this.nodeCode(item.code);

        this.balanceSheetId(model.balanceSheetId());
        this.companyId(model.companyId());
        this.btnVisibility = ko.computed(function () {
            var inListView = this.showType() === "List";
            this.visexportExcelFile(!inListView);
            this.visrefresh(!inListView);
            this.vistools(true);
        }
            .bind(this));
        this.fillTableProperties();
        this.getRecords();
        this.createForm();
    }

    exportExcelFileBtn() {
        var context = _h.kocnx();
        var model = {
            controllerName: 12,
            inputData: {
                pageNumber: this.pageNumber(),
                pageSize: this.pageSize(),
                sortProperty: this.sortProperty(),
                sortDirection: this.sortDirection(),
                searchKey: this.searchKey(),
                balanceSheetId: this.balanceSheetId(),
                sheetSearchKey: this.sheetSearchKey(),
                treeId: this.treeId(),
                nodeId: this.nodeId(),
                companyId: this.companyId(),
                companyType: context.loginCompanyType(),
                type: 2,
                amountType: this.amountType()
            }
        };
        if (context.loginCompanyType() === 0) {
            model.inputData.groupId = context.currentCompany().ci;
            model.inputData.periodId = context.periodItem().pi;
        }
        if (context.loginCompanyType() === 1) {
            model.inputData.companyId = context.currentCompany().ci;
        }
        _h.kocnx().createExcel(model);
    };

    createColList() {
        var array = [];
        for (var p in reportbalancedataModelRes) {
            if (reportbalancedataModelRes.hasOwnProperty(p)) {
                var target = reportbalancedataModelRes[p];
                if (_h.kocnx().loginCompanyType() === 0 && p !== "code") {
                    array.push(target);
                }
                if (_h.kocnx().loginCompanyType() === 1) {
                    array.push(target);
                }
            }
        }
        return array;
    }

    changeChildModel(target, force) {
        var detailModel = new BalanceReportCompanyDataViewModel();
        detailModel.treeId(this.treeId());
        detailModel.companyId(target.id());
        detailModel.nodeId(this.nodeId());
        detailModel.amountType(this.amountType());
        detailModel.sheetSearchKey(this.sheetSearchKey());
        this.childModel(detailModel);
        var text = _h.getLocalizedText("reportBalanceDataDetailsCaption");
        text += " " + this.nodeCode() + " توسط " + target.title();
        this.childModel().caption(text);
        this.childModel().init();
    }

    createForm() {
        const controls = [
            this.createLine({ t: 'tm', templateName: 'balancesheet-data-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 BalanceReportCompanyData extends BaseModel {
    constructor(model) {
        super(model);
    }
}

export function BalanceReportCompanyDataViewModel() {
    var self = this;
    self.caption = ko.observable();
    self.exportExcelFileBtn = function (m, e) {
        var context = _h.kocnx();
        var model = {
            controllerName: 12,
            inputData: {}
        };
        var type = Number($(e.currentTarget).attr("data-item"));
        switch (type) {
            case 4:
                model.inputData = {
                    pageNumber: self.pageNumber(),
                    pageSize: self.pageSize(),
                    sortProperty: self.sortProperty(),
                    sortDirection: self.sortDirection(),
                    searchKey: self.searchKey(),
                    treeId: self.treeId(),
                    nodeId: self.nodeId(),
                    sheetSearchKey: context.brvm().sheetSearchKey(),
                    companyType: context.loginCompanyType(),
                    type: type,
                    amountType: self.amountType(),
                    companyId: self.companyId()
                };
                break;
            case 5:
                model.inputData = {
                    treeId: self.treeId(),
                    nodeId: self.nodeId(),
                    type: type,
                    sheetSearchKey: context.brvm().sheetSearchKey(),
                    amountType: self.amountType(),
                    companyId: self.companyId(),
                    mappedNodeId: self.selectedRowRecord().id()
                };
                break;
        }
        _h.kocnx().createExcel(model);
    };
    self.init = function () {
        self.fillTableProperties();
        self.getRecords();
    };
    self.createExcelBtnTitle = function () {
        return _h.shortString(self.selectedRowRecord().title(), 15);
    };
    ko.utils.extend(self, new BaseViewModel({
        entityName: "BalanceReportCompanyData",
        apiService: {
            actionList: ["filterby"]
        },
        getList: true,
        filters: [{ name: 'companyId' }, { name: 'nodeId' }, { name: 'treeId' }, { name: 'amountType' }, { name: 'sheetSearchKey' }],
        buttons: [
            { name: 'exportExcelMenu', access: false, cMenu: false, templateName: "exportexcel-menu-template" },
            { name: 'refresh', access: false, cMenu: false },
            { name: 'tools', access: false, cMenu: false }
        ],
        extraParams: ["totalCreditor", "totalDebtor"],
        sortDirection: "Ascending",
        sortProperty: "code",
        context: self,
        saveState: true,
        footerTemplate: "reportbalancedata-detail-footer-template",
        cols: reportbalancedatadetailsModelRes,
        selectRow: true,
        contextMenu: false,
        searchKeyType: "enter",
        tableClass: "table ko-tbl ko-tbl-child",
        tableStyle: "table-layout: fixed;margin-top:10px;"
    }));
    self.btnVisibility = ko.computed(function () {
        var selectedRecord = self.selectedRowRecord();
        if (!_h.isNullOrEmpty(selectedRecord)) {
            self.visexportExcelMenu(true);
        } else {
            self.visexportExcelMenu(false);
        }
        self.visrefresh(true);
        self.vistools(true);
    });
}

export class TotalBalanceReportData extends BaseModel {
    constructor(model) {
        super(model);
    }
}

export class TotalBalanceReportDataViewModel extends FormBuilder {
    constructor(model, item) {
        super();
        this.width = "70%";
        this.caption = ko.observable();
        ko.utils.extend(this, new BaseViewModel({
            entityName: "TotalBalanceReportData",
            apiService: {
                actionList: ["filterby"]
            },
            filters: [{ name: 'companyId' }, { name: 'treeId' }, { name: 'nodeId' },
            { name: 'justConfirmed' }, { name: 'amountType' }],
            extraParams: ["totalCreditor", "totalDebtor", "nodeName", "companyName"],
            sortDirection: "Ascending",
            buttons: [
                { name: 'exportExcelFile', access: false, icon: 'ExportExcel', cMenu: false },
                { name: 'refresh', access: false, cMenu: false },
                { name: 'tools', access: false, cMenu: false }
            ],
            sortProperty: "companyTitle",
            context: this,
            cols: totalbalancereportModelRes,
            getList: true,
            saveState: true,
            searchKeyType: "enter",
            selectRow: false,
            contextMenu: false,
            tableStyle: "table-layout: fixed;font-size: 11px;",
            footerTemplate: "totalbalancereport-footertable-template"
        }));
        this.changeCaption = ko.computed(function () {
            this.caption(this.nodeName() + "-" + "مانده نهایی به تفکیک شرکت ها");
        }.bind(this));
        this.btnVisibility = ko.computed(function () {
            this.visexportExcelFile(true);
            this.visrefresh(true);
            this.vistools(true);
        }.bind(this));
        if (_h.kocnx().loginCompanyType() === 0) {
            this.companyId(model.companyId());
            this.justConfirmed(model.justConfirmed());
        }
        this.amountType(model.amountType());
        this.nodeId(item.id);
        this.treeId(model.treeId());
        this.fillTableProperties();
        this.getRecords();
        this.createForm();

    }

    exportExcelFileBtn() {
        var model = {
            controllerName: 12,
            inputData: {
                pageNumber: this.pageNumber(),
                pageSize: this.pageSize(),
                sortProperty: this.sortProperty(),
                sortDirection: this.sortDirection(),
                searchKey: this.searchKey(),
                companyId: this.companyId(),
                treeId: this.treeId(),
                nodeId: this.nodeId(),
                justConfirmed: this.justConfirmed(),
                type: 3,
                amountType: this.amountType()
            }
        };
        _h.kocnx().createExcel(model);
    }

    createForm() {
        const controls = [
            this.createLine({ t: 'tm', templateName: 'totalbalance-data-form-t' }, undefined, true, 0, 0),
        ];
        this.formControls(controls);
        this.formButtons({
            name: 'footer-form-t', data: {
                buttons: [
                    { name: 'cancel', click: _h.kocnx().closeForm }]
            }
        });
    }
}