dojo.provide("parus.balanceAdvReportCompareDialog");

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

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

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

  rn: null,

  _lastValues: null,

  _conditionFolderRN: null,

  _canCheckCriteria: true,

  applyProgressLabel: "Формируется протокол сравнения...",

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

    if (this.rn) {
      //      this.criteriaGroupBox.domNode.style.height = "90px";
      this.flagsGroupBox.domNode.style.display = "";
    };


    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;
      }
    });


    this.criteriaTreeView._createTreeNode = function(args) {
      return new parus.balanceAdvReportCompareCriteriaTreeNode(args);
    };

    this.criteriaTreeView.model = new parus.catalogTreeModel({
      queryid: "BalanceCompareReportRuleCriteriaHier",
      onGetConditions: dojo.hitch(this, function(model, parentNode) {
        return {
          "RULE_CODE": this.ruleEdit.value || parus.parus8.CLASS_EmptyData,
          "CRN": (parentNode ? model.getIdentity(parentNode) || "-1" : "!*")
        }
      })
    });
  },

  ruleEditChanged: function() {

    this.formEdit.attr("value", null);

    if (this.ruleEdit.value) {
      var response = parus.database.execute("FindBalanceCompareReportRule", {
        "RULE_CODE": this.ruleEdit.value
      });
      this.formEdit.attr("value", parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "FORM_CODE"));
      this._canCheckCriteria = (parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "CRITERIA_SIGN") == "1");
    };

    parus.catalogActions.refreshCatalogTree(this.criteriaTreeView);
    this.groupsEdit.attr("value", null);

  },

  onShow: function() {
    this.restoreFormLastValues();
  },

  saveFormLastValues: function() {
    this._lastValues = {};
    this._lastValues["conditionFolderRN"] = this._conditionFolderRN;
    this._lastValues["conditionFolder"] = this.conditionFolder.attr("value");
    this._lastValues["reportType"] = this.reportType.attr("value");
    this._lastValues["fromDate"] = parus.parus8.valueToExternalString(this.fromDateEdit.attr("value"));
    this._lastValues["toDate"] = parus.parus8.valueToExternalString(this.toDateEdit.attr("value"));
    this._lastValues["agentCode"] = this.agentCodeEdit.attr("value");
    this._lastValues["rule"] = this.ruleEdit.attr("value");
    this._lastValues["groups"] = this.groupsEdit.attr("value");
    this._lastValues["params"] = this.buildParams();
    this._lastValues["userSize"] = this.userSize;
    parus.userdata.set(this.declaredClass, this._lastValues);
  },

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

    this._conditionFolderRN = this._lastValues["conditionFolderRN"] || null;
    this.conditionFolder.attr("value", this._lastValues["conditionFolder"] || null);
    this.reportType.attr("value", this._lastValues["conditionFolder"] || 0);

    this.userSize = this._lastValues["userSize"] || null;

    this.fromDateEdit.attr("value", dojo.date.locale.parse(this._lastValues["fromDate"] || "", {
      selector: "date",
      datePattern: "dd.MM.yyyy"
    }));

    this.toDateEdit.attr("value", dojo.date.locale.parse(this._lastValues["toDate"] || "", {
      selector: "date",
      datePattern: "dd.MM.yyyy"
    }));

    this.agentCodeEdit.attr("value", this._lastValues["agentCode"] || null);

    this.ruleEdit.attr("value", this._lastValues["rule"] || null);

    setTimeout(dojo.hitch(this, function() {

      this.groupsEdit.attr("value", this._lastValues["groups"] || null);

    }), 300);

    this.criteriaTreeView.model.fetchAll(dojo.hitch(this, function() {

      var params = this._lastValues["params"];
      if (params) params = params["Conditions"];
      if (params) params = params["Criteria"];

      if (params) if (params.length) {
        var ids = [];
        dojo.forEach(params, function(param) {
          for (key in param)
          ids.push(param[key]);
        });

        setTimeout(dojo.hitch(this, function() {

          (function(node) {
            if (!node) return;
            node._checkBox.attr("checked", dojo.indexOf(ids, parus.parus8.nodeField(node.item, "ID")) != -1)
            dojo.forEach(node.getChildren() || [], arguments.callee);
          })(this.criteriaTreeView.rootNode);

        }), 300);

      };
    }));
  },

  onApply: function() {
    //overriden.
    this.saveFormLastValues();
    return true;
  },


  getSectionGroupsCondition: function() {
    return {
      "RULE_CODE": this.ruleEdit.value || parus.parus8.CLASS_EmptyData
    };
  },


  buildParams: function() {

    var criteria = [];

    this.criteriaTreeView.model.fetchAll();

    (function(node) {
      if (!node) return;
      if (node._checkBox.checked)
      //ВНИМАНИЕ! В теге - русская буква. Слава программистам Паруса!
      criteria.push({
        "Сriterion": parus.parus8.nodeField(node.item, "ID")
      });
      dojo.forEach(node.getChildren() || [], arguments.callee);
    })(this.criteriaTreeView.rootNode);

    if (!criteria.length) {
      parus.parus8.errorMessage("Не выбраны критерии сравнения.");
      throw new Error("Business error at " + this.declaredClass + ".");
    };

    return {
      "Conditions": {
        "SectionGroups": this.groupsEdit.value || "",
        "Criteria": criteria
      }
    };
  }
});


dojo.declare("parus.balanceAdvReportCompareCriteriaTreeNode", dijit._TreeNode, {

  _checkBox: null,

  buildRendering: function() {
    this.inherited(arguments);
    this._checkBox = new dijit.form.CheckBox({
      checked: parus.parus8.nodeField(this.item, "ISVALID") == "1",

      disabled: !this.tree.dialogObject._canCheckCriteria,

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

        var achecked = this._checkBox.checked;
        var nodes = [this];

        if (achecked) {
          var parent = this;
          while (parent) {
            var p = parent.getParent();
            if (p) nodes.push(parent);
            parent = p;
          };
        };

        var f = function(node) {
          if (node) {
            node._checkBox.attr("checked", achecked);
            dojo.forEach(node.getChildren(), f);
          }
        };

        dojo.forEach(nodes, f);

      })
    }, this.iconNode);
  },

  destroy: function() {
    if (this._checkBox) this._checkBox.destroyRecursive;
    this.inherited(arguments);
  },

  setSelected: function(selected) {
    dijit.setWaiState(this.labelNode, "selected", selected);
  }

});