dojo.provide("parus.balanceCustomDownloadReportsDialog");

dojo.require("dojo.io.iframe");

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

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

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

  kind: null,

  _lastValues: null,

  applyProgressLabel: "Формируется выгрузка в пользовательском формате...",

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

  onClose: function() {
    this.saveFormLastValues();
  },

  formatCodeChanged: function() {

    var response = parus.database.execute("customDownloadFileNames", {
      BDATE: dojo.date.locale.format(this.reportDate.value, {
        selector: "date",
        datePattern: "dd.MM.yyyy"
      }),
      FORMAT: this.formatCode.value,
      CHARSET: this.encodingType.value
    });

    if (!response) return false;

    var node = parus.parus8.rowNodes(response)[0];
    this.fileNameEdit.attr("value", parus.parus8.nodeField(node, "FILENAME"));
    this.archiveNameEdit.attr("value", parus.parus8.nodeField(node, "ARCHNAME"));

  },

  onApply: function() {
    var showReport = this.showReport.value;

    var response = parus.database._xhr("customdownload.xml", null, {
      KIND: this.kind,
      BDATE: dojo.date.locale.format(this.reportDate.value, {
        selector: "date",
        datePattern: "dd.MM.yyyy"
      }),
      FORMAT: this.formatCode.value,
      CHARSET: this.encodingType.value,
      AGENT: this.agentCode.value,
      LOG_KIND: (showReport == "2" ? 1 : 0),
      FILENAME: this.fileNameEdit.value,
      ARCHNAME: this.archiveNameEdit.value
    });

    if (!response) return;

    var node = parus.parus8.rowNodes(response)[0];
    var result = parus.parus8.nodeField(node, "RESULT");
    var dataSize = parus.parus8.nodeField(node, "DATASIZE");

    var doDownload = function() {
      if (dataSize != "0") {
        if (result == "0") parus.parus8.errorMessage("Выгрузка завершена с наличием ошибок.");

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


        var form = document.createElement("form");
        form.method = "GET";
        form.action = parus.database.getCustomDownloadDataUrl();
        //if (!dojo.isChrome) form.target = "_blank";
        document.body.appendChild(form);
        form.submit();
        document.body.removeChild(form);

      }
      else parus.parus8.errorMessage("Файл выгрузки не сформирован.<br/>Выгрузка завершена с наличием ошибок.");

    };
    var node = parus.parus8.rowNodes(response)[0];
    if (showReport != "0") {

      if (parus.parus8._embeddedMode) {
        var id = ["customDownloadReport"].join("_");
        var textID = "T" + (+(new Date));
        var title = "Протокол выгрузки отчетов пользовательском формате";

        mill.session.setValue(textID, parus.parus8.nodeField(node, "clobLOG"), false);

        var url = dojo.moduleUrl("parus", "embeddedContent.html") + "?loggedUserHandler=" + parus.database.connected + "&params=" + parus.parus8.hexEncodeParams([textID, title, result, ""]);

        parus.embeddedMode.openTab((+(new Date)), title, url);
        doDownload();

      }
      else {

        var contentPane;

        var borderContainer = new dijit.layout.BorderContainer({
          design: "headline",
          gutters: false,
          "class": "balanceTemplateContentPane",
          style: "height:100%;width:100%;padding:0"
        });

        var headingContentPane = parus.balance._createHeadingPane("Протокол выгрузки отчетов пользовательском формате");


        borderContainer.addChild(headingContentPane);

        var templateGridPane = new dijit.layout.ContentPane({
          region: "center",
          content: parus.parus8.nodeField(node, "clobLOG"),
          onShow: function() {
            if (contentPane.controlButton)

            if (result == "0") dojo.query("*", contentPane.controlButton.containerNode).addClass("balanceModifiedHeader")
            else dojo.query("*", contentPane.controlButton.containerNode).removeClass("balanceModifiedHeader");

            doDownload();
          }

        });

        borderContainer.addChild(templateGridPane);

        contentPane = new dijit.layout.ContentPane({
          title: parus.balance.formatPageTitle("Протокол выгрузки отчетов <br/>в пользовательском формате"),
          closable: true,
          "class": "balanceTemplateContentPane" + (result == "0" ? " balanceModifiedHeader" : ""),
          onClose: dojo.hitch(this, function() {
            parus.balance.TabContainer.selectChild(this.kind ? parus.balance.consolidatedPage : parus.balance.primaryPage);
            return true;
          })
        });

        templateGridPane.parentPane = contentPane;

        contentPane.setContent(borderContainer);

        parus.balance.TabContainer.addChild(contentPane);
        parus.balance.TabContainer.selectChild(contentPane);
      }

    }
    else doDownload();

    return true;

  },

  saveFormLastValues: function() {

    this._lastValues["encodingType"] = this.encodingType.value;
    this._lastValues["reportDate"] =

    dojo.date.locale.format(this.reportDate.value, {
      selector: "date",
      datePattern: "dd.MM.yyyy"
    });

    this._lastValues["agentCode"] = this.agentCode.value;
    this._lastValues["formatCode"] = this.formatCode.value;
    this._lastValues["showReport"] = this.showReport.value;

    this._lastValues["fileNameEdit"] = this.fileNameEdit.value;
    this._lastValues["archiveNameEdit"] = this.archiveNameEdit.value;
    this._lastValues["userSize"] = this.userSize;

    parus.userdata.set(this.declaredClass, this._lastValues)
  },

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

    this.encodingType.attr("value", this._lastValues["encodingType"]);

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

    this.agentCode.attr("value", this._lastValues["agentCode"]);
    this.formatCode.attr("value", this._lastValues["formatCode"]);
    this.showReport.attr("value", this._lastValues["showReport"]);

    this.fileNameEdit.attr("value", this._lastValues["fileNameEdit"]);
    this.archiveNameEdit.attr("value", this._lastValues["archiveNameEdit"]);
    this.userSize = this._lastValues["userSize"] || null;


  }

});