dojo.provide("parus.balanceIndexConsComparationItems");

dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dojo.data.ItemFileWriteStore");

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

dojo.require("dojox.grid.cells.dijit");

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

dojo.require("parus.balanceIndexConsComparation");
dojo.require("parus.balanceIndexConsComparationItem");
dojo.require("parus.balanceIndexConsComparationTemplate");
dojo.require("parus.balanceIndexConsComparationTemplatesDialog");

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

  skipUnsignificantZeroes: false,

  onShow: function() {
    var settings = parus.userdata.get(this.declaredClass);
    if (settings) if (settings.additions) this.skipUnsignificantZeroes = settings.additions.skipUnsignificantZeroes;
    var fc = {
      intPart: parus.parus8.consComparationData.intPart,
      fracPart: this.skipUnsignificantZeroes ? null : parus.parus8.consComparationData.fracPart
    };

    dojo.mixin(this.consItemsGrid.views.views[0].structure.cells[0][2], fc);
    dojo.mixin(this.consItemsGrid.views.views[0].structure.cells[0][2]._props, fc);

    dojo.mixin(this.consItemsGrid.structure[0].cells[0][1], fc);
    dojo.mixin(this.consItemsGrid.structure[0].cells[0][1]._props, fc);

    this.consItemsGridPopupMenu.bindDomNode(this.consItemsGrid.viewsNode);
    parus.balance._createActionsButton(this.consItemsGridPopupMenu, this.headerPane);

    if (settings) {
      parus.gridSettingsDialog.mergeGridSettings(this.consItemsGrid, settings.gridSettings);
      parus.gridSettingsDialog.mergeColorConditions(this.consItemsGrid, settings.colorConditions);
      parus.gridSettingsDialog.mergeMenuSettings(this.consItemsGridPopupMenu, settings.actionSettings, settings.userProcsActions, settings.userReportsActions, settings.userAppsActions);
      parus.gridSettingsDialog.mergeFilterBar(this.consItemsGrid, settings.showFilterBar, settings.filterValues, settings.sortInfo);
    };
    this.consItemsGrid.attr("store", this.gridStore());
    this.consItemsGrid.setQuery({});
  },

  gridStore: function() {

    var args = [];
    var argvals = [];
    var errors = [];

    dojo.forEach(parus.parus8.consComparationData.items, function(item) {

      if (item["INDEX"]) {
        item["VALUE"] = parus.parus8.nodeField(parus.parus8.rowNodes(parus.database.execute("IndexConsValue", {
          "REPORT": item["REPORT"],
          "SUBREPORT": item["SUBREPORT"],
          "INDEX": item["INDEX"],
          "TABLE": item["TABLE"],
          "ROWID": item["ROWID"]
        }))[0], "VALUE");

        if (parus.parus8.consComparationData.dataType == "1") item["VALUE"] = parus.parus8.formatIndexConsValue(item["VALUE"] || 0, parus.parus8.consComparationData.intPart, parus.parus8.consComparationData.fracPart);

        args.push(item["IDENTIFIER"]);
        argvals.push(parus.parus8.externalStringToValue(item["VALUE"] || 0, parus.parus8.consComparationData.dataType));

      }
    });

    dojo.forEach(parus.parus8.consComparationData.items, function(item) {

      if (!item["INDEX"]) try {
        item["VALUE"] = (Function.apply(this, args.concat("return (" + item["EXPRESSION"] + ")"))).apply(this, argvals);

        if (parus.parus8.consComparationData.dataType == "1") item["VALUE"] = parus.parus8.formatIndexConsValue(item["VALUE"] || 0, parus.parus8.consComparationData.intPart, parus.parus8.consComparationData.fracPart);
      }
      catch (e) {
        errors.push(e.toString());
        item["VALUE"] = null;
      };
    });

    if (errors.length) {
      errors.unshift("Ошибки расчётов:");
      setTimeout(function() {
        parus.parus8.errorMessage(errors.join("\n"));
      }, 1000);
    };

    return new parus.gridData({
      persistent: true,
      _data: parus.parus8.consComparationData.items
    });
  },

  clear: function() {

    (new parus.confirmationDialog({

      message: "Очистить список показателей для сравнения состава?",

      onApply: dojo.hitch(this, function() {
        parus.parus8.consComparationData = null;
        parus.parus8.consComparationDataModified();
        this.close();
        return true;
      })
    })).show();
  },

  performIndexConsComparation: function() {

    this.applied = true;
    this.close();
    parus.parus8.performIndexConsComparation();

  },

  deleteItem: function() {
    var selectedCount = this.consItemsGrid.selection.getSelectedCount();

    if (parus.parus8.consComparationData.items.length <= selectedCount) this.clear();
    else {

      var store = this.consItemsGrid.store;
      var index = this.consItemsGrid.selection.getSelectedIndex();

      (new parus.confirmationDialog({

        message: "Удалить запись (записи)?",

        onApply: dojo.hitch(this, function() {

          var item = this.consItemsGrid.selection.getFirstSelected();
          for (var i = 0; i < selectedCount; i++) {
            var idx = store.findIndex("ID", store.getValue(item, "ID"));
            parus.parus8.consComparationData.items.splice(idx, 1);
            item = this.consItemsGrid.selection.getNextSelected(item);
          };
          parus.parus8.consComparationDataModified();
          this.consItemsGrid.selection.deselectAll();
          this.consItemsGrid.attr("store", this.gridStore());
          this.consItemsGrid.setQuery({});
          this.consItemsGrid.selection.select(index - 1);
          this.consItemsGrid.updateRow(index - 1);
          this.consItemsGrid.scrollToRow(index - 1);

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

  addItem: function() {

    var dialog = new parus.balanceIndexConsComparationItem({

      onApply: dojo.hitch(this, function() {

        parus.parus8.consComparationData.items.push({
          "ID": new Date().valueOf(),
          "TITLE": dialog.titleEdit.attr("value"),
          "EXPRESSION": dialog.expressionEdit.attr("value"),
          "INCLUDEDIFF": true
        });
        parus.parus8.consComparationDataModified();
        var index = parus.parus8.consComparationData.items.length;

        this.consItemsGrid.attr("store", this.gridStore());
        this.consItemsGrid.setQuery({});
        this.consItemsGrid.selection.select(index - 1);
        this.consItemsGrid.updateRow(index - 1);
        this.consItemsGrid.scrollToRow(index - 1);

        return true;
      })

    });
    dialog.show();
  },

  editItem: function() {
    var store = this.consItemsGrid.store;
    var index = this.consItemsGrid.selection.getSelectedIndex();
    var item = this.consItemsGrid.selection.getFirstSelected();

    if (!item) return;
    if (!store.getValue(item, "EXPRESSION")) return;

    var dialog = new parus.balanceIndexConsComparationItem({
      onShow: function() {
        dialog.titleEdit.attr("value", store.getValue(item, "TITLE"));
        dialog.expressionEdit.attr("value", store.getValue(item, "EXPRESSION"));
      },

      onApply: dojo.hitch(this, function() {
        parus.parus8.consComparationData.items[index]["TITLE"] = dialog.titleEdit.attr("value");
        parus.parus8.consComparationData.items[index]["EXPRESSION"] = dialog.expressionEdit.attr("value");
        parus.parus8.consComparationDataModified();
        this.consItemsGrid.selection.deselectAll();
        this.consItemsGrid.attr("store", this.gridStore());
        this.consItemsGrid.setQuery({});
        this.consItemsGrid.selection.select(index);
        this.consItemsGrid.updateRow(index);
        this.consItemsGrid.scrollToRow(index);
        return true;
      })

    });
    dialog.show();
  },

  addFromTemplate: function() {

    var dialog = new parus.balanceIndexConsComparationTemplatesDialog({

      onApply: dojo.hitch(this, function() {

        dojo.forEach(dialog.templatesGrid.selection.getSelected(), function(item) {
          parus.parus8.addIndexConsComparationTemplate(item);
        });
        parus.parus8.consComparationDataModified();
        this.consItemsGrid.attr("store", this.gridStore());
        this.consItemsGrid.setQuery({});
        this.consItemsGrid.selection.select(0);
        this.consItemsGrid.updateRow(0);
        this.consItemsGrid.scrollToRow(0);

        return true;
      })

    });
    dialog.show();

  },

  saveAsTemplate: function() {

    var templateItems = [];

    dojo.forEach(parus.parus8.consComparationData.items, function(item) {

      var templteItem = {};

      templteItem["INCLUDEDIFF"] = item["INCLUDEDIFF"];

      if (item["INDEX"]) {

        templteItem["IDENTIFIER"] = item["IDENTIFIER"];
        templteItem["DATA"] = parus.parus8.nodeField(parus.parus8.rowNodes(parus.database.execute("IndexConsIDData", {
          "REPORT": item["REPORT"],
          "SUBREPORT": item["SUBREPORT"],
          "INDEX": item["INDEX"],
          "TABLE": item["TABLE"],
          "ROWID": item["ROWID"]
        }))[0], "clobDATA");
      }
      else {
        templteItem["TITLE"] = item["TITLE"];
        templteItem["EXPRESSION"] = item["EXPRESSION"];
      };

      templateItems.push(templteItem)

    });

    var dialog = new parus.balanceIndexConsComparationTemplate({

      onApply: dojo.hitch(this, function() {

        parus.balanceIndexConsComparation.saveTemplate({
          name: dialog.nameEdit.attr("value"),
          dataType: parus.parus8.consComparationData.dataType,
          intPart: parus.parus8.consComparationData.intPart,
          fracPart: parus.parus8.consComparationData.fracPart,
          result: parus.parus8.consComparationData.result,
          items: templateItems
        });

        return true;
      })

    });
    dialog.show();

  },

  settingsAdditions: function() {
    return [{
      title: "Скрыть незначащие нули в дробной части числа",

      id: "skipUnsignificantZeroes",

      get: dojo.hitch(this, function() {
        return this.skipUnsignificantZeroes;
      }),

      set: dojo.hitch(this, function(value) {
        this.skipUnsignificantZeroes = !! value;

        var fc = {
          intPart: parus.parus8.consComparationData.intPart,
          fracPart: this.skipUnsignificantZeroes ? null : parus.parus8.consComparationData.fracPart
        };

        var str = dojo.clone(this.consItemsGrid.structure);
        var res = [];
        var strItems = str[0].cells ? str[0].cells[0] : str;
        for (var i = 0; i < strItems.length; i++) {
          dojo.mixin(strItems[i], fc);
          res.push(dojo.clone(strItems[i]));
        };
        if (str[0] && str[0].cells) str[0].cells[0] = res;
        else str = res;

        this.consItemsGrid.setStructure(str);
      })
    }]
  }

});

dojo.mixin(parus.balanceIndexConsComparationItems, {

  formatIncludeCheck: function(data, rowIndex, column) {
    return "<div onclick=\"parus.balanceIndexConsComparationItems.toggleIncludeCheck(dijit.getEnclosingWidget(this).grid," + rowIndex + ")\" class=\"dojoxGridRowSelector dijitReset dijitInline dijitCheckBox " + (data ? "dijitCheckBoxChecked" : "") + " \">" + "<span class=\"dojoxGridRowSelectorStatusText\">" + (data ? "&#8730;" : "&#4F;") + "</span>" + "</div>"
  },

  toggleIncludeCheck: function(grid, rowIndex) {
    parus.parus8.consComparationData.items[rowIndex]["INCLUDEDIFF"] = !! !parus.parus8.consComparationData.items[rowIndex]["INCLUDEDIFF"];
    var item = grid.getItem(rowIndex)["INCLUDEDIFF"] = parus.parus8.consComparationData.items[rowIndex]["INCLUDEDIFF"];
    grid.updateRow(rowIndex);
  }

});