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

export class Company extends BaseModel {
    constructor(model, parent) {
        super(model);
        this.parent = ko.observable(parent);
        this.children = ko.observableArray();
        if (_h.any(model.children))
            for (var j = 0; j < model.children.length; j++) {
                var record = new Company(model.children[j], this);
                this.children.push(record);
            }
    }

    refreshModel(model) {
        _autoMapper.fillModel(this, model);
        this.children = ko.observableArray();
        if (_h.any(model.children))
            for (var j = 0; j < model.children.length; j++) {
                var record = new Company(model.children[j], this);
                this.children.push(record);
            }
    }
}

export class CompanyForm extends BaseFormModel {
    constructor(viewModel, editMode, parentName, pi) {
        super(viewModel, editMode);
        this.backgroundModal = false;
        this.subsetMode = ko.observable(parentName !== undefined);
        this.fileName = ko.observable();
        this.file = ko.observable();
        this.addByAutoComplete = ko.observable();
        this.picMode = ko.observable(false);
        if (this.subsetMode())
            this.caption = _h.getLocalizedText('addSubsetCaption') + ' برای ' + parentName;
        this.showPreview = ko.observable(false);
        this.name = ko.observable();
        this.companyType = ko.observable();
        this.description = ko.observable();
        this.pi = ko.observable(pi);
        if (editMode) {
            var model = viewModel.getSelectedRecord();
            this.name(model.na());
            this.companyType(model.nt());
            this.description(model.de());
            this.pi(model.pi());
            if (!_h.isEmpty(model.logoUrl())) {
                var fileName = model.logoUrl().substring(model.logoUrl().lastIndexOf("/") + 1);
                this.fileName(fileName);
            }
        } else
            this.mainCompany = ko.observable(false);
        this.isCompany = ko.computed(function () {
            return this.companyType() === 1;
        }, this);
        this.setValidationObject();
        this.handlePicMode();
        this.createForm();
    }
    setValidationObject() {
        var self = this;
        this.validationObject = ko.validatedObservable({
            companyType: self.companyType.extend({
                required: true
            }),
            currencyName: self.currencyName.extend({
                required: true
            }),
            name: self.name.extend({
                required: true,
                notOnlyNumberAndSpChr: true,
                notBeginNumberAndSpChr: true,
                minLength: 3,
                maxLength: 100,
                remoteIsUniqueRule: { params: [self.id, "Company", "name"] }
            }),
            pi: self.pi.extend({
                required: {
                    onlyIf: function () {
                        return self.subsetMode();
                    }
                }
            }),
            dateOfAcquisition: self.dateOfAcquisition.extend({
                required: true
            }),
            nationalIdentity: self.nationalIdentity.extend({
                required: true,
                minLength: 10,
                maxLength: 11,
                numberOnly: null,
                remoteIsUniqueRule: { params: [self.id, "Company", "nationalIdentity"] }
            }),
            file: self.file.extend({
                checkImage: { params: [self.fileName] }
            })
        });
    }
    handleFileChoose(files) {
        var file = files;
        var ext = _h.getExtension(file.name);
        _h.toBase64(file, function (res) {
            this.file(res);
        }.bind(this));
        this.fileName(file.name);
        if (ext.toLowerCase() === "jpg" || ext.toLowerCase() === "jpeg" || ext.toLowerCase() === "png") {
            this.handleShowPreview(file);
        } else {
            this.showPreview(false);
            this.handlePicMode();
        }
    }
    handleShowPreview(file) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#preview-pic').attr('src', e.target.result);
        };
        reader.readAsDataURL(file);
        this.showPreview(true);
        this.handlePicMode();
    }
    handlePicMode() {
        if (_h.isEmpty(this.logoUrl()) && !this.showPreview())
            this.picMode(0);

        if (!_h.isEmpty(this.logoUrl()) && !this.showPreview())
            this.picMode(1);

        if (this.showPreview())
            this.picMode(2);
        return true;
    }
    removeLogo() {
        if (_h.isEmpty(this.logoUrl())) {
            this.file(undefined);
            this.fileName("");
            this.showPreview(false);
            this.picMode(0);
        } else {
            this.file(undefined);
            this.picMode(0);
            this.fileName("");
            this.logoUrl(null);
            this.showPreview(false);
        }
    }
    onCompanyAutoSelect(controlName, item) {
        this.companyType(item.nt);
        this.description(item.de);
        this.name(undefined);
        this.name(item.na);
        this.id(item.id);
        this.nationalIdentity(item.nationalIdentity);
        this.stateType(item.stateType);
        this.currencyName(item.currencyName);
        this.dateOfAcquisition(item.dateOfAcquisition);
        this.addByAutoComplete(item.id);
        if (_h.any(this.parentVM.selectList()))
            for (var i = 0; i < this.parentVM.selectList().length; i++) {
                if (this.parentVM.selectList()[i].value() === item.pi)
                    this.pi(item.pi);
            }
    }
    createForm() {
        const controls = [
            this.createLine({ t: 'tm', templateName: 'firstrow-company-form-t' }, undefined, true, 0, 0),
            this.createLine({ t: 'slc', val: this.currencyName, options: currencyNames },
                { t: 'slc', val: this.companyType, options: companyTypes, dis: this.editMode }, true, 30),
            this.createLine({ t: 'dpk', val: this.dateOfAcquisition, dateType: 'fa' },
                { t: 'slc', val: this.pi, options: this.parentVM.selectList }, true, 30),
            this.createLine({ t: 'tm', templateName: 'upload-company-form-t' }, undefined, true, 30, 30),
            this.createLine({ t: 'chk', val: this.mainCompany, click: this.toggleMainCompany },
                undefined, this.isCompany, 30),
            this.createLine({ t: 'txa', val: this.description }, undefined, true, 30)
        ];
        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() === true, click: this.parentVM.edit },
                    { name: 'cancel', click: _h.kocnx().closeForm }]
            }
        });
    }
    toggleMainCompany() {
        this.mainCompany(!this.mainCompany());
    }
    toServer() {
        var data = ko.toJS(this);
        delete data["validationObject"];
        delete data["formButtons"];
        delete data["formControls"];
        delete data["parentVM"];
        delete data["editMode"];
        delete data["ad"];
        delete data["selected"];
        delete data["ruleModel"];
        delete data["parent"];
        delete data["children"];
        return data;
    }
}

