
import { ApiService } from "../util/apiService.js";
import {
    InfoDropDown, ContextMenu, DomChart, ChartMenu, DescCell
} from '../pages/tabletemplate/model';


ko.components.register('ko-rg', {
    viewModel: function (params) {
        var self = this;
        self.parent = params.parent;
        self.entityName = "ReportGenerator";
        self.type = !params.type ? "edit" : "cellSelect";
        self.firstLoad = ko.observable(false);
        self.active = params.active || ko.observable(true);
        self.tableTemplateId = params.tableTemplateId;
        self.templateType = ko.observable();
        self.showDesc = ko.observable(false);
        self.triggerEditable = params.triggerEditable || ko.observable(false);
        self.refreshToolBar = params.refreshToolBar || ko.observable(false);
        self.infoDropDownModel = ko.observable(new InfoDropDown(self));
        self.descCellModel = ko.observable();
        self.contextMenuModel = new ContextMenu();
        self.id = "rg-" + (self.type === "edit" ? self.tableTemplateId() : "-sc-" + self.tableTemplateId());
        self.selectedToolsClass = "selected-tools";
        self.scope = null;
        self.data = params.data;
        self.previewMode = params.previewMode || ko.observable(false);
        self.editable = ko.observable(false);
        self.lockedBy = ko.observable();
        self.lockedByUserId = ko.observable();
        self.lockedForThisUser = ko.observable(false);
        self.paperSizeAreaTypes = [
            { text: "هیچکدام", enText: "", enable: ko.observable(true) },
            { text: "سایز A4 عمودی", enText: "ruler-a4-port", enable: ko.observable(false) },
            { text: "سایز A4 افقی", enText: "ruler-a4-land", enable: ko.observable(false) }
        ];
        self.findScope = function () {
            self.scope = $('#' + self.id);
        }
        self.changePaperSizeArea = function (item) {
            for (var i = 0; i < self.paperSizeAreaTypes.length; i++) {
                if (self.paperSizeAreaTypes[i].enText !== item.enText) {
                    self.paperSizeAreaTypes[i].enable(false);
                }
            }
            item.enable(true);
            var tag = self.scope.find(".rg-paperSize");
            if (!tag || tag.length === 0) {
                var box = self.scope.find(".rp-gen").parent();
                box.append('<div class="rg-paperSize ' + item.enText + '"></div>');
            }
            tag.attr('class', '');
            tag.addClass("rg-paperSize " + item.enText);
        }
        self.refresh = function (preview) {
            if (!_h.isEmpty(preview) && typeof preview !== Boolean)
                preview = false;           
            var context = _h.kocnx().ttvm();
            var record = context.getFocusDesignRecord();
            var arrayData = $("#rg-" + record.id).find(".rp-gen").rg("toServer");
            if (arrayData && arrayData[1]) {
                var confirmText = _h.getApiMessage("ConfirmNotSaveChange");
                _h.confirmDeleteAlert(confirmText,
                    function (res) {
                        if (res) {
                            self.dispose();
                            self.getData();
                        }
                    });
            } else {
                self.dispose();
                self.getData();
            }
        }
        self.getData = function (woConfig) {
            if (!self.active())
                return;
            var model = {
                id: self.tableTemplateId()
            };
            ApiService.request(
                {
                    url: "/api/tablestructure/getexceldata",
                    data: model,
                    success: function (data) {
                        if (!_h.isNullOrEmpty(data)) {
                            if (self.type === "edit") {
                                if (!woConfig)
                                    self.config(data.model, data.bindErrors);
                                self.resetToolBar();
                                var item = {
                                    id: self.tableTemplateId(), editable: data.model.editable,
                                    lockedBy: data.model.lockedBy, lockedByUserId: data.model.lockedByUserId
                                };
                                self.lockedBy(item.lockedBy);
                                self.lockedByUserId(item.lockedByUserId);
                                if (item.editable && item.lockedByUserId === _h.kocnx().currentUser().ui) {
                                    self.editable(true);
                                    self.lockedForThisUser(true);
                                    $("#rg-" + self.tableTemplateId()).find(".rp-gen").rg("toggleEditable", true);
                                } else if (item.editable && item.lockedByUserId !== _h.kocnx().currentUser().ui) {
                                    self.editable(true);
                                    self.lockedForThisUser(false);
                                    $("#rg-" + self.tableTemplateId()).find(".rp-gen").rg("toggleEditable", false);
                                } else {
                                    self.editable(false);
                                    self.lockedForThisUser(false);
                                    $("#rg-" + self.tableTemplateId()).find(".rp-gen").rg("toggleEditable", false);
                                }
                                _h.kocnx().ttvm().setLockedItem(item);
                                setTimeout(function () {
                                    self.charts.removeAll();
                                    if (_h.any(data.model.charts))
                                        for (var k = 0; k < data.model.charts.length; k++) {
                                            var chart = new DomChart(self);
                                            self.charts.push(chart);
                                            chart.fillModel(data.model.charts[k]);
                                        }
                                }, 1000);
                            } else {
                                self.configCellSelect(data.model);
                            }
                        }
                        if (!self.firstLoad())
                            self.firstLoad(true);
                        if (self.type == "edit")
                            self.toolbarState();
                    },
                    error: function (data) {
                        var text = _h.getApiMessage("ErrorLoadExcel");
                        _h.failToast(text);
                    }
                });
        }
        self.toggleEditable = function () {
            if (!self.editable()) {
                _h.kocnx().ttvm().postTemplateEditable(self.tableTemplateId(), true, function (data) {
                    if (data.model.lockedByUserId === _h.kocnx().currentUser().ui) {
                        self.editable(data.model.editable);
                        self.lockedBy(data.model.lockedBy);
                        self.lockedByUserId(data.model.lockedByUserId);
                        self.lockedForThisUser(true);
                        self.getData(true);
                    }
                });
            } else {
                _h.kocnx().ttvm().postTemplateEditable(self.tableTemplateId(), false, function (data) {
                    $("#rg-" + self.tableTemplateId()).find(".rp-gen").rg("toggleEditable", false);
                    self.editable(false);
                    self.lockedBy(undefined);
                    self.lockedByUserId(undefined);
                    self.lockedForThisUser(false);
                    var item = {
                        id: self.tableTemplateId(), editable: false,
                        lockedBy: undefined, lockedByUserId: undefined
                    };
                    _h.kocnx().ttvm().setLockedItem(item);

                });
            }
        }
        self.saveChanges = function (preview) {
            if (!_h.isEmpty(preview) && typeof preview !== Boolean)
                preview = false;
            var context = _h.kocnx().ttvm();
            var record = context.getFocusDesignRecord();
            var arrayData = $("#rg-" + record.id).find(".rp-gen").rg("toServer");
            var model = arrayData[0];
            if (context.focusDesignItem().previewMode()) {
                var text = _h.getApiMessage("RgNotAllwedSaveChange");
                _h.failToast(text);
                return;
            }
            if (_h.any(self.charts()))
                ko.utils.arrayForEach(self.charts(), function (item, index) {
                    if (item.showChart())
                        item.changePosition();
                    item.oldShowChart = item.showChart();
                    item.showChart(false);
                    try {
                        if (item.chartObject) {
                            item.chartObject.destroy();
                            item.chartObject = null;
                        }
                    } catch (e) {
                        item.chartObject = null;
                    }
                    item.showChart(item.oldShowChart);
                });

            model.charts = [];
            for (var i = 0; i < self.charts().length; i++) {
                var chart = self.charts()[i];
                var objChart = chart.toServer(chart.oldShowChart);
                model.charts.push(ko.toJS(objChart));
            }
            if (_h.any(self.charts()))
                ko.utils.arrayForEach(self.charts(),
                    function (item, index) {
                        item.showChart(item.oldShowChart);
                        if (!item.chartObject && !preview) {
                            item.configChart();
                        }

                    });
            _h.kocnx().ttvm().saveChanges(model, function (dataRes) {
                if (dataRes !== false) {
                    if (_h.any(dataRes.bindErrors))
                        $("#rg-" + record.id).find(".rp-gen").rg("setWarning", dataRes.bindErrors);
                    if (_h.any(dataRes.cellsTag))
                        $("#rg-" + record.id).find(".rp-gen").rg("refreshCellsTag", dataRes.cellsTag);
                }
            });
        }
        self.nodeOperatorEditBtn = function () {
            if (self.selectedCells.length > 0) {
                var model = new NodesCellEdit(self, self.selectedCells);
                if (model.canShow())
                    _h.kocnx().openForm(model);
            }
        }
        self.nodeOperatorEdit = function () {
            _h.kocnx().formModel().change(function (res) {
                if (res) {
                    _h.kocnx().closeForm();
                }
            });
        }
        self.checkNodePhrase = function (formula, financialPeriod, callback) {
            var model = {
                formula: formula,
                financialPeriod: financialPeriod
            };
            ApiService.request(
                {
                    url: "/api/tablestructure/postchecknodesincell",
                    data: model,
                    success: function (list) {
                        if (!_h.isNullOrEmpty(list)) {
                            for (var i = 0; i < list.nodes.length; i++) {
                                if (list.nodes[i]["value"])
                                    list.nodes[i].code = list.nodes[i]["value"];
                            }
                            callback(list);
                        }
                    },
                    error: function (data) {

                    }
                });
        }
        self.resetToolBar = function () {
            var scope = document.getElementById(self.id);
            if (!scope)
                return;
            var defaultVal = self.getDefault();
            scope.querySelector("#textBold").classList.remove(self.selectedToolsClass);
            scope.querySelector("#textItalic").classList.remove(self.selectedToolsClass);
            scope.querySelector("#textUnderline").classList.remove(self.selectedToolsClass);
            scope.querySelector(".txtFormula").classList.remove(self.selectedToolsClass);
            scope.querySelector(".txtFormula").style.color = "black";
            scope.querySelector("#cellAddress").innerText = "";
            scope.querySelector("#textColor").style.backgroundColor = defaultVal.textColor;
            scope.querySelector("#backColor").style.backgroundColor = defaultVal.backColor;
            scope.querySelectorAll(".align-btn")[0].classList.remove(self.selectedToolsClass);
            scope.querySelectorAll(".align-btn")[1].classList.remove(self.selectedToolsClass);
            scope.querySelectorAll(".align-btn")[2].classList.remove(self.selectedToolsClass);
            switch (defaultVal.align) {
                case "right":
                    scope.querySelectorAll(".align-btn")[0].classList.add(self.selectedToolsClass);
                    break;
                case "center":
                    scope.querySelectorAll(".align-btn")[1].classList.add(self.selectedToolsClass);
                    break;
                case "left":
                    scope.querySelectorAll(".align-btn")[2].classList.add(self.selectedToolsClass);
                    break;
            }

            scope.querySelector("#colRight").hidden = true;
            scope.querySelector("#rowTop").hidden = true;
            scope.querySelector("#deleteCol").hidden = true;
            scope.querySelector("#deleteRow").hidden = true;
            scope.querySelector("#hideCol").hidden = true;
            scope.querySelector("#showCol").hidden = true;
            scope.querySelector("#hideRow").hidden = true;
            scope.querySelector("#showRow").hidden = true;
            scope.querySelector("#mergeCells").hidden = !self.hasTrueShape;
            scope.querySelector("#unMergeCells").hidden = true;
            self.scope.find(".fnt-selector").fontSelector("setValue", {
                textFontSize: defaultVal.textFontSize,
                textFontFamily: defaultVal.textFontFamily,
            });
        }
        self.selectedCells = [];
        self.hasTrueShape = false;
        self.toolbarState = function () {
            var [cells, shapeData, model, showUndo, showRedo] = self.scope.find(".rp-gen").rg("getToolbarStateData");
            self.selectedCells = cells;
            self.hasTrueShape = shapeData[4];
            var scope = document.getElementById(self.id);
            //scope.querySelector("#undoAction").hidden = !showUndo;
            //scope.querySelector("#redoAction").hidden = !showRedo;
            if (self.selectedCells.length > 1 || self.selectedCells.length === 0) {
                self.resetToolBar();
                return;
            } else {
                var cell = self.selectedCells[0];
                scope.querySelector("#colRight").hidden = false;
                scope.querySelector("#rowTop").hidden = false;
                scope.querySelector("#deleteCol").hidden = false;
                scope.querySelector("#deleteRow").hidden = false;
                scope.querySelector("#mergeCells").hidden = true;
                //scope.querySelector("#undoAction").hidden = !showUndo;
                //scope.querySelector("#redoAction").hidden = !showRedo;
                scope.querySelector("#unMergeCells").hidden = cell.colSpan === 1 && cell.rowSpan === 1;
                scope.querySelector("#textColor").style.backgroundColor = cell.style.textColor;
                scope.querySelector("#backColor").style.backgroundColor = cell.style.backColor;
                scope.querySelector("#hideCol").hidden = model.hiddenCols.indexOf(cell.col) !== -1;
                scope.querySelector("#showCol").hidden = model.hiddenCols.length === 0 || model.hiddenCols.indexOf(cell.col) === -1;
                scope.querySelector("#hideRow").hidden = model.hiddenRows.indexOf(cell.row) !== -1;
                scope.querySelector("#showRow").hidden = model.hiddenRows.length === 0 || model.hiddenRows.indexOf(cell.row) === -1;
                if (cell.style.textBold)
                    scope.querySelector("#textBold").classList.add(self.selectedToolsClass);
                else
                    scope.querySelector("#textBold").classList.remove(self.selectedToolsClass);

                if (cell.style.textItalic)
                    scope.querySelector("#textItalic").classList.add(self.selectedToolsClass);
                else
                    scope.querySelector("#textItalic").classList.remove(self.selectedToolsClass);

                if (cell.style.textUnderline)
                    scope.querySelector("#textUnderline").classList.add(self.selectedToolsClass);
                else
                    scope.querySelector("#textUnderline").classList.remove(self.selectedToolsClass);
                scope.querySelectorAll(".align-btn")[0].classList.remove(self.selectedToolsClass);
                scope.querySelectorAll(".align-btn")[1].classList.remove(self.selectedToolsClass);
                scope.querySelectorAll(".align-btn")[2].classList.remove(self.selectedToolsClass);
                switch (cell.style.textAlign) {
                    case "right":
                        scope.querySelectorAll(".align-btn")[0].classList.add(self.selectedToolsClass);
                        break;
                    case "center":
                        scope.querySelectorAll(".align-btn")[1].classList.add(self.selectedToolsClass);
                        break;
                    case "left":
                        scope.querySelectorAll(".align-btn")[2].classList.add(self.selectedToolsClass);
                        break;
                }
                self.scope.find(".fnt-selector").fontSelector("setValue", {
                    textFontSize: cell.style.textFontSize,
                    textFontFamily: cell.style.textFontFamily,
                });
                scope.querySelector("#cellAddress").innerText = cell.address;
                scope.querySelector(".txtFormula").style.color = cell.hasError === true ? "red" : "black";
                if (!_h.isNullOrEmpty(cell.value) && (cell.value.startsWith("=") || cell.value.indexOf("node") !== -1))
                    scope.querySelector(".txtFormula").value = cell.value;
                else
                    scope.querySelector(".txtFormula").value = "";
            }
        }
        self.getScope = function () {
            return $("#" + self.id);
        }
        self.handleFormula = function (param) {
            var input = self.getScope().find(".txtFormula");
            var val = $(input).val().trim();

            if (param)
                val = param.trim();
            if (self.selectedCells.length === 1) {
                if (!_h.isNullOrEmpty(val) && val !== '' && val.startsWith('=')) {
                    var res = self.scope.find(".rp-gen").rg("setFormula", { id: "Formula", value: val });
                    $(input).val(res.hasError === true ? "" : res.value);
                    $(input).css("color", res.hasError === true ? "red" : "black");
                }
                if (!_h.isNullOrEmpty(val) && val !== '' && !val.startsWith('=')) {
                    var financialPeriod = self.selectedCells[0].extraParams.financialPeriod;
                    self.checkNodePhrase(val.trim(), financialPeriod, function (data) {
                        if (data && data.isValid) {
                            $(input).css("color", "black");
                            data.nodes.filter(a => a.periodId = financialPeriod);
                            self.scope.find(".rp-gen").rg("setFormula", { id: "NodeInCell", value: data.nodes });
                            self.infoDropDownModel().refresh();
                        } else {
                            $(input).css("color", "red");
                        }
                    });
                }
                if (_h.isEmpty(val)) {
                    self.scope.find(".rp-gen").rg("setFormula", { id: "Formula", value: undefined });
                    $(input).css("color", "black");
                }
            }
        }
        self.config = function (data, bindErrors) {
            var baseSelector = "#" + self.id;
            var defaultVal = self.getDefault();
            $(baseSelector + " .toolbar-btn").on("click", function (event) {
                event.stopPropagation();
                defaultVal = self.getDefault();
                var btn = $(event.currentTarget);
                var id = btn.attr("id");
                var dvalue = btn.attr("data-value");
                if (btn.hasClass("align-btn"))
                    $(baseSelector + " .align-btn").removeClass("selected-tools");
                var obj = { id: id, default: defaultVal };
                if (dvalue)
                    obj.value = dvalue;
                var res = self.scope.find(".rp-gen").rg("command", obj);
                if ($(btn).hasClass("show-select"))
                    res ? $(btn).addClass("selected-tools") : $(btn).removeClass("selected-tools");
                self.toolbarState();
                _h.activeTooltip(true);
                self.refreshCompare();
                return false;
            });
            self.scope.find(".fnt-selector").fontSelector({
                textFontSize: defaultVal.textFontSize,
                textFontFamily: defaultVal.textFontFamily,
            });

            self.scope.find(".fnt-selector").on("selectionchange", function (evt, data) {
                defaultVal = self.getDefault();
                self.scope.find(".rp-gen").rg("command", { id: data.type, value: data.value, default: defaultVal });
                self.toolbarState();
            }).on("outOfTable", function (x, tag, z) {
                var ul = self.scope.find(".fnt-selectbox");
                if (ul.css("display") !== "none")
                    $(ul).css("display", "");
            });
            $(document).on("click", baseSelector + " .evo-palette td", function (e) {
                e.stopPropagation();
                var target = e.target;
                if (target) {
                    defaultVal = self.getDefault();
                    var color = $(target).css("background-color");
                    var trColor = _h.toHex3(color);
                    var parent = $(target).closest(".dropdown-menu");
                    if (parent) {
                        var prop = parent.attr("data-prop");
                        if (prop) {
                            self.scope.find(".rp-gen").rg("command", { id: prop, value: trColor, default: defaultVal });
                            self.scope.find("#" + prop).css("backgroundColor", trColor);
                            self.toolbarState();
                        }
                    }
                }
            });
            $(document).on("click", baseSelector + " .eraseColor", function (e) {
                e.stopPropagation();
                var target = e.target;
                if (target) {
                    defaultVal = self.getDefault();
                    var parent = $(target).closest(".dropdown-menu");
                    if (parent) {
                        var prop = parent.attr("data-prop");
                        if (prop) {
                            self.scope.find(".rp-gen").rg("command", { id: prop, value: "", default: defaultVal });
                            self.scope.find("#" + prop).css("backgroundColor", "");
                        }
                    }
                }
                return false;
            });
            $(document).on('keydown', baseSelector + " .txtFormula", function (evt, param) {
                evt = evt || window.event;
                var charCode = (evt.which) ? evt.which : evt.keyCode;
                if (charCode === 13) {
                    self.handleFormula(param);
                    evt.preventDefault();
                    _h.activeTooltip(true);
                    return false;
                }
            });
            $(document).on('focus', baseSelector + ' .txtFormula', function (evt) {
                var val = $(baseSelector + ' .txtFormula').val();
                if (!self.infoDropDownModel().show() && val.startsWith("[node:")) {
                    self.infoDropDownModel().init();
                }
            });
            self.scope.find(".rp-gen").rg({
                model: data,
                type: "edit",
                bindErrors: bindErrors,
                handleFormula: self.handleFormula,
                baseSelector: baseSelector
            });
            self.scope.find("table")
                .on("selectionchange", function () {
                    self.toolbarState();
                    if (_h.kocnx().ttvm().cellSpecMenuModel.show()) {
                        _h.kocnx().ttvm().refreshCellSpecMenu();
                    }
                    if (self.infoDropDownModel().show() && !$(baseSelector + ' .txtFormula').is(":focus")) {
                        self.infoDropDownModel().terminate();
                    }
                })
                .on("outOfTable", function (x, tag, z) {
                    if (self.contextMenuModel.show() && !$(tag).hasClass("selectable"))
                        self.contextMenuModel.show(false);
                    if (self.infoDropDownModel().show() &&
                        !$(tag).hasClass("remove-node-btn") &&
                        !$(tag).closest(".f-info-drop").length &&
                        !$(tag).closest(".txtFormula").length &&
                        !$(tag).closest(".page-number-item").length &&
                        !$(tag).closest(".btn-sm").length &&
                        !$(tag).closest(".btn-pag").length &&
                        !$(baseSelector + ' .txtFormula').is(":focus")) {
                        self.infoDropDownModel().terminate();
                    }
                })
                .on("contextMenu", function (evt, target, z) {
                    if (target.nodeName === "INPUT") {
                        _h.kocnx().ttvm().toggleCellSpecMenu();
                        return false;
                    }
                    var loc = target.classList.contains("rp-gen-col") ? "col" :
                        target.classList.contains("first-cell") ? "row" :
                            "cross";

                    var colNumber = Number($(target).attr("data-col"));
                    var model = $(evt.target).data("model");
                    var zeroCol = model.cells.filter(a => a.col === colNumber)[0];
                    if (!model.financialProperties.sortColumn)
                        model.financialProperties.sortColumn = {};
                    var height, width;
                    if (loc === "cross") {
                        height = 30;
                        width = 150;
                    } else {
                        height = Number(target.style.height.replace("px", ""));
                        width = Number(target.style.width.replace("px", ""));
                    }
                    self.contextMenuModel.init({
                        element: target,
                        viewType: loc,
                        colNumber: colNumber,
                        rowNumber: Number($(target).attr("data-row")),
                        parent: self,
                        textWrap: zeroCol ? zeroCol.style.textWrap : undefined,
                        sortDirection: (loc === "col" && colNumber === model.financialProperties.sortColumn.id)
                            ? model.financialProperties.sortColumn.sortDirection : undefined,
                        regions: (loc === "col" && colNumber === model.financialProperties.sortColumn.id) ? model.financialProperties.sortColumn.regions : undefined,
                        width: width,
                        height: height
                    })
                    return false;
                })
                .on("floatingMenu", function (evt, target, z) {
                    if (self.floatingMenuModel.show()) {
                        self.selectedCells = self.scope.find(".rp-gen").rg("getSelectedCells");
                        if (self.selectedCells.length > 0) {
                            var cell = self.selectedCells[0];
                            var nodes = self.scope.find(".rp-gen").rg("getCellValues");
                            self.floatingMenuModel.init({
                                element: target,
                                viewType: "cell",
                                parent: self,
                                cell: cell,
                                sortDirection: columnModel.sortDirection,
                                groupType: columnModel.groupType
                            });
                        }
                    }
                    return false;
                });
            self.adjustSecondScrollBar(baseSelector);
        }
        self.refreshCompare = function () {
            if (_h.kocnx().ttvm().rgMenu().showCompare())
                _h.kocnx().ttvm().rgMenu().compareCellModel().refresh();
        }
        self.configCellSelect = function (data) {
            self.scope.find(".rp-gen").rg({
                model: data,
                type: "cellSelect"
            });
            self.scope.find("table")
                .on("selectionchange", function (event, cell) {
                    if (!cell)
                        return;
                    var designItem = _h.kocnx().ttvm().findFocusDesignItem();
                    var name = self.parent.templateName();
                    if (!name)
                        name = self.parent.getTemplateName(self.parent.tableTemplateId());
                    $("#rg-" + designItem.value()).find(".rp-gen").rg("command",
                        {
                            id: "LinkedCell",
                            value: {
                                tId: cell.id,
                                templateTableType: cell.templateTableType,
                                tTitle: cell.title,
                                tag: cell.tag,
                                title: name + "(" + cell.address + ")"
                            }
                        });
                    _h.kocnx().ttvm().focusDesignItem().refreshToolBar(true);
                    _h.activeTooltip(true);
                });
            var width = self.scope.find(".rp-gen table").width();
            if (width > 650)
                $(".select-cell-box").css("width", "70%");
            else
                $(".select-cell-box").css("width", "");
            self.adjustSecondScrollBar("#selectcell-box");

        }
        self.init = function () {
            self.getData();
            self.findScope();
            if (self.type === "edit") {
                self.previewMode.subscribe(function (newVal) {
                    if (newVal) {
                        var record = _h.kocnx().ttvm().findFocusDesignItem();
                        self.scope.find(".rp-gen").rg("previewMode", "set", record.previewResult, record.bindErrors, record.hiddenRows, record.hiddenCols);
                        self.refreshCharts();

                    } else {
                        self.scope.find(".rp-gen").rg("previewMode", "reset");
                        self.refreshCharts();
                    }
                });
                self.active.subscribe(function (newVal) {
                    if (newVal && !self.firstLoad()) {
                        self.getData();
                    }
                });
            }
            self.tableTemplateId.subscribe(function (newValue) {
                if (newValue)
                    self.getData();
            });
            self.triggerEditable.subscribe(function (newValue) {
                if (newValue)
                    self.toggleEditable();
            });
            self.refreshToolBar.subscribe(function (newValue) {
                if (newValue)
                    self.toolbarState();
            });
        }
        self.adjustSecondScrollBar = function (selector) {
            var parent = $(selector);
            var table = parent.find(".rp-gen table");
            if (table.length) {
                var scrollBar = parent.find("#second-scrollbar");
                var scrollBar2 = parent.find("#third-scrollbar");
                scrollBar.find("div").width(table.width());
                scrollBar2.find("div").width(table.width());
                $(selector + " #second-scrollbar").on("scroll", function () {
                    $(selector).find(".rp-gen").scrollLeft($(this).scrollLeft());
                });

                
                $(selector + " .rp-gen").on("scroll", function () {
                    $(selector + " #second-scrollbar").scrollLeft($(this).scrollLeft());
                    $(selector + " #third-scrollbar").scrollLeft($(this).scrollLeft());
                });
                $(selector + " #third-scrollbar").on("scroll", function () {
                    $(selector).find(".rp-gen").scrollLeft($(this).scrollLeft());
                });
            }
        }
        setTimeout(function () {
            self.init();
        }, 100);
        self.chartMenuModel = ko.observable(new ChartMenu());
        self.charts = ko.observableArray([]);
        self.addChart = function (item) {
            var list = self.selectedCells;
            if (list.length > 1) {
                if (self.charts().length >= 5) {
                    toast.custom("error", ' تعداد نمودار های مجاز یک قالب جدول 5 عدد میباشد ');
                    return;
                }
                var chart = new DomChart(self, true);
                self.charts.push(chart);
                chart.fillEmpty(item, self.charts().length, list);
            } else {
                toast.custom("error", 'ابتدا باید یک محدوده از سلولها را انتخاب کنید');
            }
        }
        self.toggleChartShow = function (item) {
            if (!item.showChart()) {
                item.showChart(true);
                self.refreshChartData(item);
            } else {
                item.showChart(false);
                self.chartMenuModel().close(item);
            }
        }
        self.removeChart = function (item, e) {
            self.chartMenuModel().close(item);
            self.charts.remove(item);
            e.stopPropagation();
        }
        self.showChartMenu = function (item, e) {
            if (!self.chartMenuModel().show()) {
                self.chartMenuModel().open(e, item);
            }
            else
                self.chartMenuModel().close(e, item);
        }
        self.refreshChartData = function (item) {
            var cells = self.selectedCells;
            if (!cells.length)
                return;
            item.configChart();
        }
        self.onChartMouseOver = function (item) {
            $("#box" + item.id()).find(".toolbar-chart").css("display", "block");
        }
        self.onChartMouseOut = function (item) {
            $("#box" + item.id()).find(".toolbar-chart").css("display", "");
        }
        self.refreshCharts = function () {
            if (_h.any(self.charts()))
                for (var j = 0; j < self.charts().length; j++) {
                    if (self.charts()[j].showChart())
                        self.charts()[j].configChart();
                }
        }
        self.toggleDescCell = function () {
            if (self.showDesc()) {
                self.showDesc(false);
                self.descCellModel(null);
            } else {
                var cells = self.selectedCells;
                if (cells.length !== 1)
                    return;
                var record = new DescCell(cells[0])
                self.descCellModel(record);
                self.showDesc(true);
                var target = self.scope.find(".rp-gen").rg("getCellElement");
                $(".desc-box").position({
                    my: 'top top',
                    at: 'top top',
                    of: $(target)
                });
            }
        }
        self.saveAsDefault = function () {
            if (!self.editable())
                return;
            var textColor = self.scope.find("#textColor")[0].style.backgroundColor;
            var backColor = self.scope.find("#backColor")[0].style.backgroundColor;
            var align = self.scope.find(".align-btn.selected-tools");
            if (align.length) {
                align = $(align).attr("data-value");
            } else {
                align = undefined;
            }
            var fontData = self.scope.find(".fnt-selector").fontSelector("getValues");
            clientStorage.setSetting(
                [{
                    key: "DefaultTemplateStyle", value: JSON.stringify({
                        textColor: textColor,
                        backColor: backColor,
                        textFontFamily: fontData[0],
                        textFontSize: fontData[1],
                        align: align
                    })
                }]
            );
            var text = _h.getApiMessage("SaveSetting");
            _h.successToast(text);
        }
        self.getDefault = function () {
            var model = {};
            var data = clientStorage.getSetting("DefaultTemplateStyle");
            if (!_h.isEmpty(data)) {
                model = JSON.parse(data);
                if (!model.textFontSize)
                    model.textFontSize = "12px";
                if (!model.textFontFamily)
                    model.textFontFamily = "Nazanin";

            } else {
                return {
                    textColor: "",
                    backColor: "",
                    textFontSize: "12px",
                    textFontFamily: "Nazanin",
                    align: undefined
                };
            }
            return model;
        }
        self.undo = function () {
            var defaultVal = self.getDefault();
            self.scope.find(".rp-gen").rg("undo", defaultVal);
            setTimeout(function () {
                self.toolbarState();
                _h.kocnx().ttvm().refreshCellSpecMenu();
            }, 50);
            self.refreshCompare();
        }
        self.redo = function () {
            var defaultVal = self.getDefault();
            self.scope.find(".rp-gen").rg("redo", defaultVal);
            setTimeout(function () {
                self.toolbarState();
            }, 50);
            self.refreshCompare();
        }
        self.dispose = function () {
            var baseSelector = "#" + self.id;
            $(baseSelector + " .toolbar-btn").off('click');
        }
    },
    template: '<!-- ko template: { name: "rg-component-t" } --><!-- /ko -->'

});

$(document).on("shown.bs.tab", '.rg-tab a[data-toggle="tab"]', function () {
    var all = ko.contextFor(this);
    _h.kocnx().ttvm().changeDesignItem(all.$data);
    return false;
});


