dojo.provide("parus.templateDesignPane");

dojo.require("dojo.window");

dojo.require("dijit.Dialog");
dojo.require("dijit.form.Button");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.TabContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.Menu");
dojo.require("dijit.Tooltip");
dojo.require("dijit.TooltipDialog");

dojo.require("dijit.form.NumberTextBox");
dojo.require("dijit.form.DateTextBox");
dojo.require("dijit.form.ValidationTextBox");

dojo.require("parus.parus8");
dojo.require("parus.dialog");
dojo.require("parus.database");
dojo.require("parus.dictEdit");
dojo.require("parus.xml");
dojo.require("parus.progressDialog");
dojo.require("parus.balanceZoomDialog");

dojo.require("parus.sheet");
dojo.require("parus.templateUploadDialog");

dojo.require("parus.templateDesignColumns");

dojo.declare("parus.templateDesignPane", [dijit.layout.ContentPane], {

  content: dojo.cache("parus", "templateDesignPane.html"),

  "class": "balanceTemplateContentPaneContent",

  template: null,

  modified: false,

  headingContentPane: null,

  returnToPane: null,

  _progressIndicator: null,

  _loaded: false,

  templateSheet: null,

  infoSheet: null,

  _indexes: null,

  _tables: null,

  _loadedInfoXML: null,


  _setContent: function(data) {
    var r = this.inherited(arguments);
    r.then(dojo.hitch(this, function() {
      dojo.query("*[templateDesignRole]", this.containerNode).forEach(dojo.hitch(this, function(node) {
        this[node.getAttribute("templateDesignRole")] = dijit.byNode(node) || node;
      }));
      dojo.query("*[widgetId]", this.containerNode).forEach(dojo.hitch(this, function(node) {
        var widget = dijit.byNode(node);
        if (widget) widget.templateDesignPane = this;
      }));
    }));
    return r;
  },

  progressIndicate: function(message) {
    if (message) {
      if (this._progressIndicator) {
        this._progressIndicator.messageText.innerHTML = message;
      }
      else {
        this._progressIndicator = new parus.progressDialog({
          message: message
        });
        this._progressIndicator.show();
      }
    }
    else {
      if (this._progressIndicator) {
        this._progressIndicator.close();
        this._progressIndicator = null;
      };
    }
  },

  refreshTemplate: function() {
    dojo.query("[role='sheet']", this.domNode).forEach(dojo.hitch(this, function(node) {
      dijit.byNode(node).destroyRecursive();
    }));
    this.loadTemplate();
  },

  reload: function() {
    this.performConfirmation(

    dojo.hitch(this, function() {

      dojo.fadeOut({
        node: this.domNode,
        onEnd: dojo.hitch(this, function() {
          this.refreshTemplate();
        })
      }).play();

    }), true);

  },

  performConfirmation: function(action, canCancel) {
    if (this.modified) {
      (new parus.confirmationDialog({
        message: "Сохранить сделанные Вами изменения?",

        onShow: function() {
          if (canCancel) {
            this.cancelButton.domNode.style.display = "";
            this.noButton.onClick = dojo.hitch(this, function() {
              if (action) action();
              this.close();
            });
          }
        }

      })).show();

    }
    else action();
  },

  saveChanges: function(action) {

    this.performConfirmation(

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

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

        var input = document.createElement("input");
        input.type = "hidden";
        input.name = "template";
        input.value = this.template;
        form.appendChild(input);

        var input = document.createElement("input");
        input.type = "hidden";
        input.name = "DESIGN";
        input.value = "<root text=\"привет\"/>";
        form.appendChild(input);

        var input = document.createElement("input");
        input.type = "hidden";
        input.name = "OLDINFO";
        input.value = this._loadedInfoXML;
        form.appendChild(input);

        var input = document.createElement("input");
        input.type = "hidden";
        input.name = "INFO";
        input.value = this._buildInfoXML();
        form.appendChild(input);

        document.body.appendChild(form);

        dojo.io.iframe.send({

          method: "POST",
          form: form,
          handleAs: "xml",

          handle: dojo.hitch(this, function(response, ioArgs) {
            document.body.removeChild(form);
            this.progressIndicate();
            if (response.documentElement.nodeName == "error") return;
            if (action) action();

          })
        });



      }), 100);
    }), true);

  },

  downloadExcel: function() {

    this.performConfirmation(

    dojo.hitch(this, function() {
      setTimeout(dojo.hitch(this, function() {
        var form = document.createElement("form");
        form.method = "GET";
        form.action = parus.database.getDesignTemplateWorkBookUrl();

        var input = document.createElement("input");
        input.type = "hidden";
        input.name = "template";
        input.value = this.template;
        form.appendChild(input);

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

  },

  uploadExcel: function() {
    var dialog = new parus.templateUploadDialog({

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

        if (!dialog.validate()) return false;

        if (!dialog.fileData.value) return false;

        parus.parus8.registerAction();

        dialog.postForm.action = parus.database.getDesignTemplateUploadUrl();

        dialog.template.value = this.template;

        dialog.oldInfo.value = this._loadedInfoXML;

        dojo.io.iframe.send({

          method: "POST",
          form: dialog.postForm,
          handleAs: "xml",

          handle: dojo.hitch(this, function(response, ioArgs) {
            dialog.applied = true;
            dialog.close();
            this.refreshTemplate();
          })
        });

        return true;
      })

    });

    dialog.show();

  },

  createTemplatePopupMenu: function() {

    var menu = new dijit.Menu({
      "class": "balanceMenu",

      preAction: dojo.hitch(this, function() {
        if (this.editing) if (this.editing.cancelValue) this.editing.cancelValue();
      }),

      _openMyself: dojo.hitch(this, function(args) {
        if (this.editing) if (this.editing.cancelValue) this.editing.cancelValue();
        dijit.Menu.prototype._openMyself.apply(menu, arguments);
      })

    });

    menu.addChild(new dijit.MenuItem({
      label: "Сохранить изменения",
      defaultIcon: "PCfloppyCustomIcon",
      disabled: this.readonly,
      onClick: dojo.hitch(this, function() {
        var action = dojo.hitch(this, function() {
          parus.parus8.notificationMessage("Трафарет успешно сохранен.")
        });

        this.saveChanges(action)

      })
    }));

    menu.addChild(new dijit.MenuSeparator());


    menu.addChild(new dijit.MenuItem({
      label: "Столбцы...",
      //      defaultIcon: "",
      //      disabled: this.readonly,
      onClick: dojo.hitch(this, function() {


        (new parus.templateDesignColumns({})).show();

      })
    }));

    menu.addChild(new dijit.MenuItem({
      label: "Скачать рабочую книгу Excel...",
      defaultIcon: "PCDownCustomIcon",
      onClick: dojo.hitch(this, this.downloadExcel)
    }));

    menu.addChild(new dijit.MenuItem({
      label: "Загрузить рабочую книгу Excel...",
      defaultIcon: "PCUpCustomIcon",
      onClick: dojo.hitch(this, this.uploadExcel)
    }));


    menu.addChild(new dijit.MenuSeparator());

    menu.addChild(new dijit.MenuSeparator());
    menu.addChild(new dijit.MenuItem({
      label: "Обновить",
      defaultIcon: "PCisyncCustomIcon",
      onClick: dojo.hitch(this, this.reload)
    }));

    menu.addChild(new dijit.MenuSeparator());
    menu.addChild(new dijit.MenuItem({
      label: "Настройки...",
      onClick: dojo.hitch(this, function() {
        parus.balance.executeSettings(null, menu, this.declaredClass, null);
      })
    }));

    menu.startup();
    return menu;
  },

  onShow: function() {
    if (!this._loaded) this.loadTemplate();
    this._loaded = true;
  },

  _buildInfoXML: function() {
    var xml = ["<ROOT>"];

    xml.push("<TABLES>");
    dojo.forEach(this._tables, function(table) {
      xml.push("<T_" + table["RN"] + ">");
      xml.push("<POS>");
      xml.push("<COL>" + table["COL"] + "</COL>");
      xml.push("<ROW>" + table["ROW"] + "</ROW>");
      xml.push("<COL_COUNT>" + table["COLCNT"] + "</COL_COUNT>");
      xml.push("<ROW_COUNT>" + table["ROWCNT"] + "</ROW_COUNT>");
      xml.push("</POS>");
      xml.push("<TOTALS>");
      dojo.forEach(table.totals, function(total) {
        xml.push("<TT_" + total["RN"] + ">");
        xml.push("<POS>");
        xml.push("<COL>" + total["COL"] + "</COL>");
        xml.push("<ROW>" + total["ROW"] + "</ROW>");
        xml.push("<COL_COUNT>" + total["COLCNT"] + "</COL_COUNT>");
        xml.push("<ROW_COUNT>" + total["ROWCNT"] + "</ROW_COUNT>");
        xml.push("</POS>");
        xml.push("</TT_" + total["RN"] + ">");
      });
      xml.push("</TOTALS>");
      xml.push("<INDEXES>");
      dojo.forEach(table.indexes, function(index) {
        xml.push("<TID_" + index["RN"] + ">");
        xml.push("<POS>");
        xml.push("<COL>" + index["COL"] + "</COL>");
        xml.push("<ROW>" + index["ROW"] + "</ROW>");
        xml.push("</POS>");
        xml.push("</TID_" + index["RN"] + ">");
      });
      xml.push("</INDEXES>");
      xml.push("</T_" + table["RN"] + ">");
    });
    xml.push("</TABLES>");

    xml.push("<INDEXES>");
    dojo.forEach(this._indexes, function(index) {
      xml.push("<ID_" + index["RN"] + ">");
      xml.push("<POS>");
      xml.push("<COL>" + index["COL"] + "</COL>");
      xml.push("<ROW>" + index["ROW"] + "</ROW>");
      xml.push("</POS>");
      xml.push("</ID_" + index["RN"] + ">");
    });
    xml.push("</INDEXES>");

    xml.push("</ROOT>");
    return xml.join("");

  },

  loadTemplate: function() {

    this.progressIndicate("Трафарет готовится....");

    if (this.headingContentPane) {
      if (this.headingContentPane.actionsButton) this.headingContentPane.actionsButton.destroyRecursive();
      if (this.headingContentPane.toolbar) {
        this.headingContentPane.toolbar.destroyRecursive()
      }

      dojo.mixin(this.headingContentPane, {
        actionsButton: null,
        toolbar: null
      });

    };
    var templateJS;
    var templateInfo;
    var templateTablesInfo;
    var templateIndexesInfo;

    (new dojo.DeferredList([

    dojo.xhrGet({

      handleAs: "json",
      sync: false,
      headers: {
        "Disable-Basic-Auth": "yes"
      },
      preventCache: true,
      url: parus.database.getDesignTemplateUrl(this.template),

      load: function(response) {
        templateJS = response;
        console.log(templateJS);
      }
    }),

    parus.database.query("DesignTemplateInfo", {
      "TEMPLATE": this.template
    }, function(response) {
      templateInfo = parus.parus8.rowNodes(response)[0];
    }),

    parus.database.query("DesignTemplateTablesInfo", {
      "TEMPLATE": this.template
    }, function(response) {
      templateTablesInfo = parus.parus8.rowNodes(response);
    }),

    parus.database.query("DesignTemplateIndexesInfo", {
      "TEMPLATE": this.template
    }, function(response) {
      templateIndexesInfo = parus.parus8.rowNodes(response);
    })

    ])).addCallback(dojo.hitch(this, function() {


      dojo.query("[role='sheet']", this.domNode).forEach(dojo.hitch(this, function(node) {
        if (!this.templateSheet) this.templateSheet = new parus.sheet(templateJS._sheets[0] || {}, node)
        else if (!this.infoSheet) this.infoSheet = new parus.sheet(templateJS._sheets[1] || {}, node);
      }));

      this._indexes = [];
      this._tables = [];

      dojo.forEach(templateIndexesInfo, dojo.hitch(this, function(row) {
        this._indexes.push({
          "RN": parus.parus8.nodeField(row, "BALANCEINDEX"),
          "COL": parseInt(parus.parus8.nodeField(row, "COL")),
          "ROW": parseInt(parus.parus8.nodeField(row, "ROWN")),
          "CODE": parus.parus8.nodeField(row, "CODE"),
          "NAME": parus.parus8.nodeField(row, "NAME")
        });
        this.templateSheet.placeIndex(
        parseInt(parus.parus8.nodeField(row, "ROWN")), parseInt(parus.parus8.nodeField(row, "COL")), parus.parus8.nodeField(row, "BALANCEINDEX"), parus.parus8.nodeField(row, "CODE"));
      }));

      dojo.forEach(templateTablesInfo, dojo.hitch(this, function(row) {
        this.templateSheet.placeTable(
        parseInt(parus.parus8.nodeField(row, "ROWN")), parseInt(parus.parus8.nodeField(row, "COL")), parseInt(parus.parus8.nodeField(row, "COL_CNT")), parseInt(parus.parus8.nodeField(row, "ROWN_CNT")), parus.parus8.nodeField(row, "BLTABLES"), parus.parus8.nodeField(row, "NAME"));

        var indexes = [];
        dojo.forEach(parus.parus8.rowNodes(parus.parus8.nodeField(row, "XMLINDEXES")), dojo.hitch(this, function(row) {
          indexes.push({
            "RN": parus.parus8.nodeField(row, "TABLEIND"),
            "COL": parseInt(parus.parus8.nodeField(row, "COL")),
            "ROW": parseInt(parus.parus8.nodeField(row, "ROWN")),
            "CODE": parus.parus8.nodeField(row, "CODE"),
            "NAME": parus.parus8.nodeField(row, "NAME")
          });
          this.templateSheet.placeTableIndex(
          parseInt(parus.parus8.nodeField(row, "ROWN")), parseInt(parus.parus8.nodeField(row, "COL")), parus.parus8.nodeField(row, "TABLEIND"), parus.parus8.nodeField(row, "CODE"));
        }));

        var totals = []
        dojo.forEach(parus.parus8.rowNodes(parus.parus8.nodeField(row, "XMLTOTALS")), dojo.hitch(this, function(row) {
          totals.push({
            "RN": parus.parus8.nodeField(row, "TOTALKEY"),
            "COL": parseInt(parus.parus8.nodeField(row, "COL")),
            "ROW": parseInt(parus.parus8.nodeField(row, "ROWN")),
            "COLCNT": parseInt(parus.parus8.nodeField(row, "COL_CNT")),
            "ROWCNT": parseInt(parus.parus8.nodeField(row, "ROWN_CNT")),
            "NAME": parus.parus8.nodeField(row, "NAME")
          });
          this.templateSheet.placeTotal(
          parseInt(parus.parus8.nodeField(row, "ROWN")), parseInt(parus.parus8.nodeField(row, "COL")), parseInt(parus.parus8.nodeField(row, "COL_CNT")), parseInt(parus.parus8.nodeField(row, "ROWN_CNT")), parus.parus8.nodeField(row, "TOTALKEY"), parus.parus8.nodeField(row, "NAME"));
        }));

        this._tables.push({
          "RN": parus.parus8.nodeField(row, "BLTABLES"),
          "NAME": parus.parus8.nodeField(row, "NAME"),
          "COL": parseInt(parus.parus8.nodeField(row, "COL")),
          "ROW": parseInt(parus.parus8.nodeField(row, "ROWN")),
          "COLCNT": parseInt(parus.parus8.nodeField(row, "COL_CNT")),
          "ROWCNT": parseInt(parus.parus8.nodeField(row, "ROWN_CNT")),
          indexes: indexes,
          totals: totals
        });
      }));


      this._loadedInfoXML = this._buildInfoXML();

      this.templateSheet.buildRendering();

      console.log(this);

      /** ЗДЕСЬ!  **/


      var menu = this.createTemplatePopupMenu();
      parus.balance._createActionsButton(menu, this.headingContentPane);
      menu.bindDomNode(this.domNode);

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

      if (settings) {
        parus.gridSettingsDialog.mergeMenuSettings(menu, settings.actionSettings, settings.userProcsActions, settings.userReportsActions, settings.userAppsActions);
      }


      dojo.fadeIn({
        node: this.domNode,
        onBegin: dojo.hitch(this, function() {
          this._layoutChildren();
        }),
        onEnd: dojo.hitch(this, function() {
          this.progressIndicate();
          this.textCaptionNode.innerText = "Формула:";
        })
      }).play();

    }));

  },

  onModified: function() {
    //to be overriden
  },

  onTitleChanged: function() {
    //to be overriden
  },

  _confirmed: false,

  onClose: function() {


    if (this.editing) {
      if (!this.editing.postValue()) {
        if (this.editing.cancelValue) this.editing.cancelValue();
        else return false;
      }
    };

    var action = dojo.hitch(this, function() {
      this._confirmed = true;
      parus.balance.TabContainer.selectChild(parus.balance.formsPage, false);
      //      if (parus.balance.TabContainer) parus.balance.TabContainer.removeChild(this.parentPane);
    });

    if (this._confirmed) return true;

    if (!this.modified) {
      action();
      return false;
    }

    (new parus.confirmationDialog({
      message: "Вы закрываете вкладку с измененным трафаретом. <br/>Сохранить сделанные Вами изменения?",

      onShow: function() {
        this.cancelButton.domNode.style.display = "";
        this.noButton.onClick = dojo.hitch(this, function() {
          action();
          this.close();
        })
      }

    })).show();

    this._confirmed = false;
    return false;

  },

  _setTitleAttr: function(value) {
    this.inherited(arguments);
    if (this.autonomousMode) document.title = value;
    dojo.place("<span>" + value + "<span>", this.headingContentPane.containerNode.firstChild, "only");
    this.title = value;
    this.onTitleChanged();
  },

  showFormulasClick: function() {
    ///  this.textCaptionNode.innerText = "Формула любви:";
    dojo.forEach(this.templateSheet._cells, function(cell) {
      if (!cell.formulaText) dojo.addClass(cell.domNode, "templateDesignCellHidden");
    });

  },

  textAreaChanged: function() {
    setTimeout(dojo.hitch(this, function() {
      this._singleChild.layout();
      console.log("textAreaChanged");
    }), 100);
  }


});