export class CompanyDynamicForm extends BaseSecondaryForm {
    constructor(viewModel) {
        super(viewModel, [
            { name: "entityName", type: "", val: "CompanyDyanamic" },
            { name: "dynamicForms", type: "obar" },
            { name: "lastPriority", type: "ob" },
            { name: "selectedRow", type: "ob" },
            { name: "resultModel", type: "ob" },
            { name: "showArchived", type: "ob", value: false },
        ], "CompanyDyanamicCaption");
        this.width = "80%";
        this.visCreateBtn = ko.pureComputed(function () {
            var cond = !_h.isNullOrEmpty(this.selectedRow()) && this.selectedRow().editMode() === false;
            return cond;
        }.bind(this));
        this.visEditBtn = ko.pureComputed(function () {
            var cond = !_h.isNullOrEmpty(this.selectedRow()) && this.selectedRow().editMode();
            return cond;

        }.bind(this));
        this.createForm();
        this.getRecords();
    }
    createBtn() {
        this.getLastPriority(function (res) {
            if (res !== null) {
                var item = new CompanyDynamicItem({ id: undefined, title: "", value: undefined, priority: res + 1, archived: false }, res + 1);
                this.selectedRow(item);
            }
        }.bind(this));
    }
    create() {
        var model = this.selectedRow().toServer();
        if (model === false)
            return model;
        ApiService.request(
            {
                url: "/api/companyinfo/post",
                data: model,
                success: function (data) {
                    if (!_h.isNullOrEmpty(data)) {
                        this.getRecords(model.id);
                        this.lastPriority(data.lastPriority);
                        toast.success(this.entityName, 'post');
                    }
                }.bind(this),
                error: function (data) {
                    toast.error(this.entityName, 'post');
                }.bind(this)
            });
    }
    edit() {
        var model = this.selectedRow().toServer();
        if (model === false)
            return model;
        ApiService.request(
            {
                url: "/api/companyinfo/put",
                data: model,
                success: function (data) {
                    if (!_h.isNullOrEmpty(data)) {
                        this.getRecords(model.id);
                        this.lastPriority(data.lastPriority);
                        toast.success(this.entityName, 'put');
                    }
                }.bind(this),
                error: function (data) {
                    toast.error(this.entityName, 'put');
                }.bind(this)
            });
    }
    deleteBtn(m, item) {
        if (_h.isNullOrEmpty(this.selectedRow().id())) {
            this.selectedRow(null);
            return;
        }
        var id = this.selectedRow().id();
        var confirmText = toast.createMessage(this.entityName, 'del', null, 'confirm');
        ApiService.request(
            {
                url: "/api/companyinfo/delete",
                data: { id: id },
                success: function (data) {
                    if (!_h.isNullOrEmpty(data)) {
                        this.getRecords();
                        this.lastPriority(data.lastPriority);
                        this.selectedRow().selected(false);
                        this.selectedRow().editMode(false);
                        this.selectedRow(undefined);
                        toast.success(this.entityName, 'del');
                    }
                }.bind(this),
                error: function (data) {
                    toast.error(this.entityName, 'del');
                }.bind(this)
            });
    }
    getRecords(id) {
        ApiService.request(
            {
                url: "/api/companyinfo/filterby",
                data: { showArchived: this.showArchived() },
                success: function (data) {
                    this.dynamicForms.removeAll();
                    if (!_h.isNullOrEmpty(data)) {
                        if (_h.any(data.list)) {
                            var oldRecord;
                            for (var m = 0; m < data.list.length; m++) {
                                var target = data.list[m];
                                var record = new CompanyDynamicItem(target, data.lastPriority);
                                this.dynamicForms.push(record);
                                if (id && id === target.id) {
                                    oldRecord = record;
                                }
                            }
                            if (oldRecord) {
                                this.selectedRow(oldRecord);
                                oldRecord.selected(true);
                                oldRecord.editMode(true);
                            } else {
                                var first = this.dynamicForms()[0];
                                if (_h.isNullOrEmpty(this.selectedRow())) {
                                    this.selectedRow(first);
                                    first.selected(true);
                                    first.editMode(true);
                                }
                            }
                        }
                        this.lastPriority(data.lastPriority);
                    }
                }.bind(this),
                error: function (data) {
                    toast.error(this.entityName, 'getList');
                }.bind(this)
            });
    }
    createForm() {
        const controls = [
            this.createLine({ t: 'tm', templateName: 'companydynamicforms-form-t' }, undefined, true, 0, 0),
        ];
        this.formControls(controls);
        this.formButtons({
            name: 'footer-form-t', data: {
                buttons: [
                    {
                        name: "custom",
                        resText: 'createFormBtn',
                        vis: this.visCreateBtn,
                        click: this.create.bind(this)
                    },
                    {
                        name: "custom",
                        resText: 'editFormBtn',
                        vis: this.visEditBtn,
                        click: this.edit.bind(this)
                    },
                    { name: 'cancel', click: _h.kocnx().closeForm }]
            }
        });
    }
    toggleShowArchive() {
        this.showArchived(!this.showArchived());
        this.getRecords();
    }
    archive() {
        var model = this.selectedRow().toServer();
        if (model === false)
            return model;
        ApiService.request(
            {
                url: "/api/companyinfo/putarchive",
                data: model,
                success: function (data) {
                    if (!_h.isNullOrEmpty(data)) {
                        this.getRecords(model.id);
                        this.lastPriority(data.lastPriority);
                        toast.success(this.entityName, 'put');
                    }
                }.bind(this),
                error: function (data) {
                    toast.error(this.entityName, 'put');
                }.bind(this)
            });
    }
    onRowClick(item) {
        if (this.selectedRow() !== null && this.selectedRow() !== undefined) {
            this.selectedRow().selected(false);
            this.selectedRow().editMode(false);
        }
        item.lastPriority(this.lastPriority() + 1);
        this.selectedRow(item);
        item.selected(true);
        item.editMode(true);
        if ($("#result-dyn-t").hasClass("active")) {
            this.showInfo();
        }
    }
    showInfo() {
        var item = this.selectedRow();
        var cols = [];
        var idObj = {
            fa: '#',
            colName: 'id',
            tablecol: false,
            visibleCol: false,
            sortDir: "None",
            alias: null,
            type: "template",
            templateName: "checkbox-table-template"
        };

        cols.push(idObj);

        for (var i = 0; i < companydyanamicModelRes.length; i++) {
            var coi = companydyanamicModelRes[i];
            var obj = {
                fa: coi.fa,
                colName: coi.colName,
                tablecol: true,
                visibleCol: true,
                sortDir: "None",
                alias: null,
                type: coi.type,
                popup: true
            };
            if (coi.colName === "companyName")
                obj.sortDir = "Ascending";
            cols.push(obj);
        }

        if (!_h.isNullOrEmpty(item.fields()))
            for (var i = 0; i < item.fields().length; i++) {
                var field = item.fields()[i];
                var order = i.toString();
                if (field.order())
                    order = field.order().toString();
                var obj = {
                    fa: field.name(),
                    colName: order,
                    tablecol: true,
                    visibleCol: true,
                    sortDir: "None",
                    alias: null,
                    type: "string",
                    popup: true
                };
                switch (field.dataType()) {
                    case 4:
                        obj.type = "file";
                        break;
                }
                /*                if (field.name() === "CompanyName")
                                    obj.sortDir = "Ascending";*/

                cols.push(obj);
            }




        var model = new CompanyInfoDataViewModel(cols);
        model.formId(item.id());
        this.resultModel(model);
        this.resultModel().init();
    }
    getLastPriority(callback, id) {
        var model = {
            controllerName: 1,
            id: id
        };
        ApiService.request({
            url: "/api/common/getlastpriority",
            data: model,
            success: function (data) {
                callback(data);
            },
            error: function (data) {
                toast.error(self.entityName, 'get', 'LastPriority');
                callback(null);
            },
            messageType: 'get',
            messageKey: "LastPriority"
        });
    }
}

