dojo.provide("parus.balanceSpecialActions");

dojo.require("parus.balance");

dojo.require("parus.balanceReportRecalculateValuesDialog");
dojo.require("parus.balanceReportCheckProtocolTabPage");
dojo.require("parus.balanceReportConsolidateDialog");

dojo.require("parus.signDialog");
dojo.require("parus.balanceReportDigitalSignaturesDialog");
dojo.require("parus.balanceCheckAbsentReportsDialog");
dojo.require("parus.balanceAbsentReportsDialog");
dojo.require("parus.balancePrimaryReportFormingDialog");
dojo.require("parus.balanceReportAttachedDocumentsDialog");
dojo.require("parus.balanceDeconsolidateDialog");
dojo.require("parus.balanceValuesHistoryDialog");
dojo.require("parus.balanceStatusesDialog");
dojo.require("parus.balanceReportsExchangeExportDialog");
dojo.require("parus.balanceReportsExchangeImportDialog");
dojo.require("parus.balanceReportsExchangeJournalDialog");

dojo.require("parus.excelFileFormatDialog");
dojo.require("parus.excelColorModeDialog");

if (!parus) parus = {};

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

dojo.mixin(parus.balance, {

  getMasterGridCurrentRecordFieldValue: function(grid, fieldName) {

    var store = grid.store;
    var index = grid.selection.getSelectedIndex();
    var item = grid.getItem(index);

    return store.getValue(item, fieldName);
  },

  primaryBalanceReportsRecalculateValues: function(isSubReport) {

    (new parus.balanceReportRecalculateValuesDialog({
      isSubReport: isSubReport
    })).show();

  },

  balanceReportsClearValues: function(grid, isSubReport) {

    (new parus.confirmationDialog({

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

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

        var execMethodName = "clearReportValues";
        if (isSubReport) execMethodName = "clearSubReportValues";

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

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

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

  },

  getAcceptValue: function(accept) {
    if (accept) return 1
    else return 2;
  },

  balanceSetReportAccepted: function(grid, accepted) {

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

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

    return true;
  },

  balanceStatesHistory: function(grid) {

    var store = grid.store;
    var index = grid.selection.getSelectedIndex();
    var item = grid.getItem(index);

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

    dojo.mixin(dictionaryInfo, {
      dictionary: dictionaryInfo,
      unitCode: dictionaryInfo.unitCode,
      hideCancel: true,
      gridConditions: {
        PRN: store.getValue(item, "RN")
      },
      onApply: dojo.hitch(this, function(dialog) {
        return true;
      })
    });

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

  balanceStatusesHistory: function(grid) {

    var store = grid.store;
    var index = grid.selection.getSelectedIndex();
    var item = grid.getItem(index);

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

    dojo.mixin(dictionaryInfo, {
      dictionary: dictionaryInfo,
      unitCode: dictionaryInfo.unitCode,
      hideCancel: true,
      gridConditions: {
        PRN: store.getValue(item, "RN")
      },
      onApply: dojo.hitch(this, function(dialog) {
        return true;
      })
    });

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

  balanceSubStatusesHistory: function(grid) {

    var store = grid.store;
    var index = grid.selection.getSelectedIndex();
    var item = grid.getItem(index);

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

    dojo.mixin(dictionaryInfo, {
      dictionary: dictionaryInfo,
      unitCode: dictionaryInfo.unitCode,
      hideCancel: true,
      gridConditions: {
        PRN: store.getValue(item, "RN")
      },
      onApply: dojo.hitch(this, function(dialog) {
        return true;
      })
    });

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

  balanceValuesHistory: function(grid, isSubReport) {

    var store = grid.store;
    var index = grid.selection.getSelectedIndex();
    var item = grid.getItem(index);

    var kind = store.getValue(item, "KIND");

    var dialog;

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

    var conditions = {};
    if (isSubReport) dojo.mixin(conditions, {
      PRN: store.getValue(item, "PRN"),
      BLSUBREPORT: store.getValue(item, "RN")
    })
    else dojo.mixin(conditions, {
      PRN: store.getValue(item, "RN")
    });


    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());


    menu.addChild(new dijit.MenuItem({
      label: "Открыть...",
      defaultIcon: "PCapplicationsCustomIcon",
      itemAction: true,
      "default": true,
      onClick: dojo.hitch(this, function() {

        var info = parus.parus8.rowNodes(parus.database.execute("GetValuesHistoryInfo", {
          "RN": dialog.getValue()
        }))[0];

        var sectionTitle =
        parus.balance.describeReport(
        parus.parus8.nodeField(info, "REPORT_RN"), parus.parus8.nodeField(info, "SUBREPORT_RN"), null, null, null, parus.parus8.nodeField(info, "TIMESTAMP"), parus.parus8.nodeField(info, "AUTHID"), 4);


        if (parus.parus8._embeddedMode) {
          var id = ["customDownloadReport"].join("_");

          var url = dojo.moduleUrl("parus", "embeddedContent.html") + "?loggedUserHandler=" + parus.database.connected + "&params=" + parus.parus8.hexEncodeParams(["", sectionTitle + " (только для чтения)", "1", parus.database.getHistoryUrl("html", dialog.getValue())]);

          parus.embeddedMode.openTab("history_" + dialog.getValue(), sectionTitle, url);

        }
        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(sectionTitle + " (только для чтения)");

          borderContainer.addChild(headingContentPane);

          var templateGridPane = new dijit.layout.ContentPane({
            region: "center",
            href: parus.database.getHistoryUrl("html", dialog.getValue()),
            "class": "balanceTemplateContentPaneContent",
            onLoad: function() {
              dojo.fadeIn({
                node: templateGridPane.domNode
              }).play();
            }
          });

          borderContainer.addChild(templateGridPane);

          contentPane = new dijit.layout.ContentPane({
            title: parus.balance.formatPageTitle(sectionTitle),
            closable: true,
            "class": "balanceTemplateContentPane",
            onClose: dojo.hitch(this, function() {
              parus.balance.TabContainer.selectChild((kind == "1") ? parus.balance.consolidatedPage : parus.balance.primaryPage);
              return true;
            })
          });

          contentPane.setContent(borderContainer);

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

          if (contentPane.controlButton) dojo.query("*", contentPane.controlButton.containerNode).addClass("balanceReadOnlyHeader");

        }

        dialog.close();


      })
    }));


    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();
  },

  userExternalAccounts: function() {
    var dialog;

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

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

    menu.addChild(new dijit.MenuItem({
      label: "Удалить...",
      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("UnRegisterExternalUserAccount", {
                RN: store.getValue(item, "RN")
              });
              item = dialog.grid.selection.getNextSelected(item);
            };

            parus.balance.refreshGrid(dialog.grid);

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

      })
    }));

    menu.startup();

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

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

  checkReportTitle: function(report, subreport) {
    var result = parus.parus8.rowNodes(parus.database.query("GetReportInfoParts", {
      "REPORT": report,
      "SUBREPORT": subreport
    }))[0];
    return result;
  },

  balanceShowCheckReportProtocol: function(grid, kind, isSubReport, showResultReportOnly, rn, checklist) {

    var pageTitle;

    if (parus.parus8._embeddedMode || !parus.balance.TabContainer) {

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


      if (!rn && grid) {

        var store = grid.store;
        var item = grid.selection.getFirstSelected();
        var rnValues = [];
        for (var i = 0; i < grid.selection.getSelectedCount(); i++) {
          rnValues.push(store.getValue(item, "RN"));
          item = grid.selection.getNextSelected(item);
        };
        rn = rnValues.join(";");
      };



      var url = dojo.moduleUrl("parus", "checkreport.html") + "?loggedUserHandler=" + parus.database.connected + "&params=" + parus.parus8.hexEncodeParams([
      kind, isSubReport ? 1 : 0, 0, dojo.isArray(rn) ? rn.join(";") : rn, checklist]);


      if (parus.parus8._embeddedMode) {

        if (!grid) {

          var checkReportTitle = this.checkReportTitle(
          isSubReport ? null : rn, isSubReport ? rn : null);

          pageTitle = parus.parus8.nodeField(checkReportTitle, "CAPTION");


        }
        else {

          var store = grid.store;

          var item = grid.selection.getFirstSelected();

          pageTitle = ((kind == 0) ? "Первичные" : "Сводные") + " отчеты: Протоколы проверок <br>";

          if (grid.selection.getSelectedCount() == 1) {
            var index = grid.selection.getSelectedIndex();
            var item = grid.getItem(index);

            rn = store.getValue(item, "RN");

            var checkReportTitle = this.checkReportTitle(
            isSubReport ? store.getValue(item, "PRN") : store.getValue(item, "RN"), isSubReport ? store.getValue(item, "RN") : null);

            pageTitle = parus.parus8.nodeField(checkReportTitle, "CAPTION");
          };
        }

        pageTitle = parus.balance.formatPageTitle(pageTitle);

        var id = ["checkreport", rn, checklist].join("_");

        var url = dojo.moduleUrl("parus", "checkreport.html") + "?loggedUserHandler=" + parus.database.connected + "&params=" + parus.parus8.hexEncodeParams([
        kind, isSubReport ? 1 : 0, 0, dojo.isArray(rn) ? rn.join(";") : rn, checklist]);

        parus.embeddedMode.openTab(id, pageTitle, url);
      } else {
        parus.parus8.registerAction();
        var url = dojo.moduleUrl("parus", "checkreport.html") + "?loggedUserHandler=" + parus.database.connected + "&params=" + parus.parus8.hexEncodeParams([
        kind, isSubReport ? 1 : 0, 0, dojo.isArray(rn) ? rn.join(";") : rn, checklist]);
        window.open(url, "_blank");
      }


      return;
    }


    if (!grid) {

      var checkReportTitle = this.checkReportTitle(
      isSubReport ? null : rn[0], isSubReport ? rn[0] : null);

      pageTitle = parus.parus8.nodeField(checkReportTitle, "CAPTION");


      pageTitle = parus.balance.formatPageTitle(pageTitle);

      var tabPage = new parus.balanceReportCheckProtocolTabPage({
        ownerTabContainer: parus.balance.TabContainer,
        title: pageTitle,
        kind: kind,
        checklist: checklist
      });

      tabPage.rn = rn;
      if (isSubReport) {
        tabPage.rn = [parus.parus8.nodeField(checkReportTitle, "REPORT")]
        tabPage.subRn = rn;
      }
      else tabPage.rn = rn;

      tabPage.showResultReportOnly = showResultReportOnly;

      tabPage.show();

      return;

    };

    var store = grid.store;

    var item = grid.selection.getFirstSelected();

    var pageTitle = ((kind == 0) ? "Первичные" : "Сводные") + " отчеты: Протоколы проверок <br>";

    if (grid.selection.getSelectedCount() == 1) {
      var index = grid.selection.getSelectedIndex();
      var item = grid.getItem(index);

      var checkReportTitle = this.checkReportTitle(
      isSubReport ? store.getValue(item, "PRN") : store.getValue(item, "RN"), isSubReport ? store.getValue(item, "RN") : null);

      pageTitle = parus.parus8.nodeField(checkReportTitle, "CAPTION");
    };

    pageTitle = parus.balance.formatPageTitle(pageTitle);

    var tabPage = new parus.balanceReportCheckProtocolTabPage({
      ownerTabContainer: parus.balance.TabContainer,
      title: pageTitle,
      kind: kind,
      checklist: checklist
    });

    var rnValues = [];
    var prnValues = [];

    var item = grid.selection.getFirstSelected();

    for (var i = 0; i < grid.selection.getSelectedCount(); i++) {

      if (isSubReport) {
        rnValues.push(store.getValue(item, "PRN"));
        prnValues.push(store.getValue(item, "RN"));
      }
      else rnValues.push(store.getValue(item, "RN"));

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

    tabPage.rn = rnValues;
    if (isSubReport) tabPage.subRn = prnValues;

    tabPage.showResultReportOnly = showResultReportOnly;

    tabPage.show();

  },


  doShowReportContents: function(rnValues, consolidated) {

    var dialogTitle = "Вхождения";
    var conditions = {};
    if (consolidated) {
      dialogTitle = dialogTitle + ": Сведенные отчеты";
      conditions.PRN = rnValues.join(";")
    }
    else {
      dialogTitle = dialogTitle + ": Сводные отчеты";
      conditions.REPORT = rnValues.join(";")
    };

    var dictionaryInfo = dojo.clone(parus.dictionaries["ConsolidationReports"]);

    if (consolidated) dictionaryInfo.columns = [
    dictionaryInfo.columns[0], dictionaryInfo.columns[1], dictionaryInfo.columns[2], dictionaryInfo.columns[3], dictionaryInfo.columns[4], dictionaryInfo.columns[5], dictionaryInfo.columns[6], dictionaryInfo.columns[7], dictionaryInfo.columns[8], dictionaryInfo.columns[9]]
    else dictionaryInfo.columns = [
    dictionaryInfo.columns[0], dictionaryInfo.columns[1], dictionaryInfo.columns[10], dictionaryInfo.columns[11], dictionaryInfo.columns[12], dictionaryInfo.columns[13], dictionaryInfo.columns[14], dictionaryInfo.columns[15], dictionaryInfo.columns[16], dictionaryInfo.columns[17]];

    var dialog;

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

    menu.addChild(new dijit.MenuItem({
      defaultIcon: "PCapplicationsCustomIcon",
      label: "Исправить значения...",
      itemAction: true,
      "default": true,
      onClick: dojo.hitch(this, function() {

        var store = dialog.grid.store;
        var index = dialog.grid.selection.getSelectedIndex();
        var item = dialog.grid.getItem(index);
        if (consolidated) {
          parus.balance.executeEditValues(
          store.getValue(item, "REPORT"), null, store.getValue(item, "BDATE"), store.getValue(item, "CODE"), store.getValue(item, "AGNABBR"), null, store.getValue(item, "KIND"), store.getValue(item, "AGENT"));
        }
        else {
          parus.balance.executeEditValues(
          store.getValue(item, "PRN"), null, store.getValue(item, "BDATE"), store.getValue(item, "CODE"), store.getValue(item, "AGNABBR1"), null, store.getValue(item, "KIND1"), store.getValue(item, "AGENT1"));
        };
        dialog.close();

      })
    }));


    menu.addChild(new dijit.MenuItem({
      defaultIcon: "PCCheckCustomIcon",
      label: "Проверить значения...",
      itemAction: true,
      onClick: dojo.hitch(this, function() {

        var store = dialog.grid.store;
        var index = dialog.grid.selection.getSelectedIndex();
        var item = dialog.grid.getItem(index);
        var kind = consolidated ? store.getValue(item, "KIND") : store.getValue(item, "KIND1");

        (new parus.balanceCheckReportDialog({
          grid: null,
          kind: kind,
          isSubReport: false,
          rn: [consolidated ? store.getValue(item, "REPORT") : store.getValue(item, "PRN")],
          formedRn: [store.getValue(item, "EDITION")],
          reportRn: [consolidated ? store.getValue(item, "REPORT") : store.getValue(item, "PRN")],
          title: ((kind == "0") ? "Первичные" : "Сводные") + " отчеты: Параметры проверки"
        })).show();

        dialog.close();

      })
    }));

    menu.addChild(new dijit.MenuItem({
      label: "Протокол проверки...",
      itemAction: true,
      onClick: dojo.hitch(this, function() {

        var store = dialog.grid.store;
        var index = dialog.grid.selection.getSelectedIndex();
        var item = dialog.grid.getItem(index);
        parus.balance.balanceShowCheckReportProtocol(null, consolidated ? store.getValue(item, "KIND") : store.getValue(item, "KIND1"), false, false, [consolidated ? store.getValue(item, "REPORT") : store.getValue(item, "PRN")], null);

        dialog.close();
      })
    }));

    menu.addChild(new dijit.MenuSeparator());
    menu.addChild(new dijit.MenuItem({
      label: "История состояний...",
      itemAction: true,
      onClick: dojo.hitch(this, function() {

        var store = dialog.grid.store;
        var index = dialog.grid.selection.getSelectedIndex();
        var item = dialog.grid.getItem(index);

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

        dojo.mixin(dictionaryInfo, {
          dictionary: dictionaryInfo,
          unitCode: dictionaryInfo.unitCode,
          hideCancel: true,
          gridConditions: {
            PRN: consolidated ? store.getValue(item, "REPORT") : store.getValue(item, "PRN")
          },
          onApply: dojo.hitch(this, function(dialog) {
            return true;
          })
        });

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

      })
    }));


    menu.addChild(new dijit.MenuSeparator());
    if (consolidated) {

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

      consMenu.addChild(new dijit.MenuItem({
        label: "Сводные отчеты...",
        itemAction: true,
        onClick: dojo.hitch(this, function() {
          var rnValues = [];
          var store = dialog.grid.store;
          var item = dialog.grid.selection.getFirstSelected();
          for (var i = 0; i < dialog.grid.selection.getSelectedCount(); i++) {
            rnValues.push(store.getValue(item, "REPORT"));
            item = dialog.grid.selection.getNextSelected(item);
          };
          dialog.close();
          parus.balance.doShowReportContents(rnValues, false);
        })
      }));

      menu.addChild(new dijit.PopupMenuItem({
        label: "Вхождения/состав",
        popup: consMenu
      }));
    }
    else {
      var consMenu = new dijit.Menu({
        "class": "balanceMenu"
      });

      consMenu.addChild(new dijit.MenuItem({
        label: "Разрешить пересчеты...",
        itemAction: true,
        onClick: dojo.hitch(this, function() {

          var store = dialog.grid.store;
          parus.progressDialog.iterateOverGrid("Разрешение пересчетов...", dialog.grid, function(item) {
            parus.database.execute("doBeforeHandReport", {
              RN: store.getValue(item, "PRN")
            });
          }, function() {
            parus.balance.refreshGrid(dialog.grid, "RN", store.getValue(dialog.grid.selection.getFirstSelected(), "RN"));
          });

        })
      }));


      consMenu.addChild(new dijit.MenuItem({
        label: "Подтвердить сведение...",
        itemAction: true,
        onClick: dojo.hitch(this, function() {
          var store = dialog.grid.store;
          parus.progressDialog.iterateOverGrid("Подтверждение сведения...", dialog.grid, function(item) {
            parus.database.execute("confirmReportConsolidation", {
              RN: store.getValue(item, "PRN")
            });
          }, function() {
            parus.balance.refreshGrid(dialog.grid, "RN", store.getValue(dialog.grid.selection.getFirstSelected(), "RN"));
          });
        })
      }));

      consMenu.addChild(new dijit.MenuItem({
        defaultIcon: "PCcloseCustomIcon",
        label: "Расформировать свод...",
        itemAction: true,
        onClick: dojo.hitch(this, function() {

          var paramsdialog = new parus.balanceDeconsolidateDialog({
            onApply: dojo.hitch(this, function() {
              var grid = dialog.grid;
              var store = grid.store;
              var ml = (paramsdialog.multiLevel.checked ? "1" : "0");

              parus.progressDialog.iterateOverGrid("Расформирование свода...", grid, function(item) {
                parus.database.execute("deconsolidateReport", {
                  RN: store.getValue(item, "PRN"),
                  MULTI_SIGN: ml
                });
              }, function() {

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

              });
            })

          });

          paramsdialog.show();
        })
      }));

      menu.addChild(new dijit.PopupMenuItem({
        label: "Сведение",
        popup: consMenu
      }));

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

      consMenu.addChild(new dijit.MenuItem({
        label: "Сведенные отчеты...",
        itemAction: true,
        onClick: dojo.hitch(this, function() {
          var rnValues = [];

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

          for (var i = 0; i < dialog.grid.selection.getSelectedCount(); i++) {
            rnValues.push(store.getValue(item, "PRN"));
            item = dialog.grid.selection.getNextSelected(item);
          };

          dialog.close();

          parus.balance.doShowReportContents(rnValues, true);
        })
      }));

      menu.addChild(new dijit.PopupMenuItem({
        label: "Вхождения/состав",
        popup: consMenu
      }));
    };

    menu.startup();

    dojo.mixin(dictionaryInfo, {
      dictionary: dictionaryInfo,
      gridConditions: conditions,
      title: dialogTitle,
      hideCancel: true,
      menu: menu,
      userDataSection: "parus.dictionaryDialog-" + dictionaryInfo.code + (consolidated ? "1" : "0")
    });

    dialog = new parus.dictionaryDialog(dictionaryInfo);

    dialog.show();

  },

  balanceShowReportContents: function(grid, consolidated) {
    var rnValues = [];

    var store = grid.store;
    var index = grid.selection.getSelectedIndex();
    var item = grid.getItem(index);

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

    parus.balance.doShowReportContents(rnValues, consolidated);

  },

  balanceReportsConsolidate: function() {
    var rnValues = [];

    grid = parus.balance.consolidatedMasterGrid;
    var store = grid.store;
    var item = grid.selection.getFirstSelected();

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

    var dialog = new parus.balanceReportConsolidateDialog({
      rn: rnValues,
      title: "Сводные отчеты: Параметры сведения"
    });

    dialog.show();
  },

  balanceReportsDeConsolidate: function() {

    var dialog = new parus.balanceDeconsolidateDialog({

      onApply: dojo.hitch(this, function() {
        var grid = parus.balance.consolidatedMasterGrid;
        var store = grid.store;
        var ml = (dialog.multiLevel.checked ? "1" : "0");

        parus.progressDialog.iterateOverGrid("Расформирование свода...", grid, function(item) {
          parus.database.execute("deconsolidateReport", {
            RN: store.getValue(item, "RN"),
            MULTI_SIGN: ml
          });
        }, function() {
          parus.balance.refreshGrid(grid, "RN", store.getValue(grid.selection.getFirstSelected(), "RN"));

          var dgrid = parus.balance.consolidatedDetailGrid;
          var dstore = dgrid.store;

          parus.balance.refreshGrid(dgrid, "RN", dstore.getValue(dgrid.selection.getFirstSelected(), "RN"));

        });
        return true;
      })

    });

    dialog.show();


  },

  balanceReportsDoBeforeHand: function() {
    grid = parus.balance.consolidatedMasterGrid;
    var store = grid.store;

    parus.progressDialog.iterateOverGrid("Разрешение пересчетов...", grid, function(item) {
      parus.database.execute("doBeforeHandReport", {
        RN: store.getValue(item, "RN")
      });
    }, function() {
      parus.balance.refreshGrid(grid, "RN", store.getValue(grid.selection.getFirstSelected(), "RN"));
    });

  },

  balanceReportsConfirmConsolidation: function() {
    grid = parus.balance.consolidatedMasterGrid;
    var store = grid.store;

    parus.progressDialog.iterateOverGrid("Подтверждение сведения...", grid, function(item) {
      parus.database.execute("confirmReportConsolidation", {
        RN: store.getValue(item, "RN")
      });
    }, function() {
      parus.balance.refreshGrid(grid, "RN", store.getValue(grid.selection.getFirstSelected(), "RN"));
    });

  },

  balanceReportsUndoExport: function(grid) {
    (new parus.confirmationDialog({

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

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

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

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


  balanceReportsDoExport: function(grid) {
    (new parus.confirmationDialog({

      message: "Отправить выделенные отчеты в центр учета?",

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

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

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


  balanceReportsSign: function(grid, unitCode) {
    var rnValues = [];

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

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

    if (!rnValues.length) return;

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

      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: unitCode
          });

          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: unitCode,
              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.balance.refreshGrid(grid, "RN", rnValues[0]);
        }

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

        return true;
      }
    });

    dialog.show();
  },

  balanceReportsRemoveSign: function(grid, unitCode) {
    (new parus.confirmationDialog({

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

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

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

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

  balanceReportsDigitalSignatures: function(grid, unitCode) {
    var store = grid.store;
    var index = grid.selection.getSelectedIndex();
    var item = grid.getItem(index);

    var dialog = new parus.balanceReportDigitalSignaturesDialog({
      rn: store.getValue(item, "RN"),
      unitCode: unitCode
    });

    dialog.show();
  },

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

        (new parus.balanceAbsentReportsDialog({
          kind: kind,

          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.balance.refreshGrid(grid, "RN", grid.store.getValue(grid.selection.getFirstSelected(), "RN"));
          })

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

    })

    dialog.show();

  },

  balancePrimaryReportForming: function() {

    var grid = parus.balance.consolidatedMasterGrid;
    var store = grid.store;
    var index = grid.selection.getSelectedIndex();
    var item = grid.getItem(index);

    var dialog = new parus.balancePrimaryReportFormingDialog({

      formCode: store.getValue(item, "FORM_CODE"),

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

        dialog.restoreFormLastValues();

        dialog.agentCodeEdit.attr("value", store.getValue(item, "AGNABBR"));

        dialog.agentNameEdit.attr("disabled", false);
        dialog.agentNameEdit.attr("value", store.getValue(item, "AGNNAME"));
        dialog.agentHeadEdit.attr("value", store.getValue(item, "HEAD_ORG_NAME"));


        dialog.reportDateEdit.attr("value", store.getValue(item, "BDATE"));

      }),

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

        var path = parus.balance.consolidatedCatalogTree.path;

        response = parus.database.execute("primaryReportForming", {
          RN: store.getValue(item, "RN"),
          CATALOG_NAME: dialog.catalogInput.value,
          AGENT_CODE: dialog.agentCodeEdit.value,
          AGENT_NAME: dialog.agentNameEdit.value,
          BDATE: dialog.reportDateEdit.value,
          RELOAD: dialog.reloadCheckBox.value ? 1 : 0
        });

        if (!response) return false;

        parus.parus8.notificationMessage("Первичный отчет сформирован.");

        return true;
      })

    });

    dialog.show();
  },

  balanceReportsAttachedDocuments: function(grid, unitcode) {

    if (dojo.indexOf(parus.balance.availableUnits, "FileLinks") == -1) {
      parus.parus8.errorMessage("У вас нет доступа к разделу <br/> \"Присоединенные документы\"<br/> в приложении <br/> \"Сведение отчетности. Центр учета Онлайн\". <br/>Обратитесь к администратору.");
      return;
    };

    var store = grid.store;
    var index = grid.selection.getSelectedIndex();
    var item = grid.getItem(index);

    (new parus.balanceReportAttachedDocumentsDialog({
      rn: store.getValue(item, "RN"),
      unitcode: unitcode
    })).show();
  },

  changeStatus: function(grid, kind) {

    var store = grid.store;
    var index = grid.selection.getSelectedIndex();

    var rns = [];
    var status = null;

    var item = grid.selection.getFirstSelected();
    for (var i = 0; i < grid.selection.getSelectedCount(); i++) {
      status = status || (store.getValue(item, "STATUS") || "null");
      if ((store.getValue(item, "STATUS") || "null") != (status || "null")) {
        parus.parus8.errorMessage("Статусы отмеченных отчетов должны совпадать.");
        return;
      }
      rns.push(store.getValue(item, "RN"));
      item = grid.selection.getNextSelected(item);
    };


    if (!rns.length) 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", "")
          });

          this.refreshGrid(grid, "RN", rns[0]);
          return true;
        })
      });
      dialog.show();

    }));

  },



  changeSubreportStatus: function(grid, kind) {

    var store = grid.store;
    var index = grid.selection.getSelectedIndex();

    var rns = [];
    var status = null;

    var item = grid.selection.getFirstSelected();
    for (var i = 0; i < grid.selection.getSelectedCount(); i++) {
      status = status || (store.getValue(item, "STATUS") || "null");
      if ((store.getValue(item, "STATUS") || "null") != (status || "null")) {
        parus.parus8.errorMessage("Статусы отмеченных подотчетов должны совпадать.");
        return;
      }
      rns.push(store.getValue(item, "RN"));
      item = grid.selection.getNextSelected(item);
    };


    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.parus8.errorMessage("Отсутствуют статусы, доступные для перехода из текущего статуса подотчета.");
        return;
      };

      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", "")
          });

          this.refreshGrid(grid, "RN", rns[0]);
          return true;
        })
      });
      dialog.show();

    }));

  },

  balanceReportsExchangeExport: function(grid, catalogTree, consolidated) {


    var dialog = new parus.balanceReportsExchangeExportDialog({


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

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

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

        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(grid, catalogTree, consolidated) {

    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.balance.refreshGrid(grid);
      }, 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();

  }

});