require('./model');
require('./resource');
import { BaseViewModel } from '../master/baseViewModel.js';
import { SelectItem, DesignItem } from '../master/model';
import { RpSetting, RgMenu, CustomStyleMenu, CellSpecMenu, TableTemplateForm, TableTemplatePreviewDefault, TableTemplatePreview } from './model';
import { ApiService } from "../../util/apiService.js";


export function TableTemplateViewModel() {
    var self = this;
    self.setting = ko.observable(new RpSetting());
    self.rgMenu = ko.observable(new RgMenu(self));
    self.customStyleMenuModel = ko.observable(new CustomStyleMenu());
    self.showList = ko.observable(true);
    self.showCellSpecMenu = ko.observable(false);
    self.showCustomStyleMenu = ko.observable(false);
    self.fullScreen = ko.observable(false);
    self.toggleShowList = function () {
        if (self.editList().length === 0 && self.showList()) {
            return;
        }
        self.showList(!self.showList());
    }
    self.closeAllSubModal = function (callback) {
        self.rgMenu().closeAllModals();
        self.cellSpecMenuModel.show(false);
        if (self.showCustomStyleMenu()) {
            self.showCustomStyleMenu(false);
        }
        callback(true);
    }
    self.editList = ko.observableArray([]);
    self.backupSelectedRecords = ko.observableArray();
    self.treeSelectList = ko.observableArray();
    self.focusDesignItem = ko.observable();
    self.tableTemplateList = ko.observableArray();
    self.cellSpecMenuModel = new CellSpecMenu();
    self.periodList = ko.observableArray();
    self.firstLoadError = false;
    self.getPeriods = function () {
        ApiService.request(
            {
                url: "/api/common/getselectableperiods",
                data: {
                    controllerName: 19
                },
                success: function (data) {
                    self.periodList.removeAll();
                    if (_h.any(data))
                        for (var j = 0; j < data.length; j++) {
                            if (!_h.isNullOrEmpty(data[j])) {
                                self.periodList.push(data[j]);
                            }
                        }
                },
                error: function (data) {
                    if (data === 550)
                        self.firstLoadError = true;
                }
            });
    }
    self.getTableTemplateList = function () {
        ApiService.request({
            url: "/api/tablestructure/gettabletemplateslist",
            success: function (data) {
                self.tableTemplateList.removeAll();
                if (_h.any(data))
                    for (var j = 0; j < data.length; j++) {
                        var target = data[j];
                        self.tableTemplateList.push(new SelectItem(target));
                    }
            },
            error: function (data) {
                var text = _h.getApiMessage("ErrorLoadTableTemplate");
                _h.failToast(text);
            }
        });
    }
    self.getTreeSelectList = function () {
        var model = {
            controllerName: 20,
            mappingType: 0
        };
        self.apiService.request({
            name: "getMappingTreeList",
            data: model,
            success: function (data) {
                self.treeSelectList.removeAll();
                if (_h.any(data))
                    for (var j = 0; j < data.length; j++) {
                        var target = data[j];
                        self.treeSelectList.push(new SelectItem(target));
                    }
            },
            error: function () {
                toast.error("Tree", 'getSelectList');
            }
        });
    }
    self.changeDesignItem = function (item) {
        self.closeAllSubModal(function () {
            for (var i = 0; i < self.editList().length; i++) {
                if (self.editList()[i].active() === true)
                    self.editList()[i].active(false);
            }
            item.active(true);
            self.focusDesignItem(item);
        });
    }
    self.closePreviewForm = function () {
        if (self.focusDesignItem()) {
            self.focusDesignItem().previewResult = null;
            self.focusDesignItem().bindErrors = null;
            self.focusDesignItem().previewMode(false);
        }
        _h.kocnx().closeForm();
    }
    self.designBtn = function (parents) {
        self.closeAllSubModal(function () {
            var item = ko.toJS(parents[0]);
            var permit = _h.kocnx().permitPeriodEdit();
            var isPeriodActive = _h.kocnx().periodItem().st === 1;
            if (!item || !isPeriodActive) {
                return;
            }
            var canAdd = true;
            for (var i = 0; i < self.editList().length; i++) {
                if (item.id === self.editList()[i].value()) {
                    canAdd = false;
                    self.editList()[i].active(true);
                    self.focusDesignItem(self.editList()[i]);
                } else {
                    self.editList()[i].active(false);
                }
            }
            if (canAdd) {
                var record = new DesignItem({
                    type: item.templateTableType, text: item.title, value: item.id, active: true, editable: item.editable,
                    lockedByUserId: item.lockedByUserId, lockedBy: item.lockedBy
                });
                self.editList.push(record);
                self.focusDesignItem(record);
                self.saveEditList();
            }
            self.findFocusDesignItem();
        });
    }
    self.findFocusDesignItem = function () {
        var focus = self.editList().filter(a => a.active())[0];
        self.focusDesignItem(focus);
        return focus;
    }
    self.getFocusDesignRecord = function () {
        if (self.focusDesignItem()) {
            var dataModel = $("table.tcs:visible").data("model");
            if (dataModel)
                return {
                    code: dataModel.code,
                    id: dataModel.id,
                    rows: dataModel.rows,
                    cols: dataModel.cols,
                    accountType: dataModel.accountType,
                    defaultColumnNumber: dataModel.defaultColumnNumber,
                    defaultRowNumber: dataModel.defaultRowNumber,
                    folderId: dataModel.folderId,
                    linked: dataModel.linked,
                    name: dataModel.name,
                    periodId: dataModel.periodId,
                    priority: dataModel.priority,
                    tableId: dataModel.tableId,
                    tableTemplateType: dataModel.tableTemplateType
                }
            else
                return {
                    id: self.focusDesignItem().value(),
                    name: self.focusDesignItem().text(),
                }
        }
    }
    self.closeDesignItem = function (item) {
        var id = item.value();
        var editable = item.editable();
        self.closeDesign(item, function () {
            self.clearEditable(id, editable);
        });
    }
    self.clearEditable = function (id, editable) {
        if (editable) {
            var userId = _h.kocnx().currentUser().ui;
            var target = self.records().filter(a => a.id() === id);
            if (target.length && userId === target[0].lockedByUserId()) {
                target[0].editable(false);
                target[0].lockedBy(undefined);
                target[0].lockedByUserId(undefined);
            }
        }
        self.postTemplateEditable(id, false, function () { });
    }
    self.closeDesign = function (item, callback) {
        self.closeAllSubModal(function () {
            var record = self.getFocusDesignRecord();
            var arrayData = $("#rg-" + record.id).find(".rp-gen").rg("toServer");
            if (!arrayData || !arrayData[1]) {
                self.afterCloseDesignItem(item);
                self.findFocusDesignItem();
                callback(true);
            } else {
                var model = arrayData[0];
                var confirmText = _h.getLocalizedText("designCloseAlert");
                confirmText = confirmText.replace("__", `"${item.text()}"`);
                _h.confirmTableTemplateAlert(confirmText, function (res) {
                    switch (res) {
                        case true:
                            self.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.afterCloseDesignItem(item);
                                    self.findFocusDesignItem();
                                    callback(true);
                                }
                            });
                            break;
                        case false:
                            self.afterCloseDesignItem(item);
                            self.findFocusDesignItem();
                            callback(true);
                            break;
                    }
                }, true);
            }
        });
    }
    self.closeGroupDesign = function (item, callback, confirm) {
        self.closeAllSubModal(function () {
            var arrayData = $("#rg-" + item.value()).find(".rp-gen").rg("toServer");
            if (!arrayData || !arrayData[1] || !confirm) {
                self.afterCloseDesignItem(item);
                self.findFocusDesignItem();
                callback(true);
            } else {
                var model = arrayData[0];
                self.saveChanges(model, function (dataRes) {
                    self.afterCloseDesignItem(item);
                    self.findFocusDesignItem();
                    callback(true);
                });
            }
        });
    }
    self.afterCloseDesignItem = function (item) {
        var index;
        if (!item)
            return;
        for (var i = 0; i < self.editList().length; i++) {
            if (!item || !item.value) {
                x = 1;
            }
            if (item.value() === self.editList()[i].value()) {
                index = i;
            }
        }
        if (self.editList().length === 1) {
            self.editList.remove(item);
            self.saveEditList();
            return;
        }
        if (self.editList()[index].active() === false) {
            self.editList.remove(item);
            self.saveEditList();
            return;
        }

        if (index === 0 && self.editList().length > 1) {
            self.editList()[index + 1].active(true);
            item.active(false);
            self.editList.remove(item);
            self.saveEditList();
            return;
        }

        if (index > 0) {
            self.editList()[index - 1].active(true);
            item.active(false);
            self.editList.remove(item);
            self.saveEditList();
            return;
        }
    }
    self.saveChanges = function (model, callback) {
        ApiService.request({
            url: "/api/tablestructure/postsaveexceldata",
            data: model,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    var text = _h.getApiMessage("PostExcelDataSuccess");
                    _h.successToast(text);
                    callback(data.bindErrors);
                }
            },
            error: function (data) {
                var text = _h.getApiMessage("PostExcelDataError");
                _h.failToast(text);
                callback(false)
            }
        });
    }
    self.saveEditList = function () {
        var list = ko.toJS(self.editList());
        var key = "TableTemplateEditList_" + _h.kocnx().periodItem().pi;
        clientStorage.setSetting(
            [{ key: key, value: JSON.stringify(list) }]
        );
    }
    self.createBtn = function () {
        self.getLastPriority(function (res) {
            if (res !== null) {
                _h.kocnx()
                    .openForm(new TableTemplateForm(self, false, res));
            }
        });
    }
    self.editBtn = function () {
        if (!self.checkForEdit()) {
            return;
        }
        self.getLastPriority(function (res) {
            if (res !== null) {
                _h.kocnx()
                    .openForm(new TableTemplateForm(self, true, res));
            }
        });
    }
    self.previewDefaultBtn = function () {
        var id = self.getFocusDesignRecord().id;
        self.getTableTemplatePreview(id, function (res) {
            if (res)
                _h.kocnx()
                    .openForm(new TableTemplatePreviewDefault(self, res));
        });
    }
    self.getTableTemplatePreview = function (id, callback) {
        if (_h.isEmpty(id)) {
            id = self.getSelectedRecord().id();
        }
        self.apiService.request({
            name: "getPreviewOptions",
            data: { id: id },
            success: function (data) {
                callback(data);
            },
            error: function () {
                callback(null);
            }
        });
    }
    self.savePreviewDefault = function (m) {
        var item = m[1];
        var model = item.toServer();
        ApiService.request(
            {
                url: "/api/tabletemplate/postpreviewoptions",
                data: model,
                success: function (data) {
                    toast.success(self.entityName, 'custom', 'PreviewDefault');
                    _h.kocnx().closeForm();
                },
                error: function (data) {
                }
            });
    }
    self.previewBtn = function () {
        ApiService.request({
            url: "/api/tabletemplate/postPreview",
            data: {
                tableTemplateId: self.getSelectedRecord().id()
            },
            success: function (data) {
                if (!_h.isEmpty(data)) {
                    _h.kocnx()
                        .openForm(new TableTemplatePreview(self, data));
                }
            }.bind(this),
            error: function () {
                toast.error("TableTemplate", 'get', "Preview");
            }
        });
    }
    self.exportExcelBtn = function (type) {
        var model = {
            controllerName: 20,
            inputData: {
                tableTemplateId: 0,
                idList: []
            }
        };
        switch (type) {
            case "1":// rpg
                var record = self.getFocusDesignRecord();
                var arrayData = $("#rg-" + record.id).find(".rp-gen").rg("toServer", true);
                model.inputData.tableTemplateId = record.id;
                model.inputData.data = arrayData[0];
                break;
            case "3"://multi
                var list = self.multiCommandExecute("selectedItems");
                if (self.backupSelectedRecords().length > 0) {
                    model.inputData.idList = self.backupSelectedRecords();
                } else {
                    list.filter(a => model.inputData.idList.push(a.id()));
                }
                break;
            default:
                model.inputData.tableTemplateId = self.getSelectedRecord().id();
                break;
        }
        _h.kocnx().createExcel(model);
    }
    self.exportExcelsBtn = function () {
        self.exportExcelBtn("3");
    }
    self.exportPdfBtn = function (type) {
        var model = {
            controllerName: 20,
            inputData: {
                tableTemplateId: 0
            }
        };
        switch (type) {
            case "1":// rpg
                var record = self.getFocusDesignRecord();
                var arrayData = $("#rg-" + record.id).find(".rp-gen").rg("toServer", true);
                model.inputData.tableTemplateId = record.id;
                model.inputData.data = arrayData[0];
                break;
            default:
                model.inputData.tableTemplateId = self.getSelectedRecord().id();
                break;
        }
        _h.kocnx().createPdf(model);
    }
    self.checkForEdit = function () {
        var record = self.getSelectedRecord();
        var inEdit = self.editList().filter(a => a.value() === record.id()).length > 0;
        if (inEdit) {
            var text = _h.getApiMessage("EditLockedTableTemplate");
            _h.failToast(text);
            return false;
        }
        return true;
    }
    self.copyBtn = function () {
        var record = self.getSelectedRecord();
        if (!self.checkForEdit()) {
            return;
        }
        self.apiService.request({
            name: "postCopy",
            data: { id: record.id() },
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    toast.success(self.entityName, 'custom', "Copy");
                    self.afterCreate(data.models);
                    self.getTableTemplateList();
                }
            },
            error: function () {
                toast.error(self.entityName, 'custom', "Copy");
            }
        });
    };
    self.importFileBtn = function () {
        _h.kocnx().importFileBtn(undefined, self, "BackUp");
    }
    self.exportFileBtn = function () {
        if (self.backupSelectedRecords().length > 0) {
            var model = {
                idList: self.backupSelectedRecords()
            };
            self.apiService.request({
                name: "getToExport",
                data: model,
                success: function (data) {
                    if (!_h.isNullOrEmpty(data)) {
                        toast.success(self.entityName, 'custom', 'ExportFile');
                        _h.downloadFile(data);
                        self.backupSelectedRecords.removeAll();
                    }
                },
                error: function () {
                    toast.error(self.entityName, 'custom', 'ExportFile');
                }
            });
        }
    }
    self.init = function () {
        self.iconSize("icon-image-xsmall");
        self.getTreeSelectList();
        self.getTableTemplateList();
        self.fillTableProperties();
        self.getRecords();
        var key = "TableTemplateEditList_" + _h.kocnx().periodItem().pi;
        var model = clientStorage.getSetting(key);
        if (model !== null && model !== undefined) {
            var list = JSON.parse(model);
            if (_h.any(list)) {
                for (var i = 0; i < list.length; i++) {
                    var record = new DesignItem(list[i]);
                    self.editList.push(record);
                    if (record.active())
                        self.focusDesignItem(record);
                }
                self.showList(false);
            }
        }
        self.getFolderList();
        self.setting().init();
        self.customStyleMenuModel().fillCellStyle();
        self.getPeriods();
        self.internal = setInterval(30000, function () {
            self.getLockData();
        });
    }
    self.copyClipboard = function () {
        ko.utils.arrayFilter(self.records(),
            function (record) {
                if (record["list"]) {
                    ko.utils.arrayFilter(record.list(), function (innerRecord) {
                        if (innerRecord.selected() && self.backupSelectedRecords().indexOf(innerRecord.id()) === -1)
                            self.backupSelectedRecords.push(innerRecord.id());
                        if (!innerRecord.selected() && self.backupSelectedRecords().indexOf(innerRecord.id()) !== -1)
                            self.backupSelectedRecords.remove(innerRecord.id());
                    });
                } else {
                    if (record.selected() && self.backupSelectedRecords().indexOf(record.id()) === -1)
                        self.backupSelectedRecords.push(record.id());
                    if (!record.selected() && self.backupSelectedRecords().indexOf(record.id()) !== -1)
                        self.backupSelectedRecords.remove(record.id());
                }
            });
    }
    self.refreshTable = function () {
        self.getRecords();
        self.getTreeSelectList();
    }
    self.refreshCellSpecMenu = function () {
        if (self.cellSpecMenuModel.show()) {
            var model = self.getSpecCellData();
            self.cellSpecMenuModel.init(model);            
        }
    }
    self.getSpecCellData = function () {
        var record = self.getFocusDesignRecord();
        var selectedItems = $("#rg-" + record.id).find(".rp-gen").rg("getSelectedCells");
        if (selectedItems.length === 1) {
            var nodes = $("#rg-" + record.id).find(".rp-gen").rg("getCellValues");
            var columnModel = $("#rg-" + record.id).find(".rp-gen").rg("getTotalCostModel", selectedItems[0].value);
            var model = {
                element: null,
                viewType: "cell",
                parent: self,
                cell: selectedItems[0],
                templateTableType: record.templateTableType,
                nodeCount: nodes.length,
                sortDirection: columnModel.sortDirection,
                groupType: columnModel.groupType
            };
        }
        if (selectedItems.length > 1) {
            var model = {
                element: null,
                viewType: "cells",
                parent: self,
                templateTableType: record.templateTableType,
                cellCount: selectedItems.length,
            };
        }
        return model;
    }
    self.toggleCellSpecMenu = function () {
        var record = self.getFocusDesignRecord();
        if (record) {
            var selectedItems = $("#rg-" + record.id).find(".rp-gen").rg("getSelectedCells");
            if (selectedItems.length > 0) {
                self.cellSpecMenuModel.show(!self.cellSpecMenuModel.show());
                self.refreshCellSpecMenu();
            }
        } else {
            self.cellSpecMenuModel.show(false);
        }
    }
    self.toggleCustomStyleMenu = function () {
        var focusItem = self.findFocusDesignItem();
        self.showCustomStyleMenu(!self.showCustomStyleMenu());
        $(".custom-styles-menu").draggable({
            scroll: true,
            handle: ".customstyle-drag-handle"
        });
    }
    self.toggleFullScreen = function () {
        self.fullScreen(!self.fullScreen());
        if (self.fullScreen()) {
            $(".menu-box").css("display", "none");
            $(".header-bar").css("display", "none");
        } else {
            $(".menu-box").css("display", "");
            $(".header-bar").css("display", "");
        }
    }
    ko.utils.extend(self, new RGCloseUtility(self));
    ko.utils.extend(self, new BaseViewModel({
        entityName: "TableTemplate",
        apiService: {
            actionList: ["filterby",
                "post", "put", "delete", "postcopy",
                "postpreview", "getpreviewoptions",
                "postImport", "gettoexport"]
        },
        buttons: [
            { name: 'edit', access: true, icon: 'Edit', cMenu: true },
            { name: 'delete', access: true, icon: 'Delete', cMenu: true },
            { name: 'up', access: true, icon: 'Up', cMenu: true },
            { name: 'down', access: true, icon: 'Down', cMenu: true },
            { name: 'adminUnlock', access: true, icon: 'UnlockTemplate', cMenu: true },
            { name: 'importFile', access: true, icon: 'ImportFile', cMenu: true },
            { name: 'exportFile', access: true, icon: 'ExportFile', cMenu: true },
            { name: 'exportPdf', access: true, icon: 'ExportPdf', cMenu: true },
            { name: 'exportExcel', access: true, icon: 'ExportExcel', cMenu: true },
            { name: 'exportExcels', access: true, icon: 'ExportExcels', cMenu: true },
            { name: 'preview', access: true, icon: 'Preview', cMenu: true },
            { name: 'copy', access: true, icon: 'Copy', cMenu: true },
            { name: 'help', access: false, cMenu: false },
            { name: 'refresh', access: false, cMenu: false },
            { name: 'tools', templateName: "toolsbtn-tabletemplate-template", access: false, cMenu: false },
            { name: 'create', access: true, cMenu: false }
        ],
        extraParams: ["lastPriority"],
        filters: [],
        sortDirection: "Ascending",
        sortProperty: "priority",
        context: self,
        cols: tabletemplateModelRes,
        getList: true,
        selectRow: true,
        saveState: true,
        searchKeyType: "enter",
        tableClass: "table ko-tbl tbl-template",
        styleRow: "styleRowValue",
        isMultiSelectRows: true,
        folderManagement: true,
        contextMenu: true,
        resizable: true
    }));
    self.countSelectedRecord = ko.pureComputed(function () {
        if (self.records() && self.records().length) {
            var count = 0;
            ko.utils.arrayFilter(self.records(), function (record) {
                if (record['list'] === undefined) {
                    if (record.selected())
                        count++;
                } else {
                    if (_h.any(record['list']()))
                        for (var i = 0; i < record['list']().length; i++) {
                            if (record['list']()[i].selected())
                                count++;
                        }
                }
            });
            return count;
        }
        return 0;
    });
    self.getCountSelectedRecord = function () {
        var aaray = 0;
        ko.utils.arrayFilter(self.records(), function (record) {
            if (record['list'] === undefined) {
                if (record.selected())
                    count++;
            } else {
                if (_h.any(record['list']()))
                    for (var i = 0; i < record['list']().length; i++) {
                        if (record['list']()[i].selected())
                            count++;
                    }
            }
        });
        return count;
    }
    self.btnVisibility = ko.computed(function () {
        var permit = _h.kocnx().permitPeriodEdit();
        var isPeriodActive = _h.kocnx().periodItem().st === 1;
        var list = self.multiCommandExecute("selectedItems");
        var count = list.length;
        if (count === 0 || count > 1) {
            self.visedit(false);
            self.visdelete(false);
            self.vispreview(false);
            self.viscopy(false);
            self.visup(false);
            self.visdown(false);
            self.visexportPdf(false);
            self.visexportExcel(false);
            self.visadminUnlock(false);
        }
        if (count === 1) {
            var priority = list[0].priority();
            self.visedit(permit);
            self.visdelete(permit);
            self.vispreview(isPeriodActive);
            self.viscopy(permit);
            self.visup(permit && priority > 1);
            self.visdown(permit && self.lastPriority() !== priority);
            self.visexportPdf(true);
            self.visexportExcel(true);
            var cond = list[0].editable() === true && list[0].lockedByUserId() !== _h.kocnx().loginCompanyId();
            self.visadminUnlock(cond);
            self.visexportExcels(false);
        }
        self.visexportFile(self.backupSelectedRecords().length > 0);
        self.visexportExcels(self.backupSelectedRecords().length > 0 || count > 1);
        self.visimportFile(true);
        self.viscreate(permit);
        self.vishelp(true);
        self.visrefresh(true);
        self.vistools(true);
    });
    self.renderedHandler = function () {
        if (self.groupProperty()) {
            var en = self.entityName;
            var table = $("." + en + "-tbl");
            var colList = table.find("thead th").get();
            if (colList.length) {
                var count = colList.filter(a => a.style.display !== "none").length;
                self.colSpan(count - 1);
            }
        }
    };
    self.tabMenuItems = ko.computed(function () {
        var array = [];
        for (var i = 0; i < tabMenuItems.length; i++) {
            array.push({
                visName: tabMenuItems[i].visName,
                text: tabMenuItems[i].text,
                visible: true,
                action: self[tabMenuItems[i].action],
                icon: tabMenuItems[i].visName
            });
        }
        return array;
    });
    self.refreshPage = function () {
        if (self.firstLoadError) {
            self.editList.removeAll();
            self.init();
            self.firstLoadError = false;
        } else {
            //var record = self.getFocusDesignRecord();
            //var arrayData = $("#rg-" + record.id).find(".rp-gen").rg("toServer");
            //if (!arrayData && arrayData[0] && !arrayData[1]) {

            //}
        }
    }
    self.getDeleteData = function (id, callback) {
        self.apiService.request({
            name: "/api/tabletemplate/gettemplatesummary",
            data: { id: id },
            success: function (data) {
                callback(data);
            },
            error: function () {
                callback(null);
            }
        });
    }
    self.deleteBtn = function () {
        var record = self.getSelectedRecord();
        var id = record.id();
        if (!self.checkForEdit()) {
            return;
        }
        id = record.id();

        self.getDeleteData(id, function (list) {
            if (_h.any(list)) {
                var confirmText = _h.getApiMessage("DeleteTableTemplateConfirm");
                var strings = [];
                list.filter(a => strings.push(a.text));
                var text = strings.join(", ");
                confirmText = confirmText.replace("__", text);
                _h.confirmDeleteAlert(confirmText,
                    function (res) {
                        if (res) {
                            self.delete(id);
                        }
                    });
            } else {
                var confirmText = toast.createMessage(self.entityName, 'del', null, 'confirm');
                _h.confirmDeleteAlert(confirmText,
                    function (res) {
                        if (res) {
                            self.delete(id);
                        }
                    });
            }
        });
    }
    self.delete = function (id) {
        var model = { id: id };
        self.apiService.request({
            name: "delete",
            data: model,
            success: function (data) {
                if (!_h.isNullOrEmpty(data)) {
                    self.afterDelete(id, data.models);
                    self.selectedRecord(null);
                    toast.success(self.entityName, 'del');
                    self.updateExtraParams(data);
                }
            },
            messageType: 'del',
            messageKey: self.entityName
        });
    }
    self.getLockData = function () {
        ApiService.request(
            {
                url: "/api/common/getlockedlist",
                data: {
                    controllerName: 19
                },
                success: function (data) {
                    if (_h.any(data))
                        self.setLockedList(data);
                },
                error: function (data) {

                }
            });
    }
    self.setLockedList = function (list) {
        if (_h.any(self.records()))
            for (var j = 0; j < self.records().length; j++) {
                var target = list.filter(a => a.id === self.records()[j].id());
                if (_h.any(target)) {
                    self.records()[j].editable(target[0].editable);
                    self.records()[j].lockedBy(target[0].lockedBy);
                    self.records()[j].lockedByUserId(target[0].lockedByUserId);
                } else {
                    self.records()[j].editable(false);
                    self.records()[j].lockedBy(undefined);
                    self.records()[j].lockedByUserId(undefined);
                }
            }
        if (_h.any(self.editList()))
            for (var j = 0; j < self.editList().length; j++) {
                var target = list.filter(a => a.id === self.editList()[j].value());
                if (_h.any(target)) {
                    self.editList()[j].editable(target[0].editable);
                    self.editList()[j].lockedBy(target[0].lockedBy);
                    self.editList()[j].lockedByUserId(target[0].lockedByUserId);
                } else {
                    self.editList()[j].editable(false);
                    self.editList()[j].lockedBy(undefined);
                    self.editList()[j].lockedByUserId(undefined);
                }

            }
    }
    self.setLockedItem = function (item) {
        if (_h.any(self.records())) {
            var target = self.records().filter(a => a.id() === item.id);
            if (_h.any(target)) {
                target[0].editable(item.editable);
                target[0].lockedBy(item.lockedBy);
                target[0].lockedByUserId(item.lockedByUserId);
            }
        }
        if (_h.any(self.editList())) {
            var target = self.editList().filter(a => a.value() === item.id);
            if (_h.any(target)) {
                target[0].editable(item.editable);
                target[0].lockedBy(item.lockedBy);
                target[0].lockedByUserId(item.lockedByUserId);
            }
        }
    }
    self.adminUnlockBtn = function () {
        var record = self.getSelectedRecord();
        ApiService.request(
            {
                url: "/api/common/postadminunlock",
                data: {
                    id: record.id(),
                    controllerName: 19
                },
                success: function (data) {
                    var target = self.records().filter(a => a.id() === record.id());
                    var targetEditList = self.editList().filter(a => a.value() === record.id());
                    if (target.length) {
                        target[0].editable(false);
                        target[0].lockedBy(undefined);
                        target[0].lockedByUserId(undefined);
                        targetEditList[0].editable(false);
                        targetEditList[0].lockedBy(undefined);
                        targetEditList[0].lockedByUserId(undefined);
                    }
                },
                error: function (data) {

                }
            });
    }
    self.postTemplateEditable = function (id, editable, calback) {
        var model = {
            controllerName: 19,
            editable: editable,
            id: id
        };
        ApiService.request(
            {
                url: "/api/common/posteditable",
                data: model,
                success: function (data) {
                    calback(data);
                },
                error: function (data) {
                },
                concurrencyHandler: function (data) {
                    if (data) {
                        calback(data);
                    }
                },
            });
    }
    self.proxyEditable = function (item) {
        var userId = _h.kocnx().currentUser().ui;
        if (userId === item.lockedByUserId()) {
            item.triggerEditable(true);
            item.triggerEditable(false);
        }
        else {
            var massage = _h.getApiMessage("lockedByOtherUserError");
            toast.custom("error", massage);
        }
    }
}
function RGCloseUtility(parent) {
    var self = this;
    self.parent = parent;
    self.rightClickSelectTab = function (item) {
        setTimeout(function () {
            self.parent.changeDesignItem(item);
        }, 10);
    }
    self.closeThis = function (item, e) {
        var id = item.value();
        var editable = item.editable();
        self.parent.closeDesign(item, function () {
            self.parent.clearEditable(id, editable);
        });
    }
    self.closeAll = function (item, e) {
        if (e !== undefined) {
            if (self.parent.editList().length < 1)
                return false;
        }
        self.getCloseList("all");
        var needConfirm = self.parent.editList().filter(a => a["changed"]).length > 0;
        if (!needConfirm) {
            self.closeFunc(item, false);
        } else {
            var confirmText = _h.getLocalizedText("designCloseAllAlert");
            _h.confirmTableTemplateAlert(confirmText, function (res) {
                if (res !== undefined) {
                    self.closeFunc(item, res);
                }
            }, true);
        }
    }
    self.closeFunc = function (item, confirm) {
        var id = item.value();
        var editable = item.editable();
        self.parent.closeGroupDesign(item, function () {
            self.parent.clearEditable(id, editable);
            if (self.parent.editList().length > 0) {
                var focus = self.parent.editList().filter(a => a["needClose"])[0];
                if (focus)
                    self.closeFunc(focus, confirm);
            }
        }, confirm);
    }
    self.closeAllButThis = function (item, e) {
        if (e !== undefined) {
            if (self.parent.editList().length < 2)
                return false;
        }
        self.getCloseList("butthis");
        var focus = self.parent.editList().filter(a => a["needClose"])[0];
        if (!focus) {
            return;
        }
        var needConfirm = self.parent.editList().filter(a => a["changed"]).length > 0;
        if (!needConfirm) {
            self.closeFunc(focus, false);
        } else {
            var confirmText = _h.getLocalizedText("designCloseAllAlert");
            _h.confirmTableTemplateAlert(confirmText, function (res) {
                if (res !== undefined) {
                    self.closeFunc(focus, res);
                }
            }, true);
        }

    }
    self.closeRight = function (item, e) {
        if (e !== undefined) {
            if (self.parent.editList().length < 2)
                return false;
        }
        self.getCloseList("right");
        var focus = self.parent.editList().filter(a => a["needClose"])[0];
        if (!focus) {
            return;
        }
        var needConfirm = self.parent.editList().filter(a => a["changed"]).length > 0;
        if (!needConfirm) {
            self.closeFunc(focus, false);
        } else {
            var confirmText = _h.getLocalizedText("designCloseAllAlert");
            _h.confirmTableTemplateAlert(confirmText, function (res) {
                if (res !== undefined) {
                    self.closeFunc(focus, res);
                }
            }, true);
        }
    }
    self.closeLeft = function (item, e) {
        if (e !== undefined) {
            if (self.parent.editList().length < 2)
                return false;
        }
        self.getCloseList("left");
        var focus = self.parent.editList().filter(a => a["needClose"])[0];
        if (!focus) {
            return;
        }

        var needConfirm = self.parent.editList().filter(a => a["changed"]).length > 0;
        if (!needConfirm) {
            self.closeFunc(focus, false);
        } else {
            var confirmText = _h.getLocalizedText("designCloseAllAlert");
            _h.confirmTableTemplateAlert(confirmText, function (res) {
                if (res !== undefined) {
                    self.closeFunc(focus, res);
                }
            }, true);
        }

    }
    self.getCloseList = function (type) {
        var focus = self.parent.editList().filter(a => a.active())[0];
        var focusIndex = self.parent.editList().indexOf(focus);
        ko.utils.arrayForEach(self.parent.editList(), function (item, index) {
            var condtion = true;
            switch (type) {
                case "all":
                    condtion = true;
                    break;
                case "left":
                    condtion = index > focusIndex;
                    break;
                case "right":
                    condtion = index < focusIndex;
                    break;
                case "butthis":
                    condtion = index !== focusIndex;
                    break;
            }
            if (condtion) {
                var arrayData = $("#rg-" + item.value()).find(".rp-gen").rg("toServer");
                if (arrayData) {
                    var model = arrayData[0];
                    var isChanged = arrayData[1];
                    if (model && isChanged) {
                        item.needClose = true;
                        item.changed = true;
                    } else {
                        item.needClose = true;
                        item.changed = false;
                    }
                } else {
                    item.needClose = true;
                    item.changed = false;
                }
            }
        });
    }
}


$(document).on("focus", '.focus-area', function (e) {
    var loc = $(e.currentTarget).attr("data-loc");
    window.resSecondDomain = loc;
});