export class CompanyDynamicItem {
    constructor(model, lastPriority) {
        this.editMode = ko.observable(false);
        this.selected = ko.observable(false);
        this.id = ko.observable(model.id);
        this.title = ko.observable(model.title);
        this.priority = ko.observable(model.priority);
        this.archived = ko.observable(model.archived);
        this.lastPriority = ko.observable(lastPriority);
        this.fields = ko.observableArray();
        if (_h.any(model.fields))
            for (var j = 0; j < model.fields.length; j++) {
                var record = new CompanyDynamicField(model.fields[j]);
                this.fields.push(record);

            }
        this.validationObject = ko.validatedObservable({
            title: this.title.extend({
                required: true
            }),
            priority: this.priority.extend({
                required: true
            }),
            fields: this.fields
        });
    }
    addField() {
        var item = new CompanyDynamicField({ order: undefined, name: "", required: false });
        this.fields.push(item);
    }
    removeField(parents, item) {
        parents[0].fields.remove(item);
    }
    toServer() {
        if (!this.validationObject.isValid()) {
            this.validationObject.errors.showAllMessages();
            return false;
        }
        var model = {
            id: this.id(),
            priority: this.priority(),
            title: this.title(),
            fields: ko.toJS(this.fields())
        };

        return model;
    }
}

