dojo.provide("parus.balanceReportDigitalSignaturesDialog");

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.digitalSignature");


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

  rn: null,

  unitCode: null,

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

    var structure = dojo.clone(this.signaturesGrid.structure);
    dojo.forEach(structure[0].cells[0], dojo.hitch(this, function(column) {
      if (column.field == "SIGN_STATE") column.formatter = this.formatSignState
      else if (column.field == "STRUCT_STATE") column.formatter = this.formatStructureState;
    }));

    this.signaturesGrid.attr("structure", structure);
    this.signaturesGrid.attr("store", this.signaturesGridStore());
    this.signaturesGrid.setQuery(this.signaturesGrid.query);

    this.signaturesPopupMenu.bindDomNode(this.signaturesGrid.viewsNode);
    parus.balance._createActionsButton(this.signaturesPopupMenu, this.signaturesGridHeaderPane);

    var settings = parus.userdata.get(this.declaredClass);
    if (settings) {
      parus.gridSettingsDialog.mergeGridSettings(this.signaturesGrid, settings.gridSettings);
      parus.gridSettingsDialog.mergeColorConditions(this.signaturesGrid, settings.colorConditions);
      parus.gridSettingsDialog.mergeMenuSettings(this.signaturesPopupMenu, settings.actionSettings, settings.userProcsActions, settings.userReportsActions, settings.userAppsActions);
    };

  },

  destroy: function() {
    this.inherited(arguments);
  },

  signaturesGridStore: function() {
    return parus.gridData({
      queryid: "DigitalSignatures",

      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.signaturesGrid.selection.getSelectedCount()) {
          this.signaturesGrid.selection.select(0);
          this.signaturesGrid.autoSelected = true;
        }
      })
    });
  },

  checkSign: function() {
    var grid = this.signaturesGrid;
    var store = grid.store;
    var item = grid.selection.getFirstSelected();

    var signInfo = [];

    for (var i = 0; i < grid.selection.getSelectedCount(); i++) {
      var rnValue = grid.store.getValue(item, "RN");
      var isSimpleSign = grid.store.getValue(item, "SIMPLESIGN") == "1";
      var response = parus.database.execute("VerifySign", {
        RN: rnValue,
        DOCUMENT: this.rn,
        UNITCODE: this.unitCode
      });

      if (response) {
        var isStructChanged = parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "STRUCT_CHANGED");

        var index = grid.store.findIndex("RN", rnValue);
        if (index >= 0) {
          var record = grid.getItem(index);

          if (isSimpleSign) {
            record.setAttribute("formatSignState", "Не проверялась");
          } else {
            signInfo.push({
              rn: rnValue,
              data: parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "clobDOC_DATA"),
              signedData: parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "clobSIGN"),
              structChanged: isStructChanged
            });
          }

          var state = "";
          switch (isStructChanged) {
          case "0":
            state = "Не изменена";
            break;
          case "1":
            state = "Изменена";
            break;
          case "2":
            state = "Не используется";
            break;
          }

          record.setAttribute("formatStructureState", state);
        }
      }

      item = grid.selection.getNextSelected(item);
    }
    grid.setQuery(grid.query);

    parus.digitalSignature.checkPlugin().then(
    dojo.hitch(this, function() {
      parus.digitalSignature.checkSign(signInfo).then(
      dojo.hitch(this, function(signedInfo) {
        dojo.forEach(signedInfo, function(item) {
          var index = grid.store.findIndex("RN", item.rn);
          if (index >= 0) {
            var record = grid.getItem(index);
            record.setAttribute("formatSignState", item.checkResult ? "Проверена" : item.checkError);
          }
        });
        grid.setQuery(grid.query);
      }), function(message) {
        this.close();
        parus.parus8.errorMessage(message);
      });
    }), function(message) {
      parus.parus8.errorMessage(message);
    });
  },

  formatSignState: function(data, rowIndex, column) {
    var item = column.grid.getItem(rowIndex);
    return item.getAttribute("formatSignState") || "Не определено";
  },

  formatStructureState: function(data, rowIndex, column) {
    var item = column.grid.getItem(rowIndex);
    return item.getAttribute("formatStructureState") || "Не определено";
  }

});