dojo.provide("parus.balanceReportConsolidateDialog");

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

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

dojo.require("parus.balancePreparedConsolidationDialog");

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

  rn: null,

  _conditionFolderRN: null,

  _lastValues: null,

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

    if (this.rn.length > 1) {
      this.mainBorderContainer.domNode.style.height = "480px";
      this.warning.domNode.appendChild(document.createTextNode("Внимание! Количество формируемых сводов: " + this.rn.length));
      this.warning.domNode.style.display = "";

    }

    this.conditionFolder.attr("required", parus.parus8.optionValue("Balance_FillSelectionFolderOnConsolidate") == "1");

    this.conditionFolder.textbox.readOnly = true;

    var ownerDialog = this;

    dojo.mixin(this.conditionFolder, {

      _onKey: function(evt) {
        var dk = dojo.keys;
        var key = evt.charOrCode || evt.keyCode;

        if ((key == dk.DELETE) || (key == dk.BACKSPACE)) {
          this.attr("value", "");
          ownerDialog._conditionFolderRN = null;
          if (evt.preventDefault) evt.preventDefault();
          if (evt.stopPropagation) evt.stopPropagation();
          evt.cancelBubble = true;
          evt.keyCode = 0;
          return false;
        }
      },

      onDictButtonClick: function() {
        if (this.showingDictionary) return;

        if (this.dictionary) {
          var dictionaryInfo = parus.dictionaries[this.dictionary];

          dojo.mixin(dictionaryInfo, {
            code: this.dictionary,
            multiselect: this.multiselect,
            label: this.value,
            dictionary: dictionaryInfo,
            unitCode: this.unitCode || dictionaryInfo.unitCode,
            gridConditions: this.onGetGridConditions(),
            onApply: dojo.hitch(this, function(dialog) {

              ownerDialog._conditionFolderRN = dialog.getValue();

              this.setValue(dialog.getLabel());
              return true;
            }),

            onClose: dojo.hitch(this, function(dialog) {
              this.showingDictionary = false;
            })
          });

          this.showingDictionary = true;
          new parus.dictionaryDialog(dictionaryInfo).show();
        };

        return true;
      }
    });
  },

  onShow: function() {
    if ((parus.parus8.rowNodes(parus.database.query("ConsolidationProposal", {
      "REPORT": this.rn.join(";")
    })) || []).length) {
      this.conditionFolder.attr("disabled", true);
      this.reportType.attr("disabled", true);
    };
    this.restoreFormLastValues();
  },

  onApply: function() {
    var action = new consolidationAction;
    dojo.mixin(action, {
      rn: this.rn,
      rn0: this.rn[0],

      showReportBefore: this.beforeConsolidation.checked,
      showReportAfter: this.afterConsolidation.checked,

      conditionFolder: this._conditionFolderRN || "",
      reportType: this.reportType.value,
      recalculationType: this.recalculationType.value,
      unCheckedReport: (this.unCheckedReport.checked ? "1" : "0"),
      allowRecalculation: (this.allowRecalculation.checked ? "1" : "0"),
      calculateValues: (this.calculateValues.checked ? "1" : "0"),
      stringFormulaType: (this.stringFormulaType.checked ? "1" : "0"),
      numberFormulaType: (this.numberFormulaType.checked ? "1" : "0"),
      dateFormulaType: (this.dateFormulaType.checked ? "1" : "0"),
      formIntermediateResults: (this.formIntermediateResults.checked ? "1" : "0"),
      multiLevel: (this.multiLevel.checked ? "1" : "0"),
      skipNonExisting: (this.skipNonExisting.checked ? "1" : "0"),

      onDone: function() {

        parus.balance.refreshGrid(parus.balance.consolidatedMasterGrid, "RN", this.rn0);

        var grid = parus.balance.consolidatedDetailGrid;
        var store = grid.store;
        var item = grid.selection.getFirstSelected();

        parus.balance.refreshGrid(grid, "RN", store.getValue(grid.selection.getFirstSelected(), "RN"));


      }
    })

    action.execute();

    this.saveFormLastValues();

    return true;
  },

  saveFormLastValues: function() {

    if (!this.conditionFolder.attr("disabled")) {
      this._lastValues["conditionFolderRN"] = this._conditionFolderRN;
      this._lastValues["conditionFolder"] = this.conditionFolder.attr("value");
    };

    if (!this.reportType.attr("disabled")) this._lastValues["reportType"] = this.reportType.attr("value");

    this._lastValues["recalculationType"] = this.recalculationType.attr("value");

    this._lastValues["unCheckedReport"] = this.unCheckedReport.attr("checked");

    this._lastValues["multiLevel"] = this.multiLevel.attr("checked");
    this._lastValues["skipNonExisting"] = this.skipNonExisting.attr("checked");

    this._lastValues["disallowRecalculation"] = this.disallowRecalculation.attr("checked");

    this._lastValues["calculateValues"] = this.calculateValues.attr("checked");

    this._lastValues["stringFormulaType"] = this.stringFormulaType.attr("checked");
    this._lastValues["numberFormulaType"] = this.numberFormulaType.attr("checked");
    this._lastValues["dateFormulaType"] = this.dateFormulaType.attr("checked");

    this._lastValues["formIntermediateResults"] = this.formIntermediateResults.attr("checked");

    this._lastValues["beforeConsolidation"] = this.beforeConsolidation.attr("checked");
    this._lastValues["afterConsolidation"] = this.afterConsolidation.attr("checked");

    this._lastValues["userSize"] = this.userSize;
    parus.userdata.set(this.declaredClass, this._lastValues);
  },

  restoreFormLastValues: function() {
    this._lastValues = parus.userdata.get(this.declaredClass) || {};

    if (!this.conditionFolder.attr("disabled")) {
      this._conditionFolderRN = this._lastValues["conditionFolderRN"];
      this.conditionFolder.attr("value", this._lastValues["conditionFolder"]);
    }

    if (!this.reportType.attr("disabled")) this.reportType.attr("value", this._lastValues["reportType"]);
    this.recalculationType.attr("value", this._lastValues["recalculationType"]);
    this.unCheckedReport.attr("checked", this._lastValues["unCheckedReport"]);

    this.multiLevel.attr("checked", this._lastValues["multiLevel"]);
    this.skipNonExisting.attr("checked", this._lastValues["skipNonExisting"]);

    this.allowRecalculation.attr("checked", !this._lastValues["disallowRecalculation"]);
    this.disallowRecalculation.attr("checked", this._lastValues["disallowRecalculation"]);

    this.calculateValues.attr("checked", this._lastValues["calculateValues"]);

    this.recalculationChanged();

    this.formIntermediateResults.attr("checked", this._lastValues["formIntermediateResults"]);

    this.stringFormulaType.attr("checked", this._lastValues["stringFormulaType"]);
    this.numberFormulaType.attr("checked", this._lastValues["numberFormulaType"]);
    this.dateFormulaType.attr("checked", this._lastValues["dateFormulaType"]);

    this.beforeConsolidation.attr("checked", this._lastValues["beforeConsolidation"]);
    this.afterConsolidation.attr("checked", this._lastValues["afterConsolidation"]);
    this.userSize = this._lastValues["userSize"] || null;
  },

  setCheckBoxEnabled: function(checkBox, checkBoxLabel, enabled, checked) {
    if (checked != undefined) checkBox.attr("checked", checked);
    checkBox.attr("disabled", !enabled);
    if (enabled) checkBoxLabel.style.color = ""
    else checkBoxLabel.style.color = "#808080";
  },

  calculateValuesChanged: function() {
    var enabled = this.allowRecalculation.checked && this.calculateValues.checked;

    this.setCheckBoxEnabled(this.stringFormulaType, this.stringFormulaTypeText, enabled, this.calculateValues.checked);
    this.setCheckBoxEnabled(this.numberFormulaType, this.numberFormulaTypeText, enabled, this.calculateValues.checked);
    this.setCheckBoxEnabled(this.dateFormulaType, this.dateFormulaTypeText, enabled, this.calculateValues.checked);
  },

  recalculationChanged: function() {
    this.setCheckBoxEnabled(this.calculateValues, this.calculateValuesText, this.allowRecalculation.checked, true);
    this.setCheckBoxEnabled(this.formIntermediateResults, this.formIntermediateResultsText, !this.allowRecalculation.checked, false);

    this.calculateValuesChanged();
  }

});