export class CompanyDynamicField {
    constructor(model) {
        this.order = ko.observable(model.order);
        this.name = ko.observable(model.name);
        this.dataType = ko.observable(model.dataType);
        this.value = ko.observable(model.value);
        this.required = ko.observable(model.required);
        this.validationObject = ko.validatedObservable({
            name: this.name.extend({
                required: true
            }),
            dataType: this.dataType.extend({
                required: true
            })
        });
    }
    createTagId() {
        return this.constructor.name + "-" + this.order();
    }

}

export class CompanyInfoData extends BaseModel {
    constructor(model) {
        super(model);
        if (_h.any(model.cells))
            for (var j = 0; j < model.cells.length; j++) {
                var field = model.cells[j];
                this[field.order] = ko.observable(field.value);
            }
    }

}

export function CompanyInfoDataViewModel(cols, editMode) {
    var self = this;
    self.editMode = editMode;
    self.formName = ko.observable();
    self.cols = cols;
    self.downloadFile = function (order) {
        var selectedRecord = self.getSelectedRecord();
        var model = {
            controllerName: 61,
            inputData: {
                formId: self.formId(),
                id: selectedRecord.id(),
                companyId: selectedRecord.companyId(),
                fieldOrder: Number(order)
            }
        };
        ApiService.request(
            {
                url: "/api/filegenerator/postdownloadfile",
                data: model,
                success: function (data) {
                    if (!_h.isNullOrEmpty(data)) {
                        _h.downloadFile(data.model);
                    }
                },
                error: function (data) {
                }
            });

    }
    self.exportExcelFileBtn = function () {
        var filterModel = self.createFilterByModel();
        var model = {
            controllerName: 61,
            inputData: filterModel
        };
        _h.kocnx().createExcel(model);
    }
    self.createEditModel = function (target, editMode) {
        var model = {
            editMode: editMode,
            formId: self.formId(),
            id: editMode ? target.id() : _h.createRandomNumber(),
            fields: []
        };
        for (var i = 1; i < self.cols.length; i++) {
            var col = self.cols[i];
            var object = {
                formId: self.formId(),
                order: Number(col.colName),
                name: col.fa,
                dataType: col.dataType,
                value: editMode ? target[i] : undefined,
                required: col.required
            };
            model.fields.push(object);
        }
        return model;
    }
    self.createBtn = function () {
        var model = self.createEditModel(null, false);
        _h.kocnx()
            .openForm(new CompanyInfoDataForm(self, model));
    }
    self.editBtn = function (target) {
        if (!target || !target["id"])
            target = self.getSelectedRecord();
        var model = self.createEditModel(target, true);
        _h.kocnx()
            .openForm(new CompanyInfoDataForm(self, model));
    }
    self.init = function () {
        self.fillTableProperties();
        self.getRecords();
        self.iconSize("icon-image-small");
    }
    ko.utils.extend(this, new BaseViewModel({
        entityName: "CompanyInfoData",
        apiService: {
            actionList: ["filterby", "delete", "post", "put"]
        },
        buttons: [
            { name: 'exportExcelFile', access: true, icon: 'ExportExcel', cMenu: false },
            { name: 'delete', access: true, icon: 'Delete', cMenu: true },
            { name: 'edit', access: true, icon: 'Edit', cMenu: true },
            { name: 'help', access: false, cMenu: false },
            { name: 'refresh', access: false, cMenu: false },
            { name: 'tools', access: false, cMenu: false },
            { name: 'create', access: true, cMenu: false }
        ],
        filters: [{ name: 'formId' }],
        sortDirection: "Ascending",
        sortProperty: "",
        context: self,
        dynamicCols: true,
        extraParams: [],
        saveState: true,
        cols: cols,
        getList: true,
        selectRow: true,
        contextMenu: true,
        tableClass: "table ko-tbl ko-tbl-child ko-tbl-dyninfo",
        searchKeyType: "enter",
        tableStyle: "width: 200%;margin-top: 10px;font-size: 11px;max-width: initial;",
        isMultiSelectRows: true,
        resizable: true
    }));
    self.btnVisibility = ko.computed(function () {
        if (!self.editMode) {
            self.visexportExcelFile(true);
            self.visrefresh(true);
            self.vistools(true);
            self.viscreate(false);
            self.visedit(false);
            self.visdelete(false);
        } else {
            self.visexportExcelFile(false);
            self.visrefresh(true);
            self.vistools(true);
            self.viscreate(true);
            var selectedRecord = self.getSelectedRecord();
            if (!_h.isNullOrEmpty(selectedRecord)) {
                self.visedit(true);
                self.visdelete(true);
            } else {
                self.visedit(false);
                self.visdelete(false);
            }
        }

    });
    self.countSelectedRecord = ko.pureComputed(function () {
        var count = 0;
        for (let i = 0; i < self.records().length; i++) {
            var record = self.records()[i];
            if (record.selected())
                count++;
        }
        return count;
    });
}


$(document).on("shown.bs.tab", '.mapping-tab a[data-toggle="tab"]', function () {
    var href = $(this).attr("href");
    if (href === "#result-dyn-t") {
        _h.kocnx().formModel().showInfo();
    }
    return false;
});
$(document).on("click", '.file-download-item', function () {
    var order = $(this).attr("data-order");
    if (_h.kocnx().formModel())
        _h.kocnx().formModel().resultModel().downloadFile(order);
    else
        _h.kocnx().civm().childModel().downloadFile(order);
    return false;
});