dojo.provide("parus.balanceReportAttachedDocumentsDialog");

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

dojo.require("dojox.grid.DataGrid");

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

dojo.require("parus.balanceReportAttachedDocumentActionDialog");

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

  rn: null,

  unitcode: "BalanceReports",

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


    this.docsGrid.attr("store", this.docsGridStore());
    this.docsGrid.setQuery(this.docsGrid.query);


    this.docsGridPopupMenu.bindDomNode(this.docsGrid.viewsNode);
    parus.balance._createActionsButton(this.docsGridPopupMenu, this.docsGridHeaderPane);

    var settings = parus.userdata.get(this.declaredClass);
    if (settings) {
      parus.gridSettingsDialog.mergeGridSettings(this.docsGrid, settings.gridSettings);
      parus.gridSettingsDialog.mergeColorConditions(this.docsGrid, settings.colorConditions);
      parus.gridSettingsDialog.mergeMenuSettings(this.docsGridPopupMenu, settings.actionSettings, settings.userProcsActions, settings.userReportsActions, settings.userAppsActions);
      parus.gridSettingsDialog.mergeFilterBar(this.docsGrid, settings.showFilterBar, settings.filterValues, settings.sortInfo);
    };

  },

  docsGridStore: function() {
    return parus.gridData({
      queryid: "AttachedDocuments",

      onGetConditions: dojo.hitch(this, function(store) {
        return {
          RN: this.rn,
          UNITCODE: this.unitcode
        };
      }),

      onComplete: dojo.hitch(this, function(store, items) {
        if ((items.length > 0) && !this.docsGrid.selection.getSelectedCount()) {
          this.docsGrid.selection.select(0);
          this.docsGrid.autoSelected = true;
        }
      })
    });
  },

  refresh: function() {
    var grid = this.docsGrid;
    var index = grid.selection.getSelectedIndex();
    var item = grid.getItem(index);

    parus.balance.refreshGrid(grid, "RN", grid.store.getValue(item, "RN"));
  },

  insertFile: function() {
    (new parus.balanceReportAttachedDocumentActionDialog({
      title: "Присоединенные документы: Добавление",
      grid: this.docsGrid,
      prn: this.rn,
      unitcode: this.unitcode
    })).show();
  },

  updateFile: function() {
    var grid = this.docsGrid;
    var index = grid.selection.getSelectedIndex();
    var item = grid.getItem(index);

    (new parus.balanceReportAttachedDocumentActionDialog({
      title: "Присоединенные документы: Исправление",
      grid: this.docsGrid,
      prn: this.rn,
      rn: grid.store.getValue(item, "RN"),
      docCode: grid.store.getValue(item, "CODE"),
      docType: grid.store.getValue(item, "FILE_TYPE_CODE"),
      catalog: grid.store.getValue(item, "CATALOG"),
      note: grid.store.getValue(item, "NOTE"),
      unitcode: this.unitcode
    })).show();
  },

  deleteFile: function() {
    (new parus.confirmationDialog({

      message: "Удалить запись (записи)?",

      onApply: dojo.hitch(this, function() {
        var grid = this.docsGrid;
        var item = grid.selection.getFirstSelected();
        for (var i = 0; i < grid.selection.getSelectedCount(); i++) {
          parus.database.execute("DeleteAttachedDocument", {
            RN: grid.store.getValue(item, "RN")
          });
          item = grid.selection.getNextSelected(item);
        };

        parus.balance.refreshGrid(grid, "RN", grid.store.getValue(grid.selection.getFirstSelected(), "RN"));

        return true;
      })
    })).show();
  },

  downloadFile: function() {
    var grid = this.docsGrid;
    var item = grid.selection.getFirstSelected();
    for (var i = 0; i < grid.selection.getSelectedCount(); i++) {
      parus.balance.downloadAttachedFile(grid.store.getValue(item, "RN"));
      item = grid.selection.getNextSelected(item);
    };
  },

  insertFiles: function() {

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

    if (!parus.parus8.optionValue("BalanceOnlineCacheContractorDictValues")) {
      parus.parus8.errorMessage("В настройках системы не задан тип присоединенного документа по умолчанию.");
      return;
    };

    var form = document.createElement("form");
    form.method = "POST";
    form.encoding = "multipart/form-data";
    form.action = parus.database.getLoadAttachedDocumentsUrl();

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

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

    var input = document.createElement("input");
    input.type = "file";
    input.name = "filedata";
    input.multiple = true;
    input.onchange = dojo.hitch(this, function() {

      if (!input.files.length) {
        document.body.removeChild(form);
        return;
      };

      var progressIndicator = new parus.progressDialog({
        message: "Загружаются файлы..."
      });
      progressIndicator.show();


      dojo.xhrGet({

        url: "../.system/session.xml?filedata=",
        handleAs: "xml",
        sync: false,
        preventCache: true,

        load: dojo.hitch(this, function(response) {

          dojo.io.iframe.send({
            method: "POST",
            form: form,
            handleAs: (dojo.isIE >= 10) ? "html" : "xml",

            handle: dojo.hitch(this, function(response, ioArgs) {
              document.body.removeChild(form);

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

              if (response.documentElement.nodeName == "error") {
                parus.parus8.errorMessage(parus.parus8.nodeField(response.documentElement, "message"));
                response = null;
              };

              progressIndicator.close();
              progressIndicator.destroyRecursive();

              this.refresh();

            })
          });

          return (response);

        })
      });

    });

    form.appendChild(input);

    document.body.appendChild(form);

    input.click();
  }

});