dojo.provide("parus.abonentSpecialActions");

dojo.require("parus.abonent");

if (!parus) parus = {};

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

dojo.mixin(parus.abonent, {

  _selectedReports: function() {

    var rns = [];
    dojo.query("*[widgetId]", parus.abonent.listView.domNode).forEach(function(node) {
      var widget = dijit.byNode(node);
      if (widget) if (widget.checked) rns.push(widget.reportRN);
    });

    return rns;

  },

  _selectedReport: function() {
    return this._selectedReports()[0];
  },

  balanceReportsClearValues: function() {

    var rns = parus.abonent._selectedReports();

    if (!rns.length) return;

    (new parus.confirmationDialog({

      message: "Очистить значения показателей?",

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

        dojo.forEach(rns, function(rn) {
          parus.database.execute("clearReportValues", {
            RN: rn
          });
        });
        parus.abonent.refresh();

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

  },

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

    var url = dojo.moduleUrl("parus", "checkreport.html") + "?loggedUserHandler=" + parus.database.connected + "&params=" + parus.parus8.hexEncodeParams([
    0, 0, 0, parus.abonent._selectedReports().join(";"), ""]);
    window.open(url, "_blank");
    parus.parus8.registerAction();

  },

  balanceReportSetReportAccepted: function() {

    dojo.forEach(parus.abonent._selectedReports(), function(rn) {
      parus.database.execute("acceptReport", {
        RN: rn,
        ACCEPT: 1
      });
    });

    parus.abonent.refresh();
  },

  balanceReportSetReportUnaccepted: function() {

    dojo.forEach(parus.abonent._selectedReports(), function(rn) {
      parus.database.execute("acceptReport", {
        RN: rn,
        ACCEPT: 2
      });
    });

    parus.abonent.refresh();

  },

  balanceReportChangeStatus: function() {

    var rns = [];

    var status = null;

    var badStatus = false;

    dojo.query("*[widgetId]", parus.abonent.listView.domNode).forEach(function(node) {
      var widget = dijit.byNode(node);
      if (widget) if (widget.checked) {
        status = status || (widget.reportStatus || "null");
        if ((widget.reportStatus || "null") != (status || "null")) badStatus = true;
        rns.push(widget.reportRN);
      }
    });

    if (!rns.length) return;

    if (badStatus) {
      parus.parus8.errorMessage("Статусы отмеченных отчетов должны совпадать.");
      return;
    }

    parus.database.query("BalanceReportStatuses", {
      "REPORT": rns.join(";")
    }, dojo.hitch(this, function(response) {

      var statuses = parus.parus8.rowNodes(response);
      if (statuses.length == 0) {
        parus.parus8.errorMessage("Отсутствуют статусы, доступные для перехода из текущего статуса отчета.");
        return;
      };

      var dialog = new parus.balanceStatusesDialog({

        statuses: statuses,

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

          parus.database.execute("reportSetStatus", {
            REPORT: rns.join(";"),
            STATUS: dialog.statusesGrid.store.getValue(dialog.statusesGrid.selection.getFirstSelected(), "RN", "")
          });

          parus.abonent.refresh();

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

    }));
  },

  balanceStatesHistory: function() {

    var dictionaryInfo = parus.dictionaries["BalanceReportsStatesHistory"];

    dojo.mixin(dictionaryInfo, {
      dictionary: dictionaryInfo,
      unitCode: dictionaryInfo.unitCode,
      hideCancel: true,
      gridConditions: {
        PRN: parus.abonent._selectedReport()
      },
      onApply: dojo.hitch(this, function(dialog) {
        return true;
      })
    });

    new parus.dictionaryDialog(dictionaryInfo).show();


  },

  balanceStatusesHistory: function() {

    var dictionaryInfo = parus.dictionaries["BalanceReportsStatusesHistory"];

    dojo.mixin(dictionaryInfo, {
      dictionary: dictionaryInfo,
      unitCode: dictionaryInfo.unitCode,
      hideCancel: true,
      gridConditions: {
        PRN: parus.abonent._selectedReport()
      },
      onApply: dojo.hitch(this, function(dialog) {
        return true;
      })
    });

    new parus.dictionaryDialog(dictionaryInfo).show();

  },

  balanceValuesHistory: function() {

    var dialog;

    var dictionaryInfo = parus.dictionaries["BalanceReportsValuesHistory"];

    var conditions = {};

    dojo.mixin(conditions, {
      PRN: parus.abonent._selectedReport()
    });


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

    menu.addChild(new dijit.MenuItem({
      label: "Исправить...",
      itemAction: true,
      defaultIcon: "PCdocumentCustomIcon",
      onClick: dojo.hitch(this, function() {
        var editDialog;
        editDialog = new parus.balanceValuesHistoryDialog({

          onShow: function() {

            var store = dialog.grid.store;
            var item = dialog.grid.selection.getFirstSelected();

            editDialog.userEdit.attr("value", store.getValue(item, "USERNAME"));
            editDialog.dateEdit.attr("value", store.getValue(item, "REPORT_DATE"));
            editDialog.noteEdit.attr("value", store.getValue(item, "NOTE"));
          },

          onApply: function() {

            var store = dialog.grid.store;
            var item = dialog.grid.selection.getFirstSelected();

            parus.database.execute("updateValuesHistory", {
              RN: store.getValue(item, "RN"),
              NOTE: editDialog.noteEdit.value
            });

            parus.balance.refreshGrid(dialog.grid);
            return true;
          }

        });

        editDialog.show();
      })
    }));


    menu.addChild(new dijit.MenuItem({
      label: "Удалить...",
      defaultIcon: "PCreduceCustomIcon",
      itemAction: true,
      onClick: dojo.hitch(this, function() {

        (new parus.confirmationDialog({

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

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

            var store = dialog.grid.store;
            var item = dialog.grid.selection.getFirstSelected();
            for (var i = 0; i < dialog.grid.selection.getSelectedCount(); i++) {
              parus.database.execute("deleteValuesHistory", {
                RN: store.getValue(item, "RN")
              });
              item = dialog.grid.selection.getNextSelected(item);
            };

            parus.balance.refreshGrid(dialog.grid);

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




      })
    }));

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

    var f = function(extension, colormode) {

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


      var form = document.createElement("form");
      form.method = "GET";
      form.action = parus.database.getHistoryUrl(extension);
      if ( /*!dojo.isChrome ||*/ (extension == "html")) form.target = "_blank";
      var input = document.createElement("input");
      input.type = "hidden";
      input.name = "rn";
      input.value = dialog.getValue();
      form.appendChild(input);

      if (colormode != undefined) {
        var input = document.createElement("input");
        input.type = "hidden";
        input.name = "colormode";
        input.value = colormode;
        form.appendChild(input);
      }

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

    };

    menu.addChild(new dijit.MenuItem({
      label: "Выгрузить в Excel...",
      defaultIcon: "PCxlsCustomIcon",
      itemAction: true,
      onClick: dojo.hitch(this, function() {
        f("xls");
      })
    }));

    menu.addChild(new dijit.MenuItem({
      label: "Выгрузить в формате PDF...",
      itemAction: true,
      onClick: dojo.hitch(this, function() {
        (new parus.excelColorModeDialog({
          onApply: function() {
            f("pdf", this.colorModeEdit.value);
            return true;
          }
        })).show();
      })
    }));

    menu.addChild(new dijit.MenuItem({
      label: "Выгрузить в формате HTML...",
      itemAction: true,
      onClick: dojo.hitch(this, function() {
        (new parus.excelColorModeDialog({
          onApply: function() {
            f("html", this.colorModeEdit.value);
            return true;
          }
        })).show();
      })
    }));

    menu.startup();

    dojo.mixin(dictionaryInfo, {
      dictionary: dictionaryInfo,
      unitCode: dictionaryInfo.unitCode,
      hideCancel: true,
      gridConditions: conditions,
      onApply: dojo.hitch(this, function(dialog) {
        return true;
      }),
      menu: menu
    });

    dialog = new parus.dictionaryDialog(dictionaryInfo);
    dialog.show();


  },

  balanceShowReportContents: function() {

    parus.balance.doShowReportContents(parus.abonent._selectedReports(), false);


  },

  balanceCheckAbsentReports: function() {


    var dialog = new parus.balanceCheckAbsentReportsDialog({
      kind: 0,
      onApply: function() {

        (new parus.balanceAbsentReportsDialog({
          kind: 0,

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

          agentGroup: dialog.agentsGroupEdit.value,

          onClose: dojo.hitch(this, function(dialog) {
            parus.abonent.refresh();

          })

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

    })

    dialog.show();
  },

  balanceReportsLoadReports: function() {
    var dialog = new parus.balanceLoadReportsDialog({

      kind: 0,
      onApply: dojo.hitch(this, function() {
        parus.abonent.refresh();
        return true;
      })

    });

    dialog.show();
  },

  downloadReport: function() {


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


    var reports = parus.abonent._selectedReports();

    if (!reports.length) return;

    var response = parus.database._xhr("report.xml", null, {
      REPORTS: reports.join(";")
    });

    if (response) {

      var form = document.createElement("form");
      form.method = "GET";
      form.action = parus.database.getReportXmlDataUrl();
      //if (!dojo.isChrome)
      form.target = "_blank";

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

    }

    parus.abonent.refresh();



  },

  balanceReportsCustomFormatDownloadReports: function() {
    (new parus.balanceCustomDownloadReportsDialog({
      kind: 0
    })).show();
  },

  balanceReportsUndoExport: function() {

    (new parus.confirmationDialog({

      message: "Отменить выгрузку для центра учета выделенных отчетов?",

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

        dojo.forEach(parus.abonent._selectedReports(), function(rn) {
          parus.database.execute("undoReportExport", {
            RN: rn
          });
        });

        parus.abonent.refresh();


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

  },

  downloadExcelReportPDF: function() {
    var rns = [];
    var editions = [];

    dojo.query("*[widgetId]", parus.abonent.listView.domNode).forEach(function(node) {
      var widget = dijit.byNode(node);
      if (widget) if (widget.checked) {
        rns.push(widget.reportRN);
        if (dojo.indexOf(editions, widget.editionRN) == -1) editions.push(widget.editionRN);
      }
    });

    if (!rns.length) return;

    if (rns.length == 1) parus.balance.downloadExcelWorkBook("BalanceReports", rns[0], null, null, "pdf");
    else parus.balance.downloadExcelWorkBook("BalanceReports", rns, "*", (editions.length > 1) ? "*" : null, "pdf");
  },

  downloadExcelReportHTML: function() {
    var rns = [];
    var editions = [];

    dojo.query("*[widgetId]", parus.abonent.listView.domNode).forEach(function(node) {
      var widget = dijit.byNode(node);
      if (widget) if (widget.checked) {
        rns.push(widget.reportRN);
        if (dojo.indexOf(editions, widget.editionRN) == -1) editions.push(widget.editionRN);
      }
    });

    if (!rns.length) return;

    if (rns.length == 1) parus.balance.downloadExcelWorkBook("BalanceReports", rns[0], null, null, "html");
    else parus.balance.downloadExcelWorkBook("BalanceReports", rns, "*", (editions.length > 1) ? "*" : null, "html");
  },

  balanceReportsExchangeExport: function() {

    var dialog = new parus.balanceReportsExchangeExportDialog({


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

        var rns = parus.abonent._selectedReports();

        var response = parus.database.execute("BalanceReportExchangeExport", {
          RN: rns.join(";"),
          CODE: dialog.exchangeKind.value,
          JRNL_SIGN: dialog.useJournal.attr("checked") ? "1" : "0",
          VERSIONNUMBER: dialog.versionNumber.value || "",
          PERIOD: dialog.periodEdit.value || "",
          LOGGING: dialog.reportTypeEdit.attr("value"),
          LOG_KIND: dialog.reportEdit.value || "",
          ARCH_KIND: dialog.archiveEdit.value || "",
          ARCH_NAME: dialog.archiveNameEdit.value || "",
          JOURNAL_CATALOG: dialog.journalCatalog.value || ""
        });

        if (!response) return false;

        var node = parus.parus8.rowNodes(response)[0];

        var message = [parus.parus8.nodeField(node, "MESSAGE"), "<br/>"];
        var files = (parus.parus8.nodeField(node, "clobFILES") || "").split(";") || [];
        var ident = parus.parus8.nodeField(node, "IDENT");

        var header = false;

        dojo.forEach(files, function(file) {

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


          if (file) {
            if (!header) {
              message.push("<br/>Файлы для скачивания:<br/>");

              header = true;
            };
            var f = file.split("|");
            message.push("<a target=\"_blank\" href=\"" + parus.database.getBufferUrl(f[0]) + "\">" + f[1] + "</a><br/>");
          }
        });

        setTimeout(function() {
          parus.parus8.notificationMessage(message.join(""),

          function() {
            parus.database.execute("clearFileBuffer", {
              IDENT: ident
            });
          }

          );
        }, 100);

        return true;
      })

    });

    dialog.show();

  },

  balanceReportsExchangeImport: function() {

    var dlg;

    var doit = function(params, rns, ident) {
      dojo.mixin(params, {
        RN: rns,
        IDENT: ident
      });

      var response = parus.database._xhr("exchangeimport.xml", null, params);

      if (!response) return;

      var node = parus.parus8.rowNodes(response)[0];

      setTimeout(function() {
        var message = [parus.parus8.nodeField(node, "MESSAGE")];

        if (parus.parus8.nodeField(node, "HASLOG") == "1") {
          message.push("<br/>");
          message.push("<br/>");
          message.push("<a href=\"" + parus.database.getExchangeImportLogUrl() + "\">Скачать протокол загрузки</a>");
        }

        parus.parus8.notificationMessage(message.join(""));
        parus.abonent.refresh();

      }, 100);
    };

    dlg = new parus.balanceReportsExchangeImportDialog({

      onShow: function() {
        dlg.restoreFormLastValues();
        /*        var path = catalogTree.path;
         dlg.reportsCatalog.attr("value", catalogTree.model.getLabel(path[path.length - 1])); */

        setTimeout(function() {
          dijit.hideTooltip(dlg.fileData);
        }, 10);

      },

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

        var params = {
          CODE: dlg.exchangeKind.value,
          JRNL_SIGN: dlg.useJournal.attr("checked") ? "1" : "0",
          REPORTS_CATALOG: dlg.reportsCatalog.value,
          KIND: consolidated,
          BDATE: dlg.reportDate.attr("value") ? dojo.date.locale.format(dlg.reportDate.attr("value"), {
            selector: "date",
            datePattern: "dd.MM.yyyy"
          }) : "",
          AGENT: dlg.agentCode.attr("value"),
          LOGGING: dlg.reportTypeEdit.attr("value"),
          LOG_KIND: dlg.reportEdit.value || "",
          RELOAD: dlg.canOverWrite.attr("value") || "2",
          RECALC: dlg.recalcReports.checked ? "1" : "0",
          JRNL_SHOW: dlg.showJournal.checked ? "1" : "0",
          JOURNAL_CATALOG: dlg.journalCatalog.value || ""
        };

        var showJournalChecked = dlg.showJournal.checked;

        var progressIndicator = new parus.progressDialog({
          message: "Обмен отчетностью. Загрузка."
        });

        var performDoIt = function(ident) {

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

          if (showJournalChecked) {

            var dicDialog = new parus.balanceReportsExchangeJournalDialog({

              applyProgressLabel: "Обмен отчетностью. Загрузка.",

              kind: consolidated,

              catalog_name: dlg.journalCatalog.value || "*",

              onApply: function() {
                var store = dicDialog.grid.store;
                var item = dicDialog.grid.selection.getFirstSelected();
                var rns = [];
                for (var i = 0; i < dicDialog.grid.selection.getSelectedCount(); i++) {
                  rns.push(store.getValue(item, "RN"));
                  item = dicDialog.grid.selection.getNextSelected(item);
                };
                doit(params, rns.join(";") || "!*", ident);
                return true;
              }
            });

            dicDialog.show();

          }
          else doit(params, "!*", ident);
        };

        var files = dojo.filter(dlg._files, function(f) {
          return !!f.value;
        });

        progressIndicator.show();

        if (files.length) {
          var i = files.length - 1;
          var ident = null;
          parus.database.toBuffer(files[i], "clob", ident, function(r) {
            ident = ident || r;
            i--;
            if (i >= 0) parus.database.toBuffer(files[i], "clob", ident, arguments.callee)
            else performDoIt(ident);
          });
        }
        else performDoIt(null);

        return true;
      })

    });

    dlg.show();
  },

  _userApplication: function(rns, unitcode, userapp, groupRecords) {


    var paramsDialog = new parus.balanceUserProcParamsDialog({

      userproc: userapp,

      queryid: "userAppParams",

      title: "Параметры пользовательского приложения",

      onApply: function() {

        if (groupRecords) {

          parus.balance.executeUserApplication(userapp, rns.join(";"), unitcode, paramsDialog.paramValues(), null, null, null, function() {
            parus.abonent.refresh();

          });

        } else if (!rns.length) {

          parus.balance.executeUserApplication(userapp, null, unitcode, paramsDialog.paramValues(), null, null, null, function() {
            parus.abonent.refresh();
          });

        }
        else {

          dojo.forEach(rns, function(rn, idx) {
            parus.balance.executeUserApplication(userapp, rn, unitcode, paramsDialog.paramValues(), null, null, null, (idx == (rns.length - 1)) ?
            function() {
              parus.abonent.refresh();
            } : null);
          });

        };

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

  userApplications: function() {


    var dialog = new parus.balanceUserProcsDialog({
      unitcode: "BalanceReports",

      queryid: "userApps",

      title: "Выбор пользовательского приложения",

      onApply: function() {


        var userapp;
        var groupRecords = false;

        dojo.forEach(dialog.userProcsGrid.selection.getSelected(), function(item) {
          userapp = dialog.userProcsGrid.store.getValue(item, "RN", "");
          groupRecords = (dialog.userProcsGrid.store.getValue(item, "GROUP_RECORDS", "") != "0");
        });

        if (!userapp) return false;

        parus.abonent._userApplication(parus.abonent._selectedReports(), dialog.unitcode, userapp, groupRecords);

        return true;
      }
    });

    dialog.show();
  },

  _userProcedure: function(rns, unitcode, userproc, confirmText, perRecord, perSelection) {

    var execute = dojo.hitch(this, function() {

      var paramsDialog = new parus.balanceUserProcParamsDialog({

        useSavedValues: parus.parus8.optionValue("StoreUserProcsParams") != "0",

        userproc: userproc,

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

          if (perSelection) {
            parus.balance.executeUserProc(userproc, rns.join(";"), unitcode, paramsDialog.paramValues());

          } else if (perRecord) {
            if (!rns.length) {
              parus.parus8.errorMessage("Регистрационный номер записи не определен.");
              return true;
            }
            dojo.forEach(rns, function(rn) {
              parus.balance.executeUserProc(userproc, rn, unitcode, paramsDialog.paramValues());
            });
          }
          else parus.balance.executeUserProc(userproc, null, unitcode, paramsDialog.paramValues());

          parus.abonent.refresh();

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

    });
    if (confirmText) {
      (new parus.confirmationDialog({
        message: confirmText,
        onApply: function() {
          execute();
          return true;
        }
      })).show();
    }
    else execute();
  },

  userProcedures: function() {

    var dialog = new parus.balanceUserProcsDialog({
      unitcode: "BalanceReports",

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

        var userproc;
        var confirmText = "";
        var perRecord = false;
        var perSelection = false;

        dojo.forEach(dialog.userProcsGrid.selection.getSelected(), function(item) {
          userproc = dialog.userProcsGrid.store.getValue(item, "RN", "");
          confirmText = dialog.userProcsGrid.store.getValue(item, "CONFIRM_TEXT", "");
          perRecord = (dialog.userProcsGrid.store.getValue(item, "PERRECORD", "") != "0");
          perSelection = (dialog.userProcsGrid.store.getValue(item, "PERSELECTION", "") != "0");
        });

        if (!userproc) return false;
        parus.abonent._userProcedure(parus.abonent._selectedReports(), "BalanceReports", userproc, confirmText, perRecord, perSelection);
        return true;
      })
    });

    dialog.show();

  },

  _userReport: function(rns, unitcode, userrep, userreptitle, userreporttype) {


    var paramsDialog = new parus.balanceUserReportParamsDialog({
      userproc: userrep,

      unitcode: unitcode,

      userreporttype: userreporttype,

      rns: rns.join(";"),

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

        if (userreporttype == "4") parus.balance.downloadUserReport(userrep, rns.join(";"), unitcode, dojo.clone(paramsDialog.paramValues()), userreptitle);
        else parus.balance.executeUserReport(userrep, rns.join(";"), unitcode, dojo.clone(paramsDialog.paramValues()), userreptitle);

        return true;
      })

    });
    paramsDialog.show();

  },


  userReports: function() {

    var dialog = new parus.balanceUserProcsDialog({
      unitcode: "BalanceReports",

      queryid: "userReports",

      title: "Выбор пользовательского отчета",

      onApply: function() {

        var userrep;
        var userreptitle = "";
        var userreporttype = "1";

        dojo.forEach(dialog.userProcsGrid.selection.getSelected(), function(item) {
          userrep = dialog.userProcsGrid.store.getValue(item, "RN", "");
          userreptitle = dialog.userProcsGrid.store.getValue(item, "NAME", "");
          userreporttype = dialog.userProcsGrid.store.getValue(item, "REPORT_TYPE", "1");
        });

        if (!userrep) return false;
        parus.abonent._userReport(parus.abonent._selectedReports(), "BalanceReports", userrep, userreptitle, userreporttype);

        return true;

      }
    });

    dialog.show();



  },

  userExternalAccounts: function() {
    parus.balance.userExternalAccounts();
  },

  balanceReportsDigitalSignatures: function() {
    var dialog = new parus.balanceReportDigitalSignaturesDialog({
      rn: parus.abonent._selectedReport(),
      unitCode: "BalanceReports"
    });
    dialog.show();
  },

  balanceReportsSign: function() {


    var rnValues = parus.abonent._selectedReports();

    if (!rnValues.length) return;

    var dialog = new parus.signDialog({
      rn: rnValues,
      unitCode: "BalanceReports",

      onApply: function() {
        var isSimpleSign = dialog.getIsSimpleSign();
        var note = dialog.getNote();
        var issuer = dialog.getIssuedBy();
        var owner = dialog.getIssuedTo();
        var validFrom = dialog.getValidFrom();
        var validTo = dialog.getValidTo();
        var serialNumber = dialog.getSerialNumber();
        var thumbprint = dialog.getThumbprint();
        var thumbprintToSave = dialog.isUserCertificatesUsed ? thumbprint : null;

        var signInfo = [];
        dojo.forEach(rnValues, function(rn) {
          var response = isSimpleSign ? null : parus.database.execute("GetSignData", {
            RN: rn,
            UNITCODE: "BalanceReports"
          });

          if (response || isSimpleSign) signInfo.push({
            rn: rn,
            data: isSimpleSign ? null : parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "clobDOC_DATA"),
            signedData: null
          });
        });

        var saveSign = function() {
          dojo.forEach(signInfo, function(item) {
            if (item.signedData || isSimpleSign) parus.database.execute("SaveSign", {
              RN: item.rn,
              UNITCODE: "BalanceReports",
              SIMPLESIGN: isSimpleSign ? "1" : "0",
              clobSIGN: item.signedData,
              NOTE: note,
              ISSUER: issuer,
              OWNER: owner,
              VALID_FROM: validFrom,
              VALID_TO: validTo,
              SERIALNUMBER: serialNumber,
              THUMBPRINT: thumbprint,
              THUMBPRINT_TO_SAVE: thumbprintToSave
            });
          });

          parus.abonent.refresh();
        }

        if (isSimpleSign) saveSign();
        else parus.digitalSignature.signData(signInfo, thumbprint).then(
        saveSign, function(message) {
          parus.parus8.errorMessage(message);
        });

        return true;
      }
    });

    dialog.show();

  },

  balanceReportsRemoveSign: function() {

    (new parus.confirmationDialog({

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

      onApply: dojo.hitch(this, function() {
        dojo.forEach(parus.abonent._selectedReports(), function(rn) {
          parus.database.execute("DeleteSign", {
            RN: rn,
            UNITCODE: "BalanceReports"
          });
        });

        parus.abonent.refresh();

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


  },

  exportToFile: function() {

    var reports = parus.abonent._selectedReports();

    if (!reports.length) return;

    var dialog = new parus.balanceReportsFileExportDialog({

      onApply: function() {

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


        var response = parus.database.execute("FindUserProcedure", {
          CODE: dialog.userProcEdit.value
        });

        if (!response) return false;

        var paramsDialog = new parus.balanceUserProcParamsDialog({
          useSavedValues: parus.parus8.optionValue("StoreUserProcsParams") != "0",
          userproc: parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "NRN"),
          onApply: dojo.hitch(this, function() {
            parus.database._xhr("fileexport.xml", null, {
              RN: reports.join(";"),
              USERPROC: paramsDialog.userproc,
              UNITCODE: "BalanceReports",
              PARAMS: parus.xml.toXml({
                "PARAMS": {
                  "PARAMS": paramsDialog.paramValues()
                }
              })
            },

            function(response) {
              if (response.documentElement.nodeName == "error") return;

              setTimeout(function() {

                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);
              }, 1000);
            });
            return true;
          })
        });
        paramsDialog.show();

        return true;
      }

    });

    dialog.show();
  },

  importFromFile: function() {

    var dialog = new parus.balanceReportsFileImportDialog({
      onApply: dojo.hitch(this, function() {
        parus.abonent.refresh();
        return true;
      })
    });

    dialog.show();

  },

  exportToSignedFile: function() {


    var reports = parus.abonent._selectedReports();

    if (!reports.length) return;

    var dialog = new parus.balanceReportsFileExportDialog({

      onApply: function() {

        var response = parus.database.execute("FindUserProcedure", {
          CODE: dialog.userProcEdit.value
        });

        if (!response) return false;

        var paramsDialog = new parus.balanceUserProcParamsDialog({

          useSavedValues: parus.parus8.optionValue("StoreUserProcsParams") != "0",

          userproc: parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "NRN"),

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

            var paramValues = parus.xml.toXml({
              PARAMS: {
                PARAMS: paramsDialog.paramValues()
              }
            });

            var signDialog = new parus.signDialog({
              showNote: false,
              allowSimpleSign: false,
              checkPluginVersion: true,
              requiredVersion: {
                major: 1,
                minor: 5,
                build: 1500
              },

              rn: reports,
              unitCode: unitCode,

              onApply: dojo.hitch(this, function() {
                var signInfo = [];
                var signTemplate;

                var template = parus.parus8.getXMLReportSignTemplateName(signDialog.getGOSTVersion(), signDialog.getGOSTKeySize());
                if (template.length == 0) {
                  parus.parus8.errorMessage("Неподдерживаемая версия ГОСТ алгоритма в выбранном сертификате: " + signDialog.getGOSTVersion() + " (" + signDialog.getGOSTKeySize() + ")");
                  return true;
                }

                dojo.xhrGet({
                  sync: true,
                  handleAs: "xml",
                  url: "../parusjs/" + template,
                  load: dojo.hitch(this, function(response) {
                    signTemplate = response;
                    return response;
                  })
                });

                var errorText;

                dojo.forEach(reports, function(rn) {

                  var response = parus.database._xhr("fileexport.xml", null, {
                    RN: rn,
                    USERPROC: paramsDialog.userproc,
                    UNITCODE: "BalanceReports",
                    PARAMS: paramValues
                  });

                  if (response.documentElement.nodeName == "error") return;

                  dojo.xhrGet({
                    sync: true,

                    handleAs: "xml",
                    url: parus.database.getCustomDownloadDataUrl(),

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

                      var responseFileName = "";
                      dojo.forEach(ioargs.xhr.getResponseHeader("Content-Disposition").split(";"), function(item) {
                        if (item.indexOf("filename=") >= 0) {
                          responseFileName = dojo.string.trim(item.split("=")[1]);
                          responseFileName = responseFileName.substr(1, responseFileName.length - 2);
                        };
                      });

                      response.documentElement.appendChild(signTemplate.documentElement);

                      var reportData = (dojo.isIE <= 9) ? response.xml : (new XMLSerializer()).serializeToString(response);
                      reportData = dojo.trim(reportData.replace(/\>\s+\</g, function(match) {
                        return match.replace(/\s+/g, "");
                      }));

                      signInfo.push({
                        rn: rn,
                        fileName: responseFileName,
                        data: reportData
                      });

                      return response;
                    }),

                    error: function(e) {
                      if (!errorText) errorText = "Ошибка получения данных. <br/>Вероятно, произошел сетевой сбой, или сервер стал недоступен. <br/>Попробуйте обновить страницу в браузере и перевойти в приложение.";
                      return e;
                    }
                  });

                });

                if (errorText) {
                  parus.parus8.errorMessage(errorText);
                  return true;
                }

                parus.digitalSignature.signXMLData(signInfo, signDialog.getThumbprint(), true).then(
                dojo.hitch(this, function() {
                  dojo.forEach(signInfo, function(item) {
                    if (item.signedData) {

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

                      var form = document.createElement("form");
                      form.method = "POST";
                      form.action = parus.database.getDownloadSignedReportPackageUrl();
                      //if (!dojo.isChrome)
                      form.target = "_blank";

                      var appendParam = function(name, value) {
                        var input = document.createElement("input");
                        input.type = "hidden";
                        input.name = name;
                        input.value = value;
                        form.appendChild(input);
                      };

                      appendParam("unitcode", "BalanceReports");
                      appendParam("reports", item.rn);
                      appendParam("fileName", item.fileName);
                      appendParam("fileData", item.signedData);
                      appendParam("params", paramValues);

                      document.body.appendChild(form);
                      form.submit();
                      document.body.removeChild(form);
                    }
                  });
                }), function(message) {
                  parus.parus8.errorMessage(message);
                });

                return true;
              })
            });

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

        paramsDialog.show();
        return true;
      }

    });

    dialog.show();
  },

  _selectedSubReports: function() {

    var rns = [];

    dojo.query("*[widgetId]", parus.abonent.subreportsPopup.dataContainer.containerNode).forEach(function(node) {
      var widget = dijit.byNode(node);
      if (widget) {
        if (widget.subreportRN && widget.checked) rns.push(widget.subreportRN);
      }
    });

    return rns;

  },

  _selectedSubReport: function() {
    return parus.abonent._selectedSubReports()[0];
  },

  _selectedSubReportReport: function() {
    return parus.abonent.subreportsPopup.tile.reportRN;
  },

  balanceSubReportsClearValues: function() {
    parus.abonent.subreportsPopup.inDialog = true;

    (new parus.confirmationDialog({

      message: "Очистить значения показателей?",

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


        dojo.forEach(parus.abonent._selectedSubReports(), function(rn) {
          parus.database.execute("clearSubReportValues", {
            RN: rn
          });
        });

        parus.abonent.subreportsPopup._loadSubreports();

        return true;
      }),

      onClose: function() {

        parus.abonent.subreportsPopup.inDialog = false;
      }

    })).show();
  },

  balanceCheckSubReportProtocol: function() {

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

    var url = dojo.moduleUrl("parus", "checkreport.html") + "?loggedUserHandler=" + parus.database.connected + "&params=" + parus.parus8.hexEncodeParams([
    0, 1, 0, parus.abonent._selectedSubReports().join(";"), ""]);
    window.open(url, "_blank");
    parus.parus8.registerAction();
  },


  balanceSubReportChangeStatus: function() {

    var rns = [];

    var status = null;

    var badStatus = false;

    dojo.query("*[widgetId]", parus.abonent.subreportsPopup.dataContainer.containerNode).forEach(function(node) {
      var widget = dijit.byNode(node);
      if (widget) if (widget.checked) {
        status = status || (widget.reportStatus || "null");
        if ((widget.reportStatus || "null") != (status || "null")) badStatus = true;
        rns.push(widget.subreportRN);
      }
    });

    if (!rns.length) return;

    if (badStatus) {
      parus.abonent.subreportsPopup.inDialog = true;
      parus.parus8.errorMessage("Статусы отмеченных подотчетов должны совпадать.", function() {
        parus.abonent.subreportsPopup.inDialog = false;
      });
      return;
    }

    if (!rns.length) return;

    parus.database.query("BalanceSubReportStatuses", {
      "SUBREPORT": rns.join(";")
    }, dojo.hitch(this, function(response) {

      var statuses = parus.parus8.rowNodes(response);
      if (statuses.length == 0) {
        parus.abonent.subreportsPopup.inDialog = true;
        parus.parus8.errorMessage("Отсутствуют статусы, доступные для перехода из текущего статуса подотчета.", function() {
          parus.abonent.subreportsPopup.inDialog = false;

        });
        return;
      };


      parus.abonent.subreportsPopup.inDialog = true;

      var dialog = new parus.balanceStatusesDialog({

        statuses: statuses,

        onApply: dojo.hitch(this, function() {
          parus.database.execute("subreportSetStatus", {
            SUBREPORT: rns.join(";"),
            STATUS: dialog.statusesGrid.store.getValue(dialog.statusesGrid.selection.getFirstSelected(), "RN", "")
          });

          parus.abonent.subreportsPopup._loadSubreports();
          return true;
        }),

        onClose: function() {

          parus.abonent.subreportsPopup.inDialog = false;
        }
      });
      dialog.show();

    }));
  },

  balanceSubReportValuesHistory: function() {

    var dialog;

    var dictionaryInfo = parus.dictionaries["BalanceReportsValuesHistory"];

    var conditions = {};

    dojo.mixin(conditions, {
      PRN: parus.abonent._selectedSubReportReport(),
      BLSUBREPORT: parus.abonent._selectedSubReport()
    });

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

    menu.addChild(new dijit.MenuItem({
      label: "Исправить...",
      itemAction: true,
      defaultIcon: "PCdocumentCustomIcon",
      onClick: dojo.hitch(this, function() {
        var editDialog;
        editDialog = new parus.balanceValuesHistoryDialog({

          onShow: function() {

            var store = dialog.grid.store;
            var item = dialog.grid.selection.getFirstSelected();

            editDialog.userEdit.attr("value", store.getValue(item, "USERNAME"));
            editDialog.dateEdit.attr("value", store.getValue(item, "REPORT_DATE"));
            editDialog.noteEdit.attr("value", store.getValue(item, "NOTE"));
          },

          onApply: function() {

            var store = dialog.grid.store;
            var item = dialog.grid.selection.getFirstSelected();

            parus.database.execute("updateValuesHistory", {
              RN: store.getValue(item, "RN"),
              NOTE: editDialog.noteEdit.value
            });

            parus.balance.refreshGrid(dialog.grid);
            return true;
          }
        });
        editDialog.show();
      })
    }));


    menu.addChild(new dijit.MenuItem({
      label: "Удалить...",
      defaultIcon: "PCreduceCustomIcon",
      itemAction: true,
      onClick: dojo.hitch(this, function() {

        (new parus.confirmationDialog({

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

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

            var store = dialog.grid.store;
            var item = dialog.grid.selection.getFirstSelected();
            for (var i = 0; i < dialog.grid.selection.getSelectedCount(); i++) {
              parus.database.execute("deleteValuesHistory", {
                RN: store.getValue(item, "RN")
              });
              item = dialog.grid.selection.getNextSelected(item);
            };

            parus.balance.refreshGrid(dialog.grid);

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

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

    var f = function(extension, colormode) {

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

      var form = document.createElement("form");
      form.method = "GET";
      form.action = parus.database.getHistoryUrl(extension);
      if ( /*!dojo.isChrome ||*/ (extension == "html")) form.target = "_blank";
      var input = document.createElement("input");
      input.type = "hidden";
      input.name = "rn";
      input.value = dialog.getValue();
      form.appendChild(input);

      if (colormode != undefined) {
        var input = document.createElement("input");
        input.type = "hidden";
        input.name = "colormode";
        input.value = colormode;
        form.appendChild(input);
      }

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

    };

    menu.addChild(new dijit.MenuItem({
      label: "Выгрузить в Excel...",
      defaultIcon: "PCxlsCustomIcon",
      itemAction: true,
      onClick: dojo.hitch(this, function() {
        f("xls");
      })
    }));

    menu.addChild(new dijit.MenuItem({
      label: "Выгрузить в формате PDF...",
      itemAction: true,
      onClick: dojo.hitch(this, function() {
        (new parus.excelColorModeDialog({
          onApply: function() {
            f("pdf", this.colorModeEdit.value);
            return true;
          }
        })).show();
      })
    }));

    menu.addChild(new dijit.MenuItem({
      label: "Выгрузить в формате HTML...",
      itemAction: true,
      onClick: dojo.hitch(this, function() {
        (new parus.excelColorModeDialog({
          onApply: function() {
            f("html", this.colorModeEdit.value);
            return true;
          }
        })).show();
      })
    }));

    menu.startup();

    dojo.mixin(dictionaryInfo, {
      dictionary: dictionaryInfo,
      unitCode: dictionaryInfo.unitCode,
      hideCancel: true,
      gridConditions: conditions,
      onApply: function(dialog) {
        return true;
      },
      onClose: function() {
        parus.abonent.subreportsPopup.inDialog = false;
      },
      menu: menu
    });

    parus.abonent.subreportsPopup.inDialog = true;
    dialog = new parus.dictionaryDialog(dictionaryInfo);
    dialog.show();

  },


  balanceSubReportStatusesHistory: function() {

    var dictionaryInfo = parus.dictionaries["BalanceSubReportsStatusesHistory"];

    parus.abonent.subreportsPopup.inDialog = true;
    dojo.mixin(dictionaryInfo, {
      dictionary: dictionaryInfo,
      unitCode: dictionaryInfo.unitCode,
      hideCancel: true,
      gridConditions: {
        PRN: parus.abonent._selectedSubReport()
      },
      onApply: function(dialog) {
        return true;
      },
      onClose: function() {
        parus.abonent.subreportsPopup.inDialog = false;
      }
    });

    new parus.dictionaryDialog(dictionaryInfo).show();

  },


  downloadExcelSubReportPDF: function() {

    var rns = parus.abonent._selectedSubReports();

    if (rns.length == 1) {
      parus.balance.downloadExcelWorkBook("BalanceSubReports", parus.abonent._selectedSubReportReport(), rns, null, "pdf");
    }
    else if (rns.length > 1) {

      var rns = [];
      var prn = "";
      var item = grid.selection.getFirstSelected();

      for (var i = 0; i < grid.selection.getSelectedCount(); i++) {
        if (!prn) prn = store.getValue(item, "PRN");
        rns.push(store.getValue(item, "RN"));
        item = grid.selection.getNextSelected(item);
      };

      parus.balance.downloadExcelWorkBook("BalanceSubReports", parus.abonent._selectedSubReportReport(), rns, null, "pdf");
    }

  },


  downloadExcelSubReportHTML: function() {

    var rns = parus.abonent._selectedSubReports();

    if (rns.length == 1) {
      parus.balance.downloadExcelWorkBook("BalanceSubReports", parus.abonent._selectedSubReportReport(), rns, null, "html");
    }
    else if (rns.length > 1) {

      var rns = [];
      var prn = "";
      var item = grid.selection.getFirstSelected();

      for (var i = 0; i < grid.selection.getSelectedCount(); i++) {
        if (!prn) prn = store.getValue(item, "PRN");
        rns.push(store.getValue(item, "RN"));
        item = grid.selection.getNextSelected(item);
      };

      parus.balance.downloadExcelWorkBook("BalanceSubReports", parus.abonent._selectedSubReportReport(), rns, null, "html");
    }

  },


  userApplicationsSubReport: function() {

    var dialog = new parus.balanceUserProcsDialog({
      unitcode: "BalanceSubReports",

      queryid: "userApps",

      title: "Выбор пользовательского приложения",

      onApply: function() {
        var userapp;
        var groupRecords = false;

        dojo.forEach(dialog.userProcsGrid.selection.getSelected(), function(item) {
          userapp = dialog.userProcsGrid.store.getValue(item, "RN", "");
          groupRecords = (dialog.userProcsGrid.store.getValue(item, "GROUP_RECORDS", "") != "0");
        });

        if (!userapp) return false;

        parus.abonent._userApplication(parus.abonent._selectedSubReports(), dialog.unitcode, userapp, groupRecords);

        return true;
      }
    });

    dialog.show();
  },

  userProceduresSubReport: function() {

    var dialog = new parus.balanceUserProcsDialog({
      unitcode: "BalanceSubReports",

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

        var userproc;
        var confirmText = "";
        var perRecord = false;
        var perSelection = false;

        dojo.forEach(dialog.userProcsGrid.selection.getSelected(), function(item) {
          userproc = dialog.userProcsGrid.store.getValue(item, "RN", "");
          confirmText = dialog.userProcsGrid.store.getValue(item, "CONFIRM_TEXT", "");
          perRecord = (dialog.userProcsGrid.store.getValue(item, "PERRECORD", "") != "0");
          perSelection = (dialog.userProcsGrid.store.getValue(item, "PERSELECTION", "") != "0");
        });

        if (!userproc) return false;
        parus.abonent._userProcedure(parus.abonent._selectedSubReports(), "BalanceSubReports", userproc, confirmText, perRecord, perSelection);
        return true;
      })
    });

    dialog.show();
  },

  userReportsSubReport: function() {

    var dialog = new parus.balanceUserProcsDialog({
      unitcode: "BalanceSubReports",

      queryid: "userReports",

      title: "Выбор пользовательского отчета",

      onApply: function() {

        var userrep;
        var userreptitle = "";
        var userreporttype = "1";

        dojo.forEach(dialog.userProcsGrid.selection.getSelected(), function(item) {
          userrep = dialog.userProcsGrid.store.getValue(item, "RN", "");
          userreptitle = dialog.userProcsGrid.store.getValue(item, "NAME", "");
          userreporttype = dialog.userProcsGrid.store.getValue(item, "REPORT_TYPE", "1");
        });

        if (!userrep) return false;
        parus.abonent._userReport(parus.abonent._selectedSubReports(), "BalanceSubReports", userrep, userreptitle, userreporttype);

        return true;

      }
    });

    dialog.show();
  },


  balanceSubReportsDigitalSignatures: function() {
    var dialog = new parus.balanceReportDigitalSignaturesDialog({
      rn: parus.abonent._selectedSubReport(),
      unitCode: "BalanceSubReports"
    });
    dialog.show();
  },

  balanceSubReportsSign: function() {
    var rnValues = parus.abonent._selectedSubReports();

    if (!rnValues.length) return;

    var dialog = new parus.signDialog({
      rn: rnValues,
      unitCode: "BalanceSubReports",

      onApply: function() {
        var signInfo = [];

        dojo.forEach(rnValues, function(rn) {
          var response = parus.database.execute("GetSignData", {
            RN: rn,
            UNITCODE: "BalanceSubReports"
          });
          if (response) signInfo.push({
            rn: rn,
            data: parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "clobDOC_DATA")
          });
        });

        var note = dialog.getNote();
        var issuer = dialog.getIssuedBy();
        var owner = dialog.getIssuedTo();
        var validFrom = dialog.getValidFrom();
        var validTo = dialog.getValidTo();
        var serialNumber = dialog.getSerialNumber();
        var thumbprint = dialog.getThumbprint();
        var thumbprintToSave = dialog.isUserCertificatesUsed ? thumbprint : null;

        parus.digitalSignature.signData(signInfo, thumbprint).then(
        dojo.hitch(this, function() {
          dojo.forEach(signInfo, function(item) {
            if (item.signedData) parus.database.execute("SaveSign", {
              RN: item.rn,
              UNITCODE: "BalanceSubReports",
              clobSIGN: item.signedData,
              NOTE: note,
              ISSUER: issuer,
              OWNER: owner,
              VALID_FROM: validFrom,
              VALID_TO: validTo,
              SERIALNUMBER: serialNumber,
              THUMBPRINT: thumbprint,
              THUMBPRINT_TO_SAVE: thumbprintToSave
            });
          });

          parus.abonent.refresh();

        }), function(message) {
          parus.parus8.errorMessage(message);
        });

        return true;
      }
    });

    dialog.show();
  },

  balanceSubReportsRemoveSign: function() {

    (new parus.confirmationDialog({

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

      onApply: dojo.hitch(this, function() {
        dojo.forEach(parus.abonent._selectedSubReports(), function(rn) {
          parus.database.execute("DeleteSign", {
            RN: rn,
            UNITCODE: "BalanceSubReports"
          });
        });

        parus.abonent.refresh();

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