dojo.provide("parus.userReportPane");

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.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.excelFileFormatDialog");
dojo.require("parus.excelColorModeDialog");

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

  userreport: null,

  rn: null,

  unitcode: null,

  paramValues: null,

  headingContentPane: null,

  zoom: 1,

  "class": "balanceTemplateContentPaneContent",

  ioMethod: function(args) {
    return dojo.xhrPost(args)
  },

  _progressIndicator: null,

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

    this._progressIndicator = new parus.progressDialog({
      message: "Формируется пользовательский отчет...."
    });

    this._progressIndicator.show();
    this.setIoArgs();
    this.href = parus.database.getUserReportUrl(this.userreport, "html");
  },


  setIoArgs: function() {
    dojo.mixin(this.ioArgs, {
      content: {
        query: parus.xml.toXml({

          query: [


          {
            rn: this.rn
          },
          {
            unitcode: this.unitcode
          },
          {
            userreport: this.userreport
          },
          {
            colormode: 0
          },
          {
            params: parus.xml.toXml({
              "PARAMS": this.paramValues
            })
          }

          ]

        })

      },
      headers: {
        "Disable-Basic-Auth": "yes"
      }
    });
  },

  changeZoom: function(dz) {
    if (dz > 0) this.zoom = this.zoom * 1.2
    else if (dz < 0) this.zoom = this.zoom / 1.2
    else this.zoom = 1;
    this._zoomChanged();
  },

  _zoomChanged: function() {

    for (var i = 0; i < this.domNode.childNodes.length; i++) {
      if (this.domNode.childNodes[i].style) dojo.style(this.domNode.childNodes[i], {
        zoom: (this.zoom * 100) + "%",
        MozTransform: "scale(" + this.zoom + ")",
        MozTransformOrigin: "0 0"
      });
    }
  },

  downloadExcel: function(extension, colormode) {

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

    var f = dojo.hitch(this, function(extension, colormode) {

      var form = document.createElement("form");
      form.method = "POST";
      form.action = parus.database.getUserReportUrl(this.userreport, extension);
      //if ( /*!dojo.isChrome ||*/ (extension == "html"))
      form.target = "_blank";

      var input = document.createElement("input");
      input.type = "hidden";
      input.name = "query";
      input.value = parus.xml.toXml({
        query: {
          rn: this.rn,
          unitcode: this.unitcode,
          userreport: this.userreport,
          colormode: colormode,
          params: parus.xml.toXml({
            "PARAMS": this.paramValues
          })
        }
      });

      form.appendChild(input);

      document.body.appendChild(form);
      form.submit();
      document.body.removeChild(form);

    });

    if (extension == "xls") {
      if (parus.database.attributes.newoffice == "1") {
        (new parus.excelFileFormatDialog({
          onApply: function() {
            f(this.formatEdit.value, colormode);
            return true;
          }
        })).show();
      } else if (parus.database.attributes.newoffice == "2") f("xlsx", colormode)
      else f("xls", colormode);
    }
    else if ((extension == "pdf" || extension == "html") && (colormode === undefined || colormode === null)) {
      (new parus.excelColorModeDialog({
        onApply: function() {
          f(extension, this.colorModeEdit.value);
          return true;
        }
      })).show();
    }
    else f(extension, colormode);

  },

  reload: function() {

    dojo.fadeOut({
      node: this.domNode,
      onEnd: dojo.hitch(this, function() {
        this._progressIndicator = new parus.progressDialog({
          message: "Формируется пользовательский отчет...."
        });
        this._progressIndicator.show();
        this.setIoArgs();
        this.refresh();
      })
    }).play();

  },

  /*  enqueue: function() {
   var response = parus.database.execute("enqueueUserReport", {
   RN: this.rn,
   UNITCODE: this.unitcode,
   USERREPORT: this.userreport,
   PARAMS: parus.xml.toXml({
   "PARAMS": this.paramValues
   })
   });
   if (!response) return;
   (new parus.confirmationDialog({
   message: "Пользовательский отчет поставлен в очередь. Получить отчет?",
   onApply: function() {
   setTimeout(function() {
   parus.parus8.enqueuedUserReport(parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "NQUEUE"));
   }, 100);
   return true;
   }
   })).show();
   },  */

  createPopupMenu: function() {
    var menu = new dijit.Menu({
      "class": "balanceMenu"
    });

    menu.addChild(new dijit.MenuItem({
      defaultIcon: "PCxlsCustomIcon",
      label: "Выгрузить в Excel...",
      onClick: dojo.hitch(this, this.downloadExcel, "xls", 0)
    }));
    menu.addChild(new dijit.MenuItem({
      label: "Выгрузить в формате PDF...",
      onClick: dojo.hitch(this, this.downloadExcel, "pdf", null)
    }));
    menu.addChild(new dijit.MenuItem({
      label: "Выгрузить в формате HTML...",
      onClick: dojo.hitch(this, this.downloadExcel, "html", null)
    }));

    /*    menu.addChild(new dijit.MenuSeparator());
     menu.addChild(new dijit.MenuItem({
     label: "В очередь",
     onClick: dojo.hitch(this, this.enqueue)
     })); */


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



    var zoomMenu = new dijit.Menu({
      "class": "balanceMenu"
    });

    zoomMenu.addChild(new dijit.MenuItem({
      label: "Увеличить",
      onClick: dojo.hitch(this, function() {
        this.changeZoom(1);
      })
    }));

    zoomMenu.addChild(new dijit.MenuItem({
      label: "Уменьшить",
      onClick: dojo.hitch(this, function() {
        this.changeZoom(-1);
      })
    }));

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


    zoomMenu.addChild(new dijit.MenuItem({
      label: "100%",
      onClick: dojo.hitch(this, function() {
        this.changeZoom(0);
      })
    }));


    zoomMenu.addChild(new dijit.MenuItem({
      label: "Задать...",
      onClick: dojo.hitch(this, function() {

        var dialog = new parus.balanceZoomDialog({
          onShow: dojo.hitch(this, function() {
            dialog.zoomEdit.attr("value", this.zoom * 100);
          }),

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

            this.zoom = dialog.zoomEdit.attr("value") / 100;
            this._zoomChanged();

            return true;

          })

        });

        dialog.show();

      })
    }));


    menu.addChild(new dijit.MenuSeparator());
    menu.addChild(new dijit.PopupMenuItem({
      label: "Масштаб",
      popup: zoomMenu
    }));


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

    menu.startup();
    return menu;
  },


  onLoad: function() {

    if (this._progressIndicator) this._progressIndicator.close();
    this._progressIndicator = null;

    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 evt = document.body.onload;
    dojo.query("script", this.containerNode).forEach(dojo.hitch(this, function(item) {
      var script = (!dojo.isIE || dojo.isIE >= 10) ? item.textContent : item.innerHTML
      dojo.mixin(this, dojo.fromJson(script));
    }));
    document.body.onload = evt;


    //    if (this.onInit) this.onInit();
    var nodes = dojo.query("canvas", this.containerNode);
    for (var i = nodes.length - 1; i >= 0; i--)
    this.drawCanvasText.call(this, nodes[i]);

    var nodes = dojo.query("*[rid=v]", this.containerNode);
    for (var i = nodes.length - 1; i >= 0; i--)
    this.checkToolTips.call(this, nodes[i]);

    var templateNodes = dojo.query("*[rid=w]", this.containerNode);

    if (templateNodes.length == 1) {

      var templateNode = templateNodes[0];
      var fixedRows = templateNode.getAttribute("fixedrows");
      var fixedCols = templateNode.getAttribute("fixedcols");
      var fixedRowsHeight = templateNode.getAttribute("fixedrowsheight");
      var fixedColsWidth = templateNode.getAttribute("fixedcolswidth");

      var sizes = dojo.getMarginBox(templateNode);

      var fixedColsPane, fixedRowsPane, fixedColsRowsPane;

      if (fixedCols) {
        fixedColsPane = document.createElement("div");

        dojo.style(fixedColsPane, {
          position: "absolute",
          top: "0px",
          left: "0px",
          width: fixedColsWidth + "px",
          height: sizes.h + "px",
          border: "1px solid transparent",
          zIndex: "20",
          overflow: "clip",
          background: "#FFFFFF"
        });

        dojo.query("[fixedcol]", this.containerNode).forEach(function(node) {
          fixedColsPane.appendChild(dojo.clone(node));
        });

        templateNode.parentNode.appendChild(fixedColsPane);

      }

      if (fixedRows) {
        fixedRowsPane = document.createElement("div");

        dojo.style(fixedRowsPane, {
          position: "absolute",
          top: "0px",
          left: "0px",
          width: sizes.w + "px",
          height: fixedRowsHeight + "px",
          border: "1px solid transparent",
          zIndex: "10",
          overflow: "clip",
          background: "#FFFFFF"
        });

        dojo.query("[fixedrow]", this.containerNode).forEach(function(node) {
          fixedRowsPane.appendChild(dojo.clone(node));
        });

        templateNode.parentNode.appendChild(fixedRowsPane);

      }

      if (fixedCols && fixedRows) {

        fixedColsRowsPane = document.createElement("div");

        dojo.style(fixedColsRowsPane, {
          position: "absolute",
          top: "0px",
          left: "0px",
          width: fixedColsWidth + "px",
          height: fixedRowsHeight + "px",
          border: "1px solid transparent",
          zIndex: "30",
          overflow: "clip",
          background: "#FFFFFF"
        });

        dojo.query("[fixedrow][fixedcol]", this.containerNode).forEach(function(node) {
          fixedColsRowsPane.appendChild(dojo.clone(node));
        });

        templateNode.parentNode.appendChild(fixedColsRowsPane);



      }

      if (fixedCols || fixedRows) dojo.connect(this.containerNode, "onscroll", this, function() {
        if (fixedColsPane) fixedColsPane.style.left = this.containerNode.scrollLeft + "px";
        if (fixedRowsPane) fixedRowsPane.style.top = this.containerNode.scrollTop + "px";
        if (fixedColsRowsPane) {
          fixedColsRowsPane.style.top = this.containerNode.scrollTop + "px";
          fixedColsRowsPane.style.left = this.containerNode.scrollLeft + "px";
        }

      });
    }

    var menu = this.createPopupMenu();
    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);

    this.onLoaded();

    dojo.fadeIn({
      node: this.domNode,
      onEnd: dojo.hitch(this, function() {
        if ( /* (this.paramValues["__useReportsQueue"] == "1") && */ (parus.database.attributes.useReportsQueue == "1")) {

          var response = parus.database.execute("enqueueUserReport", {
            RN: this.rn,
            UNITCODE: this.unitcode,
            USERREPORT: this.userreport,
            PARAMS: parus.xml.toXml({
              "PARAMS": this.paramValues
            })
          });

          if (!response) return;

          (new parus.confirmationDialog({
            message: "Пользовательский отчет поставлен в очередь. Получить отчет?",
            onApply: function() {
              setTimeout(function() {
                parus.parus8.enqueuedUserReport(parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "NQUEUE"));
              }, 100);
              return true;
            }
          })).show();



        }
      })

    }).play();
  },

  onClose: function() {
    if (this.returnToPane) if (this.returnToPane.domNode) parus.balance.TabContainer.selectChild(this.returnToPane);
    return true;
  },

  onLoaded: function() {
    //placeholder
  }

});