dojo.declare("consolidationAction", null, {

  _checks: null,

  _ident: null,

  rn: null,

  showReportBefore: false,
  showReportAfter: false,

  conditionFolder: null,
  reportType: null,
  recalculationType: null,
  unCheckedReport: null,

  allowRecalculation: null,

  calculateValues: null,

  stringFormulaType: null,
  numberFormulaType: null,
  dateFormulaType: null,

  formIntermediateResults: null,

  multiLevel: null,
  skipNonExisting: null,

  onDone: function() {

  },

  showTempReports: function() {
    var response = parus.database.execute("prepareTempConsolidationReports", {
      CHECKS: this.rn.join(";"),
      KIND: this.reportType,
      CONDFOLDER: this.conditionFolder,
      UNCHECKED: this.unCheckedReport,
      BEFOREHAND: this.allowRecalculation,
      MULTI_SIGN: this.multiLevel,
      SKIP_NONEXISTS: this.skipNonExisting
    });

    var data = parus.parus8.rowNodes(response.documentElement.childNodes[0].childNodes[0].childNodes[0]);

    var dialog = new parus.balancePreparedConsolidationDialog({
      data: data,

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

        var checks = [];
        dojo.forEach(dialog.grid.selection.getSelected(), function(item) {
          checks.push(dialog.grid.store.getValue(item, "RN", ""));
        });

        this.consolidate(checks.join(";"));
        return true;
      })


    });


    dialog.show();

  },

  consolidate: function(checks) {

    parus.progressDialog.iterateOverArray("Формирование свода...", this.rn, dojo.hitch(this, function(item) {

      parus.database.execute("consolidateReport", {
        RN: item,
        CHECKS: checks,

        RESULT: this.formIntermediateResults,
        CALCTYPE: this.recalculationType,
        UNCHECKED: this.unCheckedReport,

        KIND: this.reportType,
        CONDFOLDER: this.conditionFolder,

        BEFOREHAND: this.allowRecalculation,
        CALCVALUES: this.calculateValues,
        CONS_SHOW_BEFORE: (this.showReportBefore ? "1" : "0"),

        CALC_STR: this.stringFormulaType,
        CALC_NUM: this.numberFormulaType,
        CALC_DATE: this.dateFormulaType,

        MULTI_SIGN: this.multiLevel,
        SKIP_NONEXISTS: this.skipNonExisting

      });

    }),

    dojo.hitch(this, function() {

      if (this.showReportAfter) parus.balance.balanceShowReportContents(parus.balance.consolidatedMasterGrid, true);

      this.onDone();


    }));
  },

  execute: function() {
    if (this.showReportBefore) this.showTempReports()
    else this.consolidate(null);

    return true;
  }

});