dojo.provide("parus.designerTemplatesDialog");

dojo.require("dijit.Dialog");
dojo.require("dijit.form.Button");

dojo.require("parus.parus8");
dojo.require("parus.dialog");
dojo.require("parus.gridData");

dojo.require("parus.templateDesignPane");

dojo.require("parus.designerTemplateDialog");
dojo.require("parus.designerTemplateRoleAndUserAssignDialog");

dojo.declare("parus.designerTemplatesDialog", [parus.Dialog], {

  editionRN: null,

  _refreshGridTimeoutID: null,
  _selectedMaster: null,

  postCreate: function() {
    this.inherited(arguments);


    this.templatesGrid.attr("store", new parus.gridData({

      queryid: "BalanceReportFormsTemplates",

      onGetConditions: dojo.hitch(this, function(store) {

        store.parentRN = this.editionRN;

        return {
          PRN: this.editionRN
        };
      }),
      onComplete: dojo.hitch(this, function(store, items) {

        if ((items.length > 0) && !this.templatesGrid.selection.getSelectedCount()) {
          this.templatesGrid.selection.select(0);
          this.templatesGrid.updateRow(0);
          this.templatesGrid.autoSelected = true;
        }
        this.templatesGrid.onSelected();
      })
    }));
    this.templatesGrid.setQuery({});

    this.indexesGrid.attr("store", new parus.gridData({

      queryid: "BalanceReportFormsTemplatesIndexes",

      onGetConditions: dojo.hitch(this, function(astore) {

        var store = this.templatesGrid.store;
        var index = this.templatesGrid.selection.getSelectedIndex();
        var item = (index >= 0) ? this.templatesGrid.getItem(index) : null;

        astore.parentRN = store.getValue(item, "RN");

        return {
          PRN: store.getValue(item, "RN") || parus.parus8.CLASS_EmptyData
        };
      }),
      onComplete: dojo.hitch(this, function(store, items) {

        if ((items.length > 0) && !this.indexesGrid.selection.getSelectedCount()) {
          this.indexesGrid.selection.select(0);
          this.indexesGrid.updateRow(0);
          this.indexesGrid.autoSelected = true;
        }

      })

    }));
    this.indexesGrid.setQuery({});


    this.tablesGrid.attr("store", new parus.gridData({

      queryid: "BalanceReportFormsTemplatesTables",

      onGetConditions: dojo.hitch(this, function(astore) {

        var store = this.templatesGrid.store;
        var index = this.templatesGrid.selection.getSelectedIndex();
        var item = (index >= 0) ? this.templatesGrid.getItem(index) : null;

        astore.parentRN = store.getValue(item, "RN");

        return {
          PRN: store.getValue(item, "RN") || parus.parus8.CLASS_EmptyData
        };
      }),
      onComplete: dojo.hitch(this, function(store, items) {

        if ((items.length > 0) && !this.tablesGrid.selection.getSelectedCount()) {
          this.tablesGrid.selection.select(0);
          this.tablesGrid.updateRow(0);
          this.tablesGrid.autoSelected = true;
        }

      })

    }));
    this.tablesGrid.setQuery({});


    this.usersGrid.attr("store", new parus.gridData({

      queryid: "BalanceReportFormsTemplatesUsers",

      onGetConditions: dojo.hitch(this, function(astore) {

        var store = this.templatesGrid.store;
        var index = this.templatesGrid.selection.getSelectedIndex();
        var item = (index >= 0) ? this.templatesGrid.getItem(index) : null;

        astore.parentRN = store.getValue(item, "RN");

        return {
          PRN: store.getValue(item, "RN") || parus.parus8.CLASS_EmptyData
        };
      }),
      onComplete: dojo.hitch(this, function(store, items) {

        if ((items.length > 0) && !this.usersGrid.selection.getSelectedCount()) {
          this.usersGrid.selection.select(0);
          this.usersGrid.updateRow(0);
          this.usersGrid.autoSelected = true;
        }

      })

    }));
    this.usersGrid.setQuery({});


    this.historyGrid.attr("store", new parus.gridData({

      queryid: "BalanceReportFormsTemplatesHistory",

      onGetConditions: dojo.hitch(this, function(astore) {

        var store = this.templatesGrid.store;
        var index = this.templatesGrid.selection.getSelectedIndex();
        var item = (index >= 0) ? this.templatesGrid.getItem(index) : null;

        astore.parentRN = store.getValue(item, "RN");

        return {
          PRN: store.getValue(item, "RN") || parus.parus8.CLASS_EmptyData
        };
      }),
      onComplete: dojo.hitch(this, function(store, items) {

        if ((items.length > 0) && !this.historyGrid.selection.getSelectedCount()) {
          this.historyGrid.selection.select(0);
          this.historyGrid.updateRow(0);
          this.historyGrid.autoSelected = true;
        }

      })

    }));
    this.historyGrid.setQuery({});


    parus.balance._createActionsButton(this.templatesPopupMenu, this.headerPane);
    this.templatesPopupMenu.bindDomNode(this.templatesGrid.viewsNode);

    var settings = parus.userdata.get(this.declaredClass);

    if (settings) {
      parus.gridSettingsDialog.mergeMenuSettings(this.templatesPopupMenu, settings.actionSettings, settings.userProcsActions, settings.userReportsActions, settings.userAppsActions);
      parus.gridSettingsDialog.mergeGridSettings(this.templatesGrid, settings.gridSettings);
      parus.gridSettingsDialog.mergeColorConditions(this.templatesGrid, settings.colorConditions);
      parus.gridSettingsDialog.mergeFilterBar(this.templatesGrid, settings.showFilterBar, settings.filterValues, settings.sortInfo);
    };

    var settings = parus.userdata.get(this.declaredClass + '-indexesGrid');

    if (settings) {
      parus.gridSettingsDialog.mergeMenuSettings(this.indexesGridPopupMenu, settings.actionSettings, settings.userProcsActions, settings.userReportsActions, settings.userAppsActions);
      parus.gridSettingsDialog.mergeGridSettings(this.indexesGrid, settings.gridSettings);
      parus.gridSettingsDialog.mergeColorConditions(this.indexesGrid, settings.colorConditions);
      parus.gridSettingsDialog.mergeFilterBar(this.indexesGrid, settings.showFilterBar, settings.filterValues, settings.sortInfo);
    };

    parus.balance._createActionsButton(this.indexesGridPopupMenu, this.indexesGridHeaderPane);
    this.indexesGridPopupMenu.bindDomNode(this.indexesGrid.viewsNode);

    var settings = parus.userdata.get(this.declaredClass + '-tablesGrid');

    if (settings) {
      parus.gridSettingsDialog.mergeMenuSettings(this.tablesGridPopupMenu, settings.actionSettings, settings.userProcsActions, settings.userReportsActions, settings.userAppsActions);
      parus.gridSettingsDialog.mergeGridSettings(this.tablesGrid, settings.gridSettings);
      parus.gridSettingsDialog.mergeColorConditions(this.tablesGrid, settings.colorConditions);
      parus.gridSettingsDialog.mergeFilterBar(this.tablesGrid, settings.showFilterBar, settings.filterValues, settings.sortInfo);
    };

    parus.balance._createActionsButton(this.tablesGridPopupMenu, this.tablesGridHeaderPane);
    this.tablesGridPopupMenu.bindDomNode(this.tablesGrid.viewsNode);


    var settings = parus.userdata.get(this.declaredClass + '-usersGrid');

    if (settings) {
      parus.gridSettingsDialog.mergeMenuSettings(this.usersGridPopupMenu, settings.actionSettings, settings.userProcsActions, settings.userReportsActions, settings.userAppsActions);
      parus.gridSettingsDialog.mergeGridSettings(this.usersGrid, settings.gridSettings);
      parus.gridSettingsDialog.mergeColorConditions(this.usersGrid, settings.colorConditions);
      parus.gridSettingsDialog.mergeFilterBar(this.usersGrid, settings.showFilterBar, settings.filterValues, settings.sortInfo);
    };

    parus.balance._createActionsButton(this.usersGridPopupMenu, this.usersGridHeaderPane);
    this.usersGridPopupMenu.bindDomNode(this.usersGrid.viewsNode);


    var settings = parus.userdata.get(this.declaredClass + '-historyGrid');

    if (settings) {
      parus.gridSettingsDialog.mergeMenuSettings(this.historyGridPopupMenu, settings.actionSettings, settings.userProcsActions, settings.userReportsActions, settings.userAppsActions);
      parus.gridSettingsDialog.mergeGridSettings(this.historyGrid, settings.gridSettings);
      parus.gridSettingsDialog.mergeColorConditions(this.historyGrid, settings.colorConditions);
      parus.gridSettingsDialog.mergeFilterBar(this.historyGrid, settings.showFilterBar, settings.filterValues, settings.sortInfo);
    };

    parus.balance._createActionsButton(this.historyGridPopupMenu, this.historyGridHeaderPane);
    this.historyGridPopupMenu.bindDomNode(this.historyGrid.viewsNode);


  },

  gridChanged: function() {
    if (this._refreshGridTimeoutID) clearTimeout(this._refreshGridTimeoutID);
    this._refreshGridTimeoutID = setTimeout(dojo.hitch(this, function() {
      if (this._refreshGridTimeoutID) clearTimeout(this._refreshGridTimeoutID);
      this._refreshGridTimeoutID = null;

      var grid = this.templatesGrid;
      var store = grid.store;

      var index = grid.selection.getSelectedIndex();
      var item = (index >= 0) ? grid.getItem(index) : null;
      var selectedMaster = store.getValue(item, "RN") || parus.parus8.CLASS_EmptyData;

      if (this._selectedMaster != selectedMaster) {
        this._selectedMaster = selectedMaster;
        parus.balance.refreshGrid(this.indexesGrid);
        parus.balance.refreshGrid(this.tablesGrid);
        parus.balance.refreshGrid(this.usersGrid);
        parus.balance.refreshGrid(this.historyGrid);
      }

    }), 300);
  },


  createTemplate: function(grid) {
    parus.editableDictionaryDialog.prototype.insertAction(this, grid, parus.designerTemplateDialog);
  },

  duplicateTemplate: function(grid) {
    parus.editableDictionaryDialog.prototype.duplicateAction(this, grid, parus.designerTemplateDialog);
  },

  editTemplate: function(grid) {
    parus.editableDictionaryDialog.prototype.updateAction(this, grid, parus.designerTemplateDialog);
  },

  deleteTemplate: function(grid) {
    parus.editableDictionaryDialog.prototype.deleteAction(this, grid, parus.designerTemplateDialog);
  },

  tableIndexes: function(grid) {
    var store = grid.store;
    var item = grid.selection.getFirstSelected();

    var dictionaryInfo = parus.dictionaries["DesignerTemplateTableIndexes"];

    dojo.mixin(dictionaryInfo, {
      dictionary: dictionaryInfo,
      unitCode: dictionaryInfo.unitCode,
      hideCancel: true,
      gridConditions: {
        PRN: store.getValue(item, "RN")
      }
    });

    (new parus.dictionaryDialog(dictionaryInfo)).show();
  },

  tableTotals: function(grid) {
    var store = grid.store;
    var item = grid.selection.getFirstSelected();

    var dictionaryInfo = parus.dictionaries["DesignerTemplateTableTotals"];

    dojo.mixin(dictionaryInfo, {
      dictionary: dictionaryInfo,
      unitCode: dictionaryInfo.unitCode,
      hideCancel: true,
      gridConditions: {
        PRN: store.getValue(item, "RN")
      }
    });

    (new parus.dictionaryDialog(dictionaryInfo)).show();
  },

  deleteHistory: function(grid) {
    parus.gridActions.deleteSelected(grid, function(store, item) {
      parus.database.execute("deleteBalanceReportFormsTemplatesHistory", {
        RN: store.getValue(item, "RN")
      });
    });
  },

  rollbackHistory: function(grid) {
    if (grid.selection.getSelectedCount() != 1) {
      parus.parus8.errorMessage("Выберите одну запись истории.");
      return;
    };

    (new parus.confirmationDialog({

      message: "Восстановить версию трафарета?",

      onApply: function() {

        var store = grid.store;
        var item = grid.selection.getFirstSelected();

        parus.database.execute("BalanceReportFormsTemplatesHistoryRollback", {
          RN: store.getValue(item, "RN")
        });

        grid.selection.deselectAll();
        parus.balance.refreshGrid(grid);

        return true;
      }
    })).show();

  },

  showEditor: function(grid) {

    var selected = false;
    var store = this.templatesGrid.store;
    var item = this.templatesGrid.selection.getFirstSelected();
    for (var i = 0; i < this.templatesGrid.selection.getSelectedCount(); i++) {

      var template = store.getValue(item, "RN");

      if (!parus.balance.TabContainer || parus.parus8._embeddedMode) {

        if (parus.parus8._themeEditorMode) {
          alert("В режиме редактирования схемы это действие невозможно.");
          return;
        }


        var url = dojo.moduleUrl("parus", "designerTemplate.html") + "?loggedUserHandler=" + parus.database.connected + "&params=" + parus.parus8.hexEncodeParams([template]);

        if (parus.parus8._embeddedMode) {
          var id = [report, subreport, (+(new Date))].join("_");
          parus.embeddedMode.openTab(id, "Редактирование трафарета", url);
        } else {
          window.open(url, "_blank");
        }

        parus.parus8.registerAction();

        return;
      }

      var contentPane;

      var borderContainer = new dijit.layout.BorderContainer({
        design: "headline",
        gutters: false,
        "class": "balanceTemplateContentPane",
        region: "center",
        style: "height:100%;width:100%;padding:0"
      });


      var title = parus.balance.describeReport(null, null, template, null, null, null, null, 6);

      var headingContentPane = parus.balance._createHeadingPane(title);

      borderContainer.addChild(headingContentPane);


      var templateGridPane = new parus.templateDesignPane({
        region: "center",
        template: template,
        headingContentPane: headingContentPane,
        onModified: function() {
          if (contentPane.controlButton) {
            var list = dojo.query("*", contentPane.controlButton.containerNode);
            list.removeClass("balanceReadOnlyHeader");
            list.removeClass("balanceModifiedHeader");
            if (templateGridPane.readonly) list.addClass("balanceReadOnlyHeader");
            else if (templateGridPane.modified) list.addClass("balanceModifiedHeader");
          }

          if (parus.parus8._embeddedMode) {
            parus.embeddedMode.changeTabState(templateGridPane.modified);
          }
        },
        onTitleChanged: function() {
          if (templateGridPane.title) {
            var title = parus.balance.formatPageTitle(templateGridPane.title);

            contentPane.attr("title", title);

            if (parus.parus8._embeddedMode) {
              parus.embeddedMode.changeTabTitle(title);
            }
          }
        }

      });

      borderContainer.addChild(templateGridPane);

      contentPane = new dijit.layout.ContentPane({
        title: parus.balance.formatPageTitle(title),
        closable: true,
        region: "center",
        "class": "balanceTemplateContentPane",
        onClose: dojo.hitch(templateGridPane, templateGridPane.onClose)
      });

      templateGridPane.parentPane = contentPane;

      contentPane.setContent(borderContainer);

      if (parus.balance.TabContainer) {
        parus.balance.TabContainer.addChild(contentPane);
        if (!selected) {
          parus.balance.TabContainer.selectChild(contentPane);
          selected = true;
        }
      }

      item = this.templatesGrid.selection.getNextSelected(item);
    };

    this.close();

  },

  insertUser: function(grid) {
    parus.editableDictionaryDialog.prototype.insertAction(this, grid, parus.designerTemplateRoleAndUserAssignDialog);
  },

  duplicateUser: function(grid) {
    parus.editableDictionaryDialog.prototype.duplicateAction(this, grid, parus.designerTemplateRoleAndUserAssignDialog);
  },

  editUser: function(grid) {
    parus.editableDictionaryDialog.prototype.updateAction(this, grid, parus.designerTemplateRoleAndUserAssignDialog);
  },

  deleteUser: function(grid) {
    parus.editableDictionaryDialog.prototype.deleteAction(this, grid, parus.designerTemplateRoleAndUserAssignDialog);
  }

});


dojo.mixin(parus.designerTemplatesDialog, {

  formatUsage: function(data, rowIndex, column) {
    return (["Для редактирования", "Для экспорта"])[data];
  },

  formatDirection: function(data, rowIndex, column) {
    return (["Вниз", "Вправо"])[data];
  },

  formatTableColNumber: function(data, rowIndex, column) {
    return "$" + parus.parus8.toLetters(data);
  },

  formatTableRowNumber: function(data, rowIndex, column) {
    return "$" + data.toString();
  }

});