if (!parus) parus = {};

if (!parus.userReport) dojo.mixin(parus, {
  userReport: {}
});

dojo.mixin(parus.userReport, {

  startup: function() {

    var params = null;

    dojo.xhrGet({

      url: "../.system/session.xml",
      handleAs: "xml",
      sync: true,
      preventCache: true,

      load: function(response) {

        if (!dojo.isIE) response.normalize();

        var LNodes = response.documentElement.getElementsByTagName("*");

        for (var i = 0; i != LNodes.length; i++) {
          if (LNodes[i].nodeName == "params") params = LNodes[i].childNodes.item(0).nodeValue;
        }

        return (response);

      }
    });

    params = parus.parus8.hexDecodeParams(params);

    var userreport = params[0];
    var rn = params[1];
    var unitcode = params[2];
    var paramValues = {};
    var userreportTitle = params[3];

    for (var i = 4; i < params.length; i += 2) {
      paramValues[params[i]] = params[i + 1];
    }

    var contentPane;

    var borderContainer = new dijit.layout.BorderContainer({
      design: "headline",
      gutters: false,
      "class": "balanceTemplateContentPane",
      style: "height:100%;width:100%;padding:0;opacity:0;filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"
    }, dojo.place("<div></div>", dojo.body(), "last"));

    var headingContentPane = parus.balance._createHeadingPane("Пользовательский отчет \"" + userreportTitle + "\"");

    borderContainer.addChild(headingContentPane);

    var templateGridPane = new parus.userReportPane({
      region: "center",
      userreport: userreport,
      rn: rn,
      unitcode: unitcode,
      paramValues: paramValues,
      headingContentPane: headingContentPane,
      onLoaded: function() {
        loadingDiv.style.display = "none";
        dojo.fadeIn({
          node: borderContainer.domNode,
          duration: 300
        }).play();

      }

    });

    borderContainer.addChild(templateGridPane);
    borderContainer.startup();

  }

});