dojo.provide("parus.exportGridDialog");

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

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

dojo.require("parus.gridExtraRow");

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

  applyProgressLabel: "Экспорт таблицы",

  _lastValues: null,

  grid: null,

  onShow: function() {
    this._lastValues = parus.userdata.get(this.declaredClass) || {};
    this.userSize = this._lastValues["userSize"] || null;
    this.formatEdit.attr("value", this._lastValues["formatEdit"]);
    this.dataEdit.attr("value", this._lastValues["dataEdit"]);
    this.colorModeEdit.attr("value", this._lastValues["colorModeEdit"]);
    if (!parus.database.attributes.newoffice) this.formatEdit.removeOption("xlsx");
    if (parus.database.attributes.newoffice == "2") this.formatEdit.removeOption("xls");
  },

  onClose: function() {
    this._lastValues["formatEdit"] = this.formatEdit.attr("value");
    this._lastValues["dataEdit"] = this.dataEdit.attr("value");
    this._lastValues["colorModeEdit"] = this.colorModeEdit.attr("value");
    this._lastValues["userSize"] = this.userSize;
    parus.userdata.set(this.declaredClass, this._lastValues);
  },

  _itemToRow: function(item, testnode, rown) {

    var row = {};
    var rowColor = null;
    var cols = 0;

    dojo.forEach(this.grid.views.views[0].structure.cells[0], dojo.hitch(this, function(column) {
      if (!column.field) return;
      if (column.hidden) return;

      var value = null;
      var color = null;

      if (column._props.propRN) {
        value = parus._docPropsValueForGrid(parus.parus8.docPropValue(item, column._props.propRN), column._props.dataType, column._props.dataSubType);
      }
      else if (column._props.attrRN) {
        value = parus._docPropsValueForGrid(parus.parus8.docAttrValue(item, column._props.attrRN), column._props.dataType, column._props.dataSubType);
      }
      else {
        value = this.grid.store.getValue(item, column.field) || null;
        if (column.formatter) try {
          value = column.formatter(value, rown, column._props);
        } catch (e) {};
      }

      if (this.grid.colorConditions && this.grid.colorConditions.length) {


        var matched = "";
        var notmatched = "";
        var applyToRow = false;

        var checkCondition = function(condition, v) {

          if (condition.mask.match(/.*!.*/)) {
            notmatched = condition.color;
            applyToRow = condition.applyToRow;
          }

          if (condition.mask) dojo.forEach(condition.mask.split(";"), function(mask) {

            if (mask.substring(0, 1) == "!") {
              var matcher = ((mask == "!*") ? /^.+$/m : dojo.data.util.filter.patternToRegExp(mask.substring(1, mask.length), false));
              if (v.match(matcher)) {
                notmatched = "";
                applyToRow = false
              };
            }
            else {
              var matcher = ((mask == "*") ? /^.+$/m : dojo.data.util.filter.patternToRegExp(mask, false));
              if (v.match(matcher)) {
                matched = condition.color;
                applyToRow = condition.applyToRow;
              }
            }
          })
          else {
            var vn = dojo.number.parse(v),
                fn = dojo.number.parse(condition.fromValue),
                tn = dojo.number.parse(condition.toValue);
            if (!isNaN(vn)) {
              if (!isNaN(fn) && !isNaN(tn) && (vn >= fn) && (vn <= tn)) {
                matched = condition.color;
                applyToRow = condition.applyToRow;
              }
              else if (!isNaN(fn) && isNaN(tn) && (vn >= fn)) {
                matched = condition.color;
                applyToRow = condition.applyToRow;
              }
              else if (isNaN(fn) && !isNaN(tn) && (vn <= tn)) {
                matched = condition.color;
                applyToRow = condition.applyToRow;
              }
            };

            var pattern = {
              selector: "date",
              datePattern: "dd.MM.yyyy"
            };

            var vd = dojo.date.locale.parse(v, pattern),
                fd = dojo.date.locale.parse(condition.fromValue, pattern),
                td = dojo.date.locale.parse(condition.toValue, pattern);

            if (vd) {
              if (fd && td && (vd >= fd) && (vd <= td)) matched = condition.color;
              else if (fd && !td && (vd >= fd)) {
                matched = condition.color;
                applyToRow = condition.applyToRow;
              }
              else if (!fd && td && (vd <= td)) {
                matched = condition.color;
                applyToRow = condition.applyToRow;
              }
            };

          }

        };

        dojo.forEach(this.grid.colorConditions, function(condition) {

          if (matched || notmatched) return;

          if (condition.field == column.field) checkCondition(condition, value || "");
        });


        if (matched && !notmatched) {
          if (applyToRow) rowColor = matched;
          else color = matched;
        }
        else if (notmatched && !matched) {
          if (applyToRow) rowColor = matched;
          else color = notmatched;
        }
      }



      dojo.place("<span>" + (value || "") + "</span>", testnode, "only");
      row["f" + (cols++)] = {
        color: color,
        value: parus.parus8.getTextContent(testnode)
      };

    }));

    return {
      row: row,
      color: rowColor
    };


  },

  onApply: function() {

    var columns = {};

    var testnode = document.createElement("div");
    var cols = 0;

    dojo.forEach(this.grid.views.views[0].structure.cells[0], dojo.hitch(this, function(column, idx) {
      if (!column.field) return;
      if (column.hidden) return;
      dojo.place("<span>" + column.name + "</span>", testnode, "only");
      columns["f" + (cols++)] = {
        title: parus.parus8.getTextContent(testnode),
        dataType: (column.dataType || "0"),
        intPart: (column.intPart || column._props.intPart || "0"),
        fractPart: (column.fracPart || column._props.fracPart || "0")
      };
    }));

    var rows = {};
    var rcnt = 0;

    if (this.grid.extraRowObject) if (this.grid.extraRowObject.visible) {
      for (var i = 0; i < this.grid.extraRowObject.rowCount; i++) {

        var row = {};
        var cols = 0;

        dojo.forEach(this.grid.views.views[0].structure.cells[0], dojo.hitch(this, function(column) {
          if (!column.field) return;
          if (column.hidden) return;
          dojo.place("<span>" + (this.grid.onExtraRowValue(column, i)) + "</span>", testnode, "only");
          row["f" + (cols++)] = {
            color: null,
            value: parus.parus8.getTextContent(testnode)
          };
        }));

        rows["r" + (rcnt++)] = {
          row: row,
          color: null,
          bold: 1
        }
      }
    };

    if (this.dataEdit.attr("value") == "1") {
      var item = this.grid.selection.getFirstSelected();
      if (item) for (var i = 0; i < this.grid.selection.getSelectedCount(); i++) {
        rows["r" + (rcnt++)] = this._itemToRow(item, testnode, i);
        item = this.grid.selection.getNextSelected(item);
      };
    }
    else if (this.grid.store.forEach) {
      this.grid.store.forEach(dojo.hitch(this, function(store, item, idx) {
        rows["r" + (rcnt++)] = this._itemToRow(item, testnode, idx);
      }));
    }

    var colormode = this.colorModeEdit.attr("value");
    var format = this.formatEdit.attr("value");

    setTimeout(function() {

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

      var form = document.createElement("form");
      form.method = "POST";
      form.action = parus.database.getExportDataUrl(format);

      //if (/*!dojo.isChrome || */ (format == "html")) 
      if (!parus.parus8._embeddedMode) form.target = "_blank";

      var input = document.createElement("input");
      input.type = "hidden";
      input.name = "data";
      input.value = parus.xml.toXml({
        data: {
          colcnt: cols,
          rowcnt: rcnt,
          columns: columns,
          rows: rows
        }
      });
      form.appendChild(input);

      input = document.createElement("input");
      input.type = "hidden";
      input.name = "colormode";
      input.value = colormode;
      form.appendChild(input);

      document.body.appendChild(form);
      form.submit();
      document.body.removeChild(form);
    }, 500);

    return true;
  }

});