text: import { Loc, Runtime, Type } from "main.core";
  import { BitrixVue } from 'ui.vue';
  import './style.css';
  // import { } from '../plugins/dynatable/jquery.dynatable';
  // import { } from '../plugins/datatables/datatables';
  
  (function () {
      if (window.BlogBFileDialog)
          return;
  
      window.BlogBFileDialog = function (arParams) {
          this.dialogName = 'AttachmentsDialog';
          this.agent = false;
          this.uploadFileUrl = arParams.upload_path; // from file.input php
  
          this.id = (!!arParams["id"] ? arParams["id"] : this.getID());
          this.controlID = arParams["id"];
          this.enabled = true;
  
          this.controller = (!!arParams.controller) ? arParams.controller : null;
          this.fileInput = arParams.fileInput;
          arParams.hAttachEvents = BX.delegate(this.InitAgent, this);
  
          this.msg = arParams.msg;
          this.dropAutoUpload = arParams.dropAutoUpload;
          this.CID = arParams.CID;
          this.multiple = !!arParams.multiple;
  
          arParams.caller = this;
          arParams.classes = {
              'uploaderParent': 'file-uploader',
              'uploader': 'file-fileUploader',
              'tpl_simple': 'file-simple',
              'tpl_extended': 'file-extended',
              'selector': 'file-selector',
              'selector_active': 'file-selector-active'
          };
          arParams.doc_prefix = 'wd-doc';
          arParams.placeholder = BX.findChild(this.controller, {
              'className': 'file-placeholder-tbody'
          }, true);
          this.doc_prefix = arParams.doc_prefix;
          this.values = (arParams["values"] || []);
  
          if (!!BX.FileUploadAgent) {
              this.agent = new BX.FileUploadAgent(arParams);
              BX.addCustomEvent(this, 'ShowUploadedFile', BX.delegate(this.ShowUploadedFile, this));
              BX.addCustomEvent(this, 'StopUpload', BX.delegate(this.StopUpload, this));
              BX.onCustomEvent(BX(this.controller.parentNode), "BFileDLoadFormControllerInit", [this]);
          } else {
              BX.debug('/bitrix/components/bitrix/main.file.input/templates/drag_n_drop/script.js: BX.FileUploadAgent is not defined.' +
                  ' You need to load /bitrix/js/main/file_upload_agent.js');
          }
      }
      window.dataHeader = "Y";
      window.StringDataObj = [];
      window.BlogBFileDialogUniqueID = [];
      window.BlogBFileDialog.prototype.getID = function () {
          return '' + new Date().getTime();
      }
  
      window.BlogBFileDialog.prototype.InitAgent = function (agent) {
          if (this.controller) {
              agent.placeholder = BX.findChild(this.controller, {
                  'className': 'file-placeholder-tbody'
              }, true);
          }
      }
  
      window.BlogBFileDialog.prototype.ShowUploadedFile = function (agent) // event
      {
          this.agent = agent;
          var uploadResult = agent.uploadResult;
  
          if (uploadResult && (uploadResult.element_id > 0)) {
              if (!!agent.inputName && agent.inputName.length > 0) {
                  var hidden = BX.create('INPUT', {
                      props: {
                          'id': 'file-doc' + uploadResult.element_id,
                          'type': 'hidden',
                          'name': agent.inputName + (this.multiple ? '[]' : ''),
                          'value': uploadResult.element_id
                      }
                  });
                  agent.controller.appendChild(hidden);
              }
              this.values.push(this.CreateFileRow(uploadResult));
              agent._clearPlace();
  
              if (this.controller && this.controller.parentNode)
                  BX.onCustomEvent(this.controller.parentNode, 'OnFileUploadSuccess', [uploadResult, this]);
  
          } else {
              var text = (uploadResult && uploadResult["error"] ? uploadResult["error"] : this.msg.upload_error);
              agent.ShowUploadError(text);
  
              if (this.controller && this.controller.parentNode)
                  BX.onCustomEvent(this.controller.parentNode, 'OnFileUploadFail');
          }
      }
  
      window.BlogBFileDialog.prototype.CreateFileRow = function (result) {
          var res = result;
          var mode = 'file';
          if (!!res.element_content_type && (res.element_content_type.indexOf('image/') == 0) &&
              !!res.element_image && (res.element_image.length > 0) &&
              !!res.element_thumbnail && (res.element_thumbnail.length > 0)) {
              mode = 'image';
          }
  
          var tpl = BX("file-" + mode + "-template");
  
          BX.template(tpl, BX.delegate(function (node) {
              this.tplFileRow(node, res);
          }, this));
          var newNode = BX.clone(tpl);
  
          if (mode == 'image') {
              var span = null;
              for (let i = 0; i < newNode.children.length; i++) {
                  span = newNode.children[i];
                  if (span.nodeType == 1)
                      break;
              }
  
              span.setAttribute('id', this.doc_prefix + result.element_id);
              var closeControl = BX.findChild(span, {
                  'className': 'feed-add-post-del-but'
              }, true);
              BX.bind(closeControl, 'click', BX.delegate(
                  function () {
                      var control = closeControl;
                      var parent = control.parentNode;
                      this.agent.StopUpload(parent);
                      BX.cleanNode(parent, true);
                  }, this));
              this.agent.AddNodeToPlaceholder(span);
              newNode = span;
          } else {
              newNode.setAttribute('id', this.doc_prefix + result.element_id);
              this.agent.AddRowToPlaceholder(newNode);
          }
          return newNode;
      }
  
      window.BlogBFileDialog.prototype.GetUploadDialog = function (agent) {
          return new BlogBFileDialogUploader(this, agent);
      }
  
      window.BlogBFileDialog.prototype.tplFileRow = function (nodes, res) {
          for (let id in nodes) {
              if (!nodes.hasOwnProperty(id))
                  continue;
  
              var node = nodes[id];
  
              if ((id == 'image') &&
                  !!res.element_image && (res.element_image.length > 0) &&
                  !!res.element_thumbnail && (res.element_thumbnail.length > 0)) {
                  node.setAttribute('src', res.element_image);
                  node.setAttribute('rel', res.element_thumbnail);
              } else {
                  if (!!res['element_' + id])
                      node.innerHTML = res['element_' + id];
              }
          }
      }
  
      window.BlogBFileDialog.prototype._addUrlParam = function (url, param) {
          if (!url)
              return null;
          if (url.indexOf(param) == -1)
              url += ((url.indexOf('?') == -1) ? '?' : '&') + param;
          return url;
      }
  
      window.BlogBFileDialog.prototype.LoadDialogs = function (dialogs) {
          if (!!this.agent)
              this.agent.LoadDialogs(dialogs);
          else {
              var dlgs = dialogs;
              setTimeout(BX.delegate(function () {
                  this.LoadDialogs(dlgs);
              }, this), 100);
          }
      }
  
      window.BlogBFileDialog.prototype.StopUpload = function (agent, parent) {
          this.agent = agent;
          let id = false,
              mID = parent.id.match(new RegExp(this.doc_prefix + '(\\d+)'));
          if (!!mID) {
              id = mID[1];
          }
  
          if (this.controller && this.controller.parentNode)
              BX.onCustomEvent(this.controller.parentNode, 'OnFileUploadRemove', [id, this]);
  
          var data = {
              action: 'StopUploadFile',
              fileID: id,
              sessid: BX.bitrix_sessid(),
              cid: this.CID,
              controlID: this.controlID,
              mfi_mode: "delete",
              grid_id: 'uploadBasket',
          };
          BX.ajax.post(this.uploadFileUrl, data);
      }
  
      window.BlogBFileDialogDispatcher = function (controller) {
          this.id = this.getID();
          this.controller = controller;
          BX.loadScript('/bitrix/js/main/core/core_dd.js', BX.delegate(function () {
              if (BX.type.isElementNode(this.controller) && this.controller.parentNode && this.controller.parentNode.parentNode) {
                  var target = this.controller.parentNode.parentNode;
                  this.dropbox = new BX.DD.dropFiles(target);
                  if (this.dropbox && this.dropbox.supported() && BX.ajax.FormData.isSupported()) {
                      this.hExpandUploader = BX.proxy(this.ExpandUploader, this);
                      BX.addCustomEvent(this.dropbox, 'dragEnter', this.hExpandUploader);
                      BX.addCustomEvent(target, "UnbindDndDispatcher", BX.delegate(this.Unbind, this));
                  }
              }
          }, this));
      }
  
      window.BlogBFileDialogDispatcher.prototype.getID = function () {
          return '' + new Date().getTime();
      }
  
      window.BlogBFileDialogDispatcher.prototype.ExpandUploader = function () {
          BX.onCustomEvent(BX(this.controller.parentNode), "BFileDLoadFormController", ['show']);
          //	this.Unbind();
      }
  
      window.BlogBFileDialogDispatcher.prototype.Unbind = function () {
          BX.removeCustomEvent(this.dropbox, 'dragEnter', this.hExpandUploader);
      }
  
      // upoader section
      window.BlogBFileDialogUploader = function (arParams, agent) {
          this.WDUploaded = false;
          this.WDUploadInProgress = false;
          this.documentExists = false;
          this.fileDropped = false;
  
          this.caller = arParams;
          this.agent = agent;
          this.parentID = this.agent.id;
          this.id = this.caller.getID();
  
          this.msg = arParams.msg;
          this.dropAutoUpload = arParams.dropAutoUpload;
          this.uploadFileUrl = arParams.uploadFileUrl; // from file.input php
          this.CID = arParams.CID;
          this.controlID = arParams.controlID;
  
          this.CreateElements();
          this.fileInput = (!!agent.fileInput ? agent.fileInput : ((BX.type.isDomNode(agent.fileInputID)) ? agent.fileInputID : BX(arParams.fileInput)));
          if (BX.type.isDomNode(this.fileInput)) {
              this.fileInput.name = 'mfi_files[]';
          }
          this.fileList = this.__form;
  
          BX.loadScript('/bitrix/js/main/core/core_dd.js', BX.delegate(
              function () {
                  var dropbox = new BX.DD.dropFiles();
                  if (dropbox && dropbox.supported() && BX.ajax.FormData.isSupported()) {
                      this.dropbox = dropbox;
                  }
                  this.agent.BindUploadEvents(this);
              }, this));
      }
  
      window.BlogBFileDialogUploader.prototype.CreateElements = function () {
          var uniqueID;
          do {
              uniqueID = Math.floor(Math.random() * 99999);
          } while (BX("iframe-" + uniqueID));
  
          let iframeName = "iframe-" + this.id,
              iframe = BX.create("IFRAME", {
                  props: {
                      name: iframeName,
                      id: iframeName
                  },
                  style: {
                      display: "none"
                  }
              });
          document.body.appendChild(iframe);
          this.iframeUpload = iframe;
  
          let form = BX.create("FORM", {
              props: {
                  id: "form-" + uniqueID,
                  method: "POST",
                  action: this.uploadFileUrl,
                  enctype: "multipart/form-data",
                  encoding: "multipart/form-data",
                  target: iframeName
              },
              style: {
                  display: "none"
              },
              children: [
                  BX.create("INPUT", {
                      props: {
                          type: "hidden",
                          name: "sessid",
                          value: BX.bitrix_sessid()
                      }
                  }),
                  BX.create("INPUT", {
                      props: {
                          type: "hidden",
                          name: "uniqueID",
                          value: uniqueID
                      }
                  }),
                  BX.create("INPUT", {
                      props: {
                          type: "hidden",
                          name: "cid",
                          value: this.CID
                      }
                  }),
                  BX.create("INPUT", {
                      props: {
                          type: "hidden",
                          name: "controlID",
                          value: (!!this.controlID ? this.controlID : '')
                      }
                  }),
                  BX.create("INPUT", {
                      props: {
                          type: "hidden",
                          name: "mfi_mode",
                          value: "upload"
                      }
                  })
              ]
          });
          document.body.appendChild(form);
          this.__form = form;
  
          window['FILE_UPLOADER_CALLBACK_' + uniqueID] = BX.proxy(this.Callback, this);
      }
  
      window.BlogBFileDialogUploader.prototype.GetUploadFileName = function () {
          let fileName = '',
              fileNode = null;
          if (this.fileInput && (this.fileInput.value.length > 0)) {
              fileName = this.fileInput.value;
              if (fileName.indexOf('\\') > -1) // deal with Chrome fakepath
                  fileName = fileName.substr(fileName.lastIndexOf('\\') + 1);
          } else {
              fileNode = this.fileList;
              if (fileNode.file)
                  fileName = fileNode.file.fileName || fileNode.file.name;
          }
          return fileName;
      }
  
      window.BlogBFileDialogUploader.prototype.Callback = function (files, uniqueID) {
          if (files.length > 0) {
              for (var i = 0; i < files.length; i++) {
                  var result = {};
                  result.success = true;
                  result.storage = 'bfile';
                  result.element_id = files[i].fileID;
                  result.element_name = files[i].fileName;
                  result.element_size = files[i].fileSize;
                  result.element_url = files[i].fileURL;
                  result.element_content_type = (files[i].content_type ? files[i].content_type : files[i].fileContentType);
  
                  result.element_image = ((!!files[i].img_thumb_src) ? files[i].img_thumb_src : files[i].fileSrc);
                  if (!!result.element_image)
                      result.element_image = result.element_image.replace(/\/([^\/]+)$/, function (str, name) {
                          return "/" + BX.util.urlencode(name);
                      });
                  result.element_thumbnail = ((!!files[i].img_source_src) ? files[i].img_source_src : files[i].fileSrc);
                  if (!!result.element_thumbnail)
                      result.element_thumbnail = result.element_thumbnail.replace(/\/([^\/]+)$/, function (str, name) {
                          return "/" + BX.util.urlencode(name);
                      });
                  if (files["error"])
                      result["error"] = files["error"];
                  if (files[i]["status"] == "error" && !result["error"])
                      result["error"] = files[i]["message"];
  
                  BX.onCustomEvent(this, 'uploadFinish', [result]);
              }
          } else {
              var result = {};
              result.success = false;
              result.messages = this.msg.upload_error;
              BX.onCustomEvent(this, 'uploadFinish', [result]);
          }
          window['FILE_UPLOADER_CALLBACK_' + uniqueID] = BX.DoNothing;
          BX.cleanNode(BX("iframe-" + uniqueID), true);
          BX.cleanNode(BX("form-" + uniqueID), true);
          this.agent.uploadDialog = null;
      }
  
      window.BlogBFileDialogUploader.prototype.UploadResponse = function (evt, responseJSONStr) {
          this.WDUploadInProgress = false;
          BX.unbind(window, 'beforeunload', BX.proxy(this.UploadLeave, this));
  
          if (!responseJSONStr ||
              responseJSONStr.length <= 0) {
              this.onError();
          }
      }
  
      window.BlogBFileDialogUploader.prototype.UploadResponseIframe = function (evt, responseJSONStr) {
          this.WDUploadInProgress = false;
          BX.unbind(window, 'beforeunload', BX.proxy(this.UploadLeave, this));
      }
  
      window.BlogBFileDialogUploader.prototype.UploadLeave = function (e) {
          var e = e || window.event;
          var msg = '';
          if (this.WDUploadInProgress)
              msg = this.msg.UploadInterrupt;
          else if (((!this.WDUploaded) && this.fileInput && (this.fileInput.value.length > 0)))
              msg = this.msg.UploadNotDone;
          if (msg != '') {
              if (e)
                  e.returnValue = msg;
              return msg; // safari & chrome
          }
          return;
      }
  
      window.BlogBFileDialogUploader.prototype.UpdateListFiles = function (files) {
          if (this && files) {
              if (files.length < 1)
                  return;
              var fileNode = this.fileList;
              fileNode.file = files[0];
  
              this.WDUploadInProgress = true;
              this.fileDropped = true;
              this.CallSubmit();
          }
      }
  
      window.BlogBFileDialogUploader.prototype.GetInputData = function (parentNode) {
          var elements = [];
          var data = {};
          elements = elements.concat(
              BX.findChildren(parentNode, {
                  'tag': 'input'
              }, true),
              BX.findChildren(parentNode, {
                  'tag': 'textarea'
              }, true),
              BX.findChildren(parentNode, {
                  'tag': 'select'
              }, true));
  
          for (var i = 0; i < elements.length; i++) {
              var el = elements[i];
              if (!el || el.disabled || el.name.length < 1)
                  continue;
              switch (el.type.toLowerCase()) {
                  case 'text':
                  case 'textarea':
                  case 'password':
                  case 'hidden':
                  case 'select-one':
                      data[el.name] = el.value;
                      break;
                  case 'radio':
                      if (el.checked)
                          data[el.name] = el.value;
                      break;
                  case 'checkbox':
                      data[el.name] = (el.checked ? 'Y' : 'N');
                      break;
                  case 'select-multiple':
                      var l = el.options.length;
                      if (l > 0) data[el.name] = new Array();
                      for (let j = 0; j < l; j++)
                          if (el.options[j].selected)
                              data[el.name].push(el.options[j].value);
                      break;
                  default:
                      break;
              }
          }
          return data;
      }
  
      window.BlogBFileDialogUploader.prototype.SetFileInput = function (fileInput) {
          if (!!this.__form.mfi_save)
              return;
          if (this.fileInput && this.fileInput != fileInput)
              BX.remove(this.fileInput);
          this.__form.appendChild(fileInput);
          this.fileInput = fileInput;
      }
  
      window.BlogBFileDialogUploader.prototype.CallSubmit = function () {
          if (!!this.__form.mfi_save)
              return;
          BX.onCustomEvent(this, 'uploadStart', [this]);
  
          BX.bind(window, 'beforeunload', BX.proxy(this.UploadLeave, this));
          BX.bind(this.iframeUpload, 'load', BX.delegate(this.UploadResponseIframe, this));
  
          if (this.dropbox) {
              this.onProgress(0.15);
              if (this.fileInput && (this.fileInput.files.length > 0)) {
                  var fileNode = this.fileList;
                  fileNode.file = this.fileInput.files[0];
              }
  
              var arConstParams = this.GetInputData(this.__form);
              this.fileNodes = [this.fileList];
              for (let i in this.fileNodes) {
                  if (this.fileNodes[i].file) {
                      var fd = new BX.ajax.FormData();
  
                      for (let item in this.fileNodes[i].data) {
                          fd.append(item, this.fileNodes[i].data[item]);
                      }
  
                      if (!!Object && !!Object.keys) // for IE 10 ....
                      {
                          var keys = Object.keys(arConstParams);
                          for (var k in keys) {
                              var key = keys[k]
                              var cons = arConstParams[key]
                              fd.append(key, cons);
                          }
                      } else {
                          for (let item in arConstParams) {
                              fd.append(item, arConstParams[item]);
                          }
                      }
  
                      fd.append('mfi_files[]', this.fileNodes[i].file);
                      fd.send(
                          this.uploadFileUrl + (this.uploadFileUrl.indexOf("/?") == -1 ? "?" : "&") + "action=FileUpload",
                          BX.delegate(function (ajaxdata) {
                              this.UploadResponse(null, ajaxdata);
                          }, this),
                          BX.delegate(this.onProgress, this)
                      );
                  }
              }
          } else {
              this.onProgress(0.15);
              this.WDUploadInProgress = true;
              var fid = this.__form.id;
              BX.submit(this.__form, 'mfi_save', 'Y');
          }
      }
  
      window.BlogBFileDialogUploader.prototype.onProgress = function (percent) {
          if (isNaN(percent))
              return;
          BX.onCustomEvent(this, 'progress', [percent]);
      }
  
      window.BlogBFileDialogUploader.prototype.onError = function () {
          BX.onCustomEvent(this, 'uploadFinish', [{
              success: false,
              messages: this.msg.upload_error
          }]);
      }
  
      top.BlogBFileDialog = window.BlogBFileDialog;
      top.BlogBFileDialogUploader = window.BlogBFileDialogUploader;
      top.BlogBFileDialogDispatcher = window.BlogBFileDialogDispatcher;
  
      window.MFIDD = function (params) {
          BX.loadCSS('/bitrix/components/bitrix/main.file.input/templates/drag_n_drop/style.css');
  
          var status = (params["status"] === 'show' ? 'show' : (params["status"] === 'hide' ? 'hide' : 'switch'));
          // всегда показываем поле загрузки
          if (status == 'switch')
              status = (params['controller'].style.display != 'none' ? 'show' : 'show');
          var showControl = function (status) {
              if (status == "show") {
                  BX.fx.show(params['controller'], 'fade', {
                      time: 0.2
                  });
                  if (params['switcher'] && params['switcher'].style.display != 'none')
                      BX.fx.hide(params['switcher'], 'fade', {
                          time: 0.1
                      });
                  if (!!window['BfileUnbindDispatcher' + params['uid']])
                      window['BfileUnbindDispatcher' + params['uid']]();
              } else if (params['controller'].style.display !== "none") {
                  BX.fx.hide(params['controller'], 'fade', {
                      time: 0.2
                  });
              }
          };
          if (!params['controller'].loaded) {
              params['controller'].loaded = true;
              var dropbox = new BX.DD.dropFiles(),
                  variant = (dropbox && dropbox.supported() && BX.ajax.FormData.isSupported() ? 'extended' : 'simple');
  
              top['BfileFD' + params['uid']] = window['BfileFD' + params['uid']] = new BlogBFileDialog({
                  'mode': variant,
                  'CID': params['CID'],
                  'id': params['id'],
                  'upload_path': params['upload_path'],
                  'multiple': params['multiple'],
                  'controller': params['controller'],
                  'inputName': params['inputName'],
                  'fileInput': ("file-fileUploader-" + params['uid']),
                  'fileInputName': "mfi_files[]",
                  'values': BX.findChildren(BX('file-selectdialog-' + params['uid']), {
                      "className": "file-inline-file"
                  }, true),
                  'msg': {
                      'loading': BX.message('loading'),
                      'file_exists': BX.message('file_exists'),
                      'upload_error': BX.message('upload_error'),
                      'access_denied': BX.message('access_denied')
                  }
              });
              showControl(status);
              window['BfileFD' + params['uid']].LoadDialogs('DropInterface');
              BX.onCustomEvent('BFileDSelectFileDialogLoaded', [window['BfileFD' + params['uid']]]);
          } else
              showControl(status);
      }
      window.BlogBFileJustDialog = function (arParams) {
          this.dialogName = 'AttachmentsDialog';
          this.agent = false;
  
          this.id = (!!arParams["id"] ? arParams["id"] : this.getID());
          this.controlID = arParams["id"];
          this.enabled = true;
          this.uploadFileUrl = arParams.upload_path; // from file.input php
  
          this.controller = (!!arParams.controller) ? arParams.controller : null;
          this.CID = arParams.CID;
  
          arParams.caller = this;
          arParams.doc_prefix = 'wd-doc';
          arParams._mkFileInput = BX.DoNothing
          arParams.mode = 'extended';
          arParams.classes = {
              'tpl_simple': 'file-simple',
              'tpl_extended': 'file-extended'
          };
  
          this.doc_prefix = arParams.doc_prefix;
  
          if (!!BX.FileUploadAgent) {
              this.agent = new BX.FileUploadAgent(arParams);
              BX.addCustomEvent(this, 'StopUpload', BX.delegate(this.StopUpload, this));
              BX.onCustomEvent(BX(this.controller.parentNode), "BFileDLoadFormControllerInit", [this]);
          } else {
              BX.debug('/bitrix/components/bitrix/main.file.input/templates/drag_n_drop/script.js: BX.FileUploadAgent is not defined.' +
                  ' You need to load /bitrix/js/main/file_upload_agent.js');
          }
      }
      window.BlogBFileJustDialog.prototype.StopUpload = function (agent, parent) {
          this.agent = agent;
          let id = false,
              mID = parent.id.match(new RegExp(this.doc_prefix + '(\\d+)'));
          if (!!mID) {
              id = mID[1];
          }
  
          if (this.controller && this.controller.parentNode)
              BX.onCustomEvent(this.controller.parentNode, 'OnFileUploadRemove', [id, this]);
  
          let data = {
              action: 'StopUploadFile',
              fileID: id,
              sessid: BX.bitrix_sessid(),
              cid: this.CID,
              controlID: this.controlID,
              mfi_mode: "delete",
              grid_id: 'uploadBasket',
          };
          BX.ajax.post(this.uploadFileUrl, data);
      }
      window.BlogBFileJustDialog.prototype.StopUpload = function (agent, parent) {
          this.agent = agent;
          let id = false,
              mID = parent.id.match(new RegExp(this.doc_prefix + '(\\d+)'));
          if (!!mID) {
              id = mID[1];
          }
  
          if (this.controller && this.controller.parentNode)
              BX.onCustomEvent(this.controller.parentNode, 'OnFileUploadRemove', [id, this]);
  
          let data = {
              action: 'StopUploadFile',
              fileID: id,
              sessid: BX.bitrix_sessid(),
              cid: this.CID,
              controlID: this.controlID,
              mfi_mode: "delete",
              grid_id: 'uploadBasket',
          };
          BX.ajax.post(this.uploadFileUrl, data);
      }
      window.BlogBFileDialog.prototype.repeatUpload = function (agent, parent) {
          this.agent = agent;
          let id = false,
              mID = parent.id.match(new RegExp(this.doc_prefix + '(\\d+)'));
          if (!!mID) {
              id = mID[1];
          }
  
          if (this.controller && this.controller.parentNode)
              BX.onCustomEvent(this.controller.parentNode, 'OnFileUploadRemove', [id, this]);
  
          let data = {
              action: 'RepeatUploadFile',
              fileID: id,
              sessid: BX.bitrix_sessid(),
              cid: this.CID,
              controlID: this.controlID,
              mfi_mode: "delete",
              grid_id: 'uploadBasket',
          };
          BX.ajax.post(this.uploadFileUrl, data);
      }
  
      window.MFIS = function (params) {
          if (!params['controller'].loaded) {
              params['controller'].loaded = true;
              top['BfileFD' + params['uid']] = window['BfileFD' + params['uid']] = new BlogBFileJustDialog({
                  'CID': params['CID'],
                  'id': params['id'],
                  'upload_path': params['upload_path'],
                  'controller': params['controller'],
                  'values': BX.findChildren(BX('file-selectdialog-' + params['uid']), {
                      "className": "file-inline-file"
                  }, true)
              });
              BX.fx.show(params['controller'], 'fade', {
                  time: 0.2
              });
              BX.onCustomEvent('BFileDSelectFileDialogLoaded', [window['BfileFD' + params['uid']]]);
          }
      }
  
      // TODO Переписать на bitirx api and BX.Vue
      jQuery(document).on("click", ".files-list .files-load>i", function () {
          window.load = jQuery(this);
          let id = jQuery(this).parents("tr").attr("id").replace("wd-doc", "");
          window.dataDivider = window.StringDataObj[id].result.delimiter;
          // $("textarea#excelPasteBox").val(window.StringDataObj[id].result.data).trigger('change');
      });
      // Смена номеров ячеек
      jQuery(document).on("change blur", "#col_code_num_input, #col_count_num_input, #col_barcode_num_input", function () {
          let col_code_num = jQuery("#col_code_num_input").val(),
              col_count_num = jQuery("#col_count_num_input").val(),
              col_barcode_num = jQuery("#col_barcode_num_input").val(),
              $error = jQuery("#col_num_error"),
              $button = jQuery("#checkFilesInDataTable");
          if (col_code_num == col_count_num || col_code_num == col_barcode_num || col_barcode_num == col_count_num) {
              $error.removeClass("d-none");
              $button.attr("disabled", true);
          } else {
              $error.addClass("d-none");
              $button.attr("disabled", false);
          }
      })
      // при удалении
      BX.addCustomEvent('OnFileUploadRemove', function (file_id, node) {
          delete window.StringDataObj[file_id];
          $("#wd-doc" + file_id).find('input[checked = "checked"]').removeAttr('checked');
          // let file_node = document.getElementById("wd-doc" + file_id);
          // file_node.parentNode.removeChild(file_node);
      });
  
      function setButtons(disabled = false) {
          var buttons = [
              BX("exportJsonData"),
              BX("checkTextInDataTable"),
              BX("checkFilesInDataTable")
          ];
          if (disabled) {
              for (let i = 0; i < buttons.length; i++) {
                  BX.addClass(buttons[i], "ui-btn-clock");
                  // BX.adjust(buttons[i], {props: {disabled: true}});
              }
          } else {
              for (let i = 0; i < buttons.length; i++) {
                  BX.removeClass(buttons[i], "ui-btn-clock");
                  // BX.adjust(buttons[i], { props: { disabled: false } });
              }
          }
      }
      BX.addCustomEvent('uploadStart', function () {
          setButtons(true);
      });
      // получаем данные с временнных файлов на сервере (из-за сложности разбора excel на js) и
      // добавляем массив в глобальную область и обновляем данные в результирующей таблице
      BX.addCustomEvent('OnFileUploadSuccess', function (data) {
          setButtons(false);
          if (data?.element_id) {
              data.AJAX = "Y";
              data.sessid = BX.bitrix_sessid();
              data.action = 'GetDataOfUploadedFile';
              BX.ajax({
                  url: '/local/components/germes/sale.cart.import/ajax.php',
                  method: 'POST',
                  data: data,
                  dataType: 'json',
                  async: true,
                  cache: true,
                  onsuccess: BX.proxy(function (res) {
                      debugger
                      if (res != undefined && res.error) {
                          data.error = res.error;
                          let file_row = BX("wd-doc" + data.element_id);
                          let file = BX.findChildren(file_row, {
                              "class": "f-wrap",
                              "tag": "span"
                          }, true);
                          let checkbox = BX.findChildren(file_row, {
                              "type": "checkbox",
                              "tag": "input"
                          }, true);
                          file[0].innerHTML += ' <span class="text-danger">(' + data.error + ')</span>';
                          checkbox[0].checked = false;
                          checkbox[0].disabled = true;
                          BX.UI.Notification.Center.notify({
                              content: data.error || '',
                              position: "top-center",
                              autoHideDelay: 5000,
                              closeButton: true,
                              category: "OnFileUploadSuccess-error",
                          });
                      } else if (res !== null && res["data"] !== undefined) {
                          if (window.StringDataObj === undefined || window.StringDataObj.constructor !== Array) { // если пуст или не массив
                              window.StringDataObj = [];
                          }
                          window.StringDataObj[data.element_id] = data;
                          window.StringDataObj[data.element_id]["result"] = res;
                          BX.UI.Notification.Center.notify({
                              content: 'Данные загружены',
                              position: "top-center",
                              autoHideDelay: 5000,
                              closeButton: true,
                              category: "OnFileUploadSuccess-success",
                          });
                      }
                  }, this),
                  onfailure: BX.proxy(function (data, error) {
                      BX.UI.Notification.Center.notify({
                          content: error ?? data,
                          position: "top-center",
                          autoHideDelay: 5000,
                          closeButton: true,
                          category: "checkDataTable-error",
                      });
                  }, this)
              });
          } else {
              BX.UI.Notification.Center.notify({
                  content: data || '',
                  position: "top-center",
                  autoHideDelay: 5000,
                  closeButton: true,
                  category: "OnBusketFileUploadFail",
              });
          }
      });
      // нотификация об ошибке загрузки файла
      BX.addCustomEvent('OnFileUploadFail', function (data) {
          BX.UI.Notification.Center.notify({
              content: data || '',
              position: "top-center",
              autoHideDelay: 5000,
              closeButton: true,
              category: "OnBusketFileUploadFail",
          });
      });
      //
      $(document).ready(function () {
          // отмена табуляции в текстовом поле
          $(document).on('keydown', 'textarea#excelPasteBox', function (e) {
              if (event.keyCode === 9) {
                  // Set up some variables. We need to know the current position of the cursor or selection.
                  var selectionStartPos = this.selectionStart;
                  var selectionEndPos = this.selectionEnd;
                  var oldContent = this.value;
                  // Set the new content.
                  this.value = oldContent.substring(0, selectionStartPos) + "\t" + oldContent.substring(selectionEndPos);
                  // Set the new cursor position (current position + 1 to account for the new tab character).
                  this.selectionStart = this.selectionEnd = selectionStartPos + 1;
                  // Prevent the default action (tabbing to the next field or control).
                  event.preventDefault();
              }
          });
          $(document).on('change', 'textarea#excelPasteBox', function (e) {
              e.preventDefault();
              if ("РАЗБИРАЕМ ДАННЫЕ") {
                  var cb;
                  var clipText = '';
                  if (e.type == "paste") {
                      if (window.clipboardData && window.clipboardData.getData) {
                          cb = window.clipboardData;
                          clipText = cb.getData('Text');
                      } else if (e.clipboardData && e.clipboardData.getData) {
                          cb = e.clipboardData;
                          clipText = cb.getData('text/plain');
                      } else {
                          cb = e.originalEvent.clipboardData;
                          clipText = cb.getData('text/plain');
                      }
                  } else {
                      clipText = $(this).val();
                  }
                  clipText = $(this).val();
                  parseDataToTable(clipText);
              }
          });
          jQuery.fn.pop = [].pop;
          jQuery.fn.shift = [].shift;
      });
      // загрузка данных в таблицу по кнопке
      jQuery(document).on('click', 'button#checkTextInDataTable', function () {
          checkTextInDataTable();
      });
      // загрузка данных в таблицу по кнопке
      jQuery(document).on('click', 'button#checkFilesInDataTable', function () {
          checkFilesInDataTable();
      });
      // очистка данных из таблицы по кнопке
      jQuery(document).on('click', 'button#clearDataTable', function () {
          jQuery('table#excelDataTable').find('tbody').remove();
          // window.StringDataObj = [];
          $('#output').parent().find("#print_output").addClass("d-none");
          $('#output').parent().find("#clearDataTable").addClass("d-none");
      });
      // загрузка данных на сервер по кнопке
      jQuery(document).on('click', 'button#exportJsonData', function () {
          debugger
          userStore?.dispatch("basket/getList", { limit: 10 })
              .then(result => {
                  debugger
                  // window.userBasketList
                  let $rows = jQuery('table#excelDataTable').find('tr:not(:hidden)'),
                      userBasketList = result,
                      headers = [],
                      jsonString = "",
                      data = [];
                  // Собираем заголовки
                  if ($rows != undefined) {
                      jQuery('#exportJsonDataAlert').html("");
                      let header = $rows[0];
                      if (header != undefined) {
                          header = $(header).find('th:not(:empty):not([data-attr-ignore])');
                          if (header != undefined) {
                              header.each(function () {
                                  headers.push(jQuery(this).text().toLowerCase());
                              });
                          }
                      } else {
                          header = $rows.find('th:not(:empty):not([data-attr-ignore])');
                          if (header != undefined) {
                              header.each(function () {
                                  headers.push(jQuery(this).text().toLowerCase());
                              });
                          }
                      }
                  }
                  if ($rows.length < 2) {
                      jQuery('#exportJsonDataAlert').html("Нет данных для загрузки");
                      return !1;
                  }
                  $rows.each(function () {
                      let $td = jQuery(this).find('td:not([data-attr-ignore])'),
                          h = {};
                      headers.forEach(function (header, i) {
                          h[i] = $td.eq(i).text();
                      });
                      data.push(h);
                  });
                  window.data = data;
                  Vue.set(insertBasket, 'insertData', data);
                  jsonString = JSON.stringify(data, null, 2);
                  jQuery('textarea#jsonDataDump').val(jsonString);
                  window.jsonString = jsonString;
                  // debugger
                  Confirmer.show();
                  if (window.data.length > 0) {
                      let content = '';
                      content += `<div>
                          Хотите создать новую корзину и добавить туда товары или добавить в текущую?`;
                      content += `<select>
                              <option value="">+ Ноавя корзина</option>`;
                      if (userBasketList) {
                          for (let id in userBasketList) {
                              let contragentName = (userBasketList[id]?.CONTRAGENT?.NAME ?? ""),
                                  addressName = (userBasketList[id]?.ADDRESS?.NAME ?? "")
                              content += `<option value="` + id + `">`
                                  + ` #` + id
                                  + (contragentName || addressName ? ' (' + contragentName + ' ' + addressName + ')' : '')
                                  + `</option>`;
                          };
                      }
                      content += `</select>
                      </div>`;
                      Confirmer.show();
                  } else {
                      // AlertWindow.show();
                  }
              }, reject => {
                  debugger
                  throw reject
              }).catch(error => {
                  debugger
                  console.error(error)
              });
      });
      // Проверяем какие файлы должны быть в таблице
      function checkFilesInDataTable() {
          window.arrayData = [];
          window.StringData = "";
          let $cheked = $("table.files-list").find(".files-load input:checked");
          if ($cheked.length) {
              $cheked.each(function (i, item) {
                  var file_id = $(item).parents("tr").attr("id").replace("wd-doc", "");
                  if (window.StringDataObj?.[file_id]?.result?.data) {
                      let tmp = [];
                      if (window.StringDataObj[file_id].result.array) {
                          tmp = filterColFromArray(window.StringDataObj[file_id].result.array)
                      } else {
                          window.StringData += '\n' + window.StringDataObj[file_id].result.data;
                          tmp = parseStringToArray(window.StringDataObj[file_id].result.data, window.StringDataObj[file_id].result.dataDivider);
                      }
                      window.arrayData = window.arrayData.concat(tmp);
                  }
              });
              if (window.arrayData.length) {
                  writeTable(window.arrayData);
              } else if (window.StringData !== "" && typeof window.StringData !== 'undefined') {
                  parseDataToTable(window.StringData, true);
              } else {
                  BX.UI.Notification.Center.notify({
                      content: "Ещё секунду, мы сохраняем файл...",
                      position: "top-center",
                      autoHideDelay: 3000,
                      closeButton: true,
                      category: "multibasket-import-error",
                  });
              }
          } else {
              BX.UI.Notification.Center.notify({
                  content: "Сначала загрузите файлы или текст в '#1 Загрузка данных'.",
                  position: "top-center",
                  autoHideDelay: 3000,
                  closeButton: true,
                  category: "multibasket-import-error",
              });
          }
      }
      // строку в массив
      function filterColFromArray(tableArray) {
          if (!tableArray?.length) return []
          let tableData = [],
              col_code_num = $("#col_code_num_input").val() -1,
              col_count_num = $("#col_count_num_input").val() -1,
              col_barcode_num = $("#col_barcode_num_input").val() -1;
          const loader = '<div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div>';
          tableArray.forEach(row => {
              if (row[col_code_num]
                  && parseFloat(row[col_count_num])
              ) {
                  if ((row[col_code_num] != '' && row[col_code_num] != '-')
                      ||
                      (row[col_barcode_num] != '' && row[col_barcode_num] != '-')
                  ) {
                      tableData.push({
                          0: row[col_code_num],
                          1: row[col_barcode_num],
                          2: row[col_count_num],
                          3: loader
                      });
                  }
              }
          });
          return tableData
      }
      // строку в массив
      function parseStringToArray(string, data_divider = ';') {
          let clipText = "",
              clipRows = "",
              clipRows_new = [],
              jsonObj_new = [],
              jsonObj = [],
              delN = false;
          if ("УБИРАЕМ ПЕРЕНОСЫ В МНОГОСТРОЧНЫХ ЯЧЕЙКАХ" && string) {
              let clip = string;
              for (let i in clip) {
                  if (clip[i] == '"' && clip[i + 1] != '"') {
                      delN = !delN;
                  }
                  if (clip[i] == "\n" && delN) {
                      clipText += " ";
                      continue;
                  }
                  clipText += clip[i];
              }
          }
          if ("РАЗБИРАЕМ СТРОКИ" && clipText) {
              clipText += "\n";
              clipRows = clipText.split('\n');
              let delimiter = data_divider || '[;|,|	|\\s]';
              delimiter = new RegExp(delimiter);
              for (let i = 0; i < clipRows.length; i++) {
                  if (clipRows[i].trim() != "") { // не пишем пустые строки
                      clipRows_new.push(clipRows[i].trim().split(delimiter));
                  }
              }
              clipRows = clipRows_new;
              for (let i = 0; i < clipRows.length; i++) {
                  let item = {};
                  for (let j = 0; j < clipRows[i].length; j++) {
                      if (clipRows[i][j] != '\r') {
                          if (clipRows[i][j].length !== 0) {
                              item[j] = clipRows[i][j];
                          }
                      }
                      if (item[j] == 'undefined') item[j] = '';
                  }
                  jsonObj.push(item);
              }
          }
          const loader = '<div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div>';
          if (jsonObj != undefined) {
              if ("ОСТАВЛЯЕМ НУЖНЫЕ КОЛОНКИ") {
                  let col_code_num = $("#col_code_num_input").val(),
                      col_count_num = $("#col_count_num_input").val(),
                      col_barcode_num = $("#col_barcode_num_input").val();
                  if (col_code_num != undefined) col_code_num -= 1;
                  if (col_count_num != undefined) col_count_num -= 1;
                  if (col_barcode_num != undefined) col_barcode_num -= 1;
                  BX.setCookie('col_code_num', col_code_num, {
                      expires: 7862400
                  }); // на 3 месяца добавить {, secure: true} для ssl
                  BX.setCookie('col_count_num', col_count_num, {
                      expires: 7862400
                  }); // на 3 месяца добавить {, secure: true} для ssl
                  BX.setCookie('col_barcode_num', col_barcode_num, {
                      expires: 7862400
                  }); // на 3 месяца добавить {, secure: true} для ssl
                  jsonObj.forEach(element => {
                      if (element[col_code_num] && parseFloat(element[col_count_num])) {
                          if ((element[col_code_num] != '' && element[col_code_num] != '-') || (element[col_barcode_num] != '' && element[col_barcode_num] != '-'))
                              jsonObj_new.push({
                                  0: element[col_code_num],
                                  1: element[col_barcode_num],
                                  2: element[col_count_num],
                                  3: loader
                              });
                      }
                  });
                  jsonObj = jsonObj_new;
              } else {
                  jsonObj.forEach(element => {
                      if (element[0] != '' && element[0] != '-')
                          if (Object.keys(element).length == 2) {
                              jsonObj_new.push({
                                  0: element[0],
                                  1: '',
                                  2: element[1],
                                  3: loader
                              });
                          } else {
                              jsonObj_new.push({
                                  0: element[0],
                                  1: element[1],
                                  2: element[2],
                                  3: loader
                              });
                          }
                  });
                  jsonObj = jsonObj_new;
              }
          }
          return jsonObj;
      }
      // Разбор строк и передача в таблицу данных
      var loader = '<div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div>';
  
      function parseDataToTable(StringData, $use_custom_col, dataDivider) {
          let clip = StringData,
              clipText = "",
              delN = false;
          if ("УБИРАЕМ ПЕРЕНОСЫ В МНОГОСТРОЧНЫХ ЯЧЕЙКАХ" && StringData) {
              for (let i in clip) {
                  if (clip[i] == '"' && clip[i + 1] != '"') {
                      delN = !delN;
                  }
                  if (clip[i] == "\n" && delN) {
                      clipText += " ";
                      continue;
                  }
                  clipText += clip[i];
              }
          }
          if (clipText) {
              clipText += "\n";
              let clipRows = clipText.split('\n');
              let delimiter = new RegExp(dataDivider || ';');
              let clipRows_new = [];
              for (let i = 0; i < clipRows.length; i++) {
                  var clipRow = clipRows[i].trim();
                  if (clipRow != "") { // не пишем пустые строки
                      if (/\s|\t/ig.test(clipRow)) {
                          // есть пробелы - они разделитель
                          clipRow = clipRow.replace(/(\t|	|\s|\;)+/ig, ";");
                      } else if (/\w\;|(\d\,\d)|(\d\.\d)/ig.test(clipRow)) {
                          // нет проблелов но есть разделители чисел - делим по другим символам
                          clipRow = clipRow.replace(/(\t|	|\s|\;)+/ig, ";");
                      } else {
                          // делим по , или ;
                          clipRow = clipRow.replace(/(\,|\;)+/ig, ";");
                      }
                      clipRows_new.push(clipRow.trim().split(delimiter));
                  }
              }
              clipRows = clipRows_new;
              let jsonObj = [];
              for (let i = 0; i < clipRows.length; i++) {
                  var item = {};
                  for (let j = 0; j < clipRows[i].length; j++) {
                      if (clipRows[i][j] != '\r') {
                          if (clipRows[i][j].length !== 0) {
                              item[j] = clipRows[i][j];
                          }
                      }
                      if (item[j] == 'undefined') item[j] = '';
                  }
                  jsonObj.push(item);
              }
              if ("Исправляем данные" && jsonObj.length && $use_custom_col) {
                  let col_code_num = $("#col_code_num_input").val(),
                      col_count_num = $("#col_count_num_input").val(),
                      col_barcode_num = $("#col_barcode_num_input").val();
                  BX.setCookie('col_code_num', col_code_num, {
                      expires: 7862400
                  }); // на 3 месяца добавить {, secure: true} для ssl
                  BX.setCookie('col_count_num', col_count_num, {
                      expires: 7862400
                  }); // на 3 месяца добавить {, secure: true} для ssl
                  BX.setCookie('col_barcode_num', col_barcode_num, {
                      expires: 7862400
                  }); // на 3 месяца добавить {, secure: true} для ssl
                  var jsonObj_new = [];
                  jsonObj.forEach(element => {
                      jsonObj_new.push({
                          0: element[col_code_num - 1],
                          1: element[col_barcode_num - 1],
                          2: element[col_count_num - 1],
                          3: loader
                      });
                  });
                  jsonObj = jsonObj_new;
              } else {
                  var jsonObj_new = [];
                  jsonObj.forEach(element => {
                      if (Object.keys(element).length == 2) {
                          jsonObj_new.push({
                              0: element[0],
                              1: '',
                              2: element[1]?.replace(",", "."),
                              3: loader
                          });
                      } else {
                          jsonObj_new.push({
                              0: element[0],
                              1: element[1],
                              2: element[2]?.replace(",", "."),
                              3: loader
                          });
                      }
                  });
                  jsonObj = jsonObj_new;
              }
              writeTable(jsonObj);
          } else {
  
          }
      }
      //
      function writeTable(jsonObj) {
          if ("СОЗДАЁМ ТАБЛИЦУ" && jsonObj) {
              var tablePlaceHolder = document.getElementById('output');
              tablePlaceHolder.innerHTML = '';
              var customAttributeWriter = function (record) {
                  // `this` is the column object in settings.columns
                  // TODO: automatically convert common types, such as arrays and objects, to string
                  return record[this.index] || "-";
                  // return record[this.id]||""; // вариант по умолчанию
              };
              var customCellWriter = function (column, record) {
                  var html = column.attributeWriter(record),
                      td = '<td';
                  if (column.hidden || column.textAlign) {
                      td += ' style="';
                      if (column.hidden) {
                          td += 'display: none;';
                      }
                      if (column.textAlign) {
                          td += 'text-align: ' + column.textAlign + ';';
                      }
                      td += '"';
                  }
                  return td + '><div>' + html + '<\/td>';
              };
              var makeElementEditable = function (element) {
                  $('div', element).attr('contenteditable', true);
                  $(element).focusout(function () {
                      $('div', element).attr('contenteditable', false);
                  });
                  $(element).keydown(function (e) {
                      if (e.which == 13) {
                          e.preventDefault();
                          $('div', element).attr('contenteditable', false);
                          $(document).focus();
                      }
                  });
                  $('div', element).on('paste', function (e) {
                      // e.preventDefault();
                  });
              };
              let table = document.createElement('table');
              table.id = 'excelDataTable';
              table.className = 'table table-hover';
              let header = table.createTHead(),
                  row = header.insertRow(0),
                  notEmptyColIndex = [];
              for (let i = 0; i < jsonObj.length; i++) {
                  var obj = jsonObj[i];
                  for (let j in obj) {
                      if ($.inArray(j, notEmptyColIndex) == -1) {
                          notEmptyColIndex.push(j);
                      }
                      let val = obj[j];
                      if (obj[j] == undefined) {
                          jsonObj[i][j] = "";
                      }
                  }
              }
              if ("СТАВИМ ЗАГОЛОВОК ТАБЛИЦЫ ДЛЯ ПЛАГИНА") {
                  const colName = ["Код", "Штрихкод", "Количество", "Статус / Цена"];
                  notEmptyColIndex.forEach(function (value, index) {
                      let headerCell = document.createElement('th');
                      headerCell.innerHTML = '<div>' + (colName[value] || "-") + '<\/div>';
                      if (value != 2) {
                          $(headerCell).click(function () {
                              makeElementEditable(this);
                          });
                          $(headerCell).keyup(function (e) {
                              let ignoredClass = 'ignored',
                                  ignoredAttr = 'data-attr-ignore',
                                  columnCells = $('td, th', table)
                                      .filter(':nth-child(' + ($(this).index() + 1) + ')');
                              $(this).removeAttr(ignoredAttr);
                              $(columnCells).each(function () {
                                  $(this).removeClass(ignoredClass);
                                  $(this).removeAttr(ignoredAttr);
                              });
                              if ($(this).is(':empty') || $(this).text().trim() === '') {
                                  $(this).attr(ignoredAttr, '');
                                  $(columnCells).each(function () {
                                      $(this).addClass(ignoredClass);
                                      $(this).attr(ignoredAttr, '');
                                  });
                              }
                          });
                      }
                      let cell = row.insertCell(index);
                      cell.parentNode.insertBefore(headerCell, cell);
                      cell.parentNode.removeChild(cell);
                  });
              }
              tablePlaceHolder.appendChild(table);
              // используем внешний плагин для редактора таблиц
              // используем внешний плагин для динамической таблицы
              $('table#excelDataTable').DataTable({
                  language: {
                      "url": "//cdn.datatables.net/plug-ins/1.10.19/i18n/Russian.json",
                      /* "processing": "Подождите...",
                      "search": "Поиск:",
                      "lengthMenu": "Показать _MENU_ записей",
                      "info": "Записи с _START_ до _END_ из _TOTAL_ записей",
                      "infoEmpty": "Записи с 0 до 0 из 0 записей",
                      "infoFiltered": "(отфильтровано из _MAX_ записей)",
                      "infoPostFix": "",
                      "loadingRecords": "Загрузка записей...",
                      "zeroRecords": "Записи отсутствуют.",
                      "emptyTable": "В таблице отсутствуют данные",
                      "paginate": {
                          "first": "Первая",
                          "previous": "Предыдущая",
                          "next": "Следующая",
                          "last": "Последняя"
                      },
                      "aria": {
                          "sortAscending": ": активировать для сортировки столбца по возрастанию",
                          "sortDescending": ": активировать для сортировки столбца по убыванию"
                      } */
                  },
                  keys: {
                      // editor: editor,
                      editOnFocus: false
                  },
                  fixedHeader: false,
                  data: jsonObj,
                  searching: false,
                  paging: false,
                  ordering: true,
                  order: [
                      [2, "desc"]
                  ],
                  info: false,
                  select: {
                      style: 'os',
                      selector: 'td:first-child'
                  },
              });
              $('table#excelDataTable').on('click', 'tr', function () {
                  $(this).toggleClass('selected');
              });
              window.jsonObj = jsonObj;
              checkDataTable(jsonObj);
              /* $('#button').click( function () {
                  alert( table.rows('.selected').data().length +' row(s) selected' );
              } ); */
              /* var excelDynaTable = $('table#excelDataTable').dynatable({
                  features: {
                      paginate: false,
                      search: false,
                      recordCount: false,
                      sort: false
                  },
                  dataset: {
                      records: jsonObj
                  },
                  writers: {
                      _cellWriter: customCellWriter,
                      _attributeWriter: customAttributeWriter,
                  }
              }); */
              $('#output').parent().find("#print_output").removeClass("d-none");
              $('#output').parent().find("#clearDataTable").removeClass("d-none");
          }
          $(document).on('click', 'table#excelDataTable td', function () {
              makeElementEditable(this);
          });
      }
      // проверяем TEXT данные
      function checkTextInDataTable() {
          let clipText = $("textarea#excelPasteBox").val();
          if (clipText) {
              parseDataToTable(clipText);
          }
      }
  
      function getObjHash(obj) {
          let str = JSON.stringify(obj),
              hash = 0;
          str = String(str);
          if (str.length == 0) return hash;
          for (let i = 0; i < str.length; i++) {
              hash = ((hash << 5) - hash) + str.charCodeAt(i);
              hash = hash & hash; // Convert to 32bit integer
          }
          return hash;
      }
      // проверяем данные запросом к серверу
      function checkDataTable(jsonObj) {
          debugger
          let basketUrl = '/local/components/germes/sale.cart.import/ajax.php', // window.location.pathname,
              basketParams = {
                  AJAX: "Y",
                  action: "BASKET_IMPORT_CHECK",
                  sessid: BX.bitrix_sessid(),
                  basket: jsonObj,
                  basket_hash: getObjHash(jsonObj)
              };
          window.data_Hash = basketParams.basket_hash
          BX.ajax({
              url: basketUrl,
              method: 'POST',
              data: basketParams,
              dataType: 'json',
              async: true,
              cache: true,
              onsuccess: BX.proxy(function (data) {
                  debugger
                  let arItems = data?.arItems;
                  if (!arItems) throw 'Ничего не нашли!'
                  if (data?.success !== undefined) {
                      for (let key in data.success) {
                          let element = data.success[key],
                              element_code = element[0],
                              element_barcode = element[1];
                          window.jsonObj.map(function (searchedItem) {
                              if ((element_code && searchedItem[0] == element_code) || (element_barcode && (searchedItem[0] == element_barcode || searchedItem[1] == element_barcode))) {
                                  let $price = "Определён!",
                                      arItem = arItems[element_code.toUpperCase()],
                                      quantity = isNaN(searchedItem[2]) ? 0 : searchedItem[2];
                                  if (arItem && arItem.PRICE) {
                                      $price = arItem.PRICE;
                                  }
                                  if (searchedItem[0] == element_barcode || (searchedItem[0] != element_code && searchedItem[1] == element_barcode)) {
                                      searchedItem[0] = element_code;
                                      searchedItem[1] = element_barcode;
                                  }
                                  searchedItem[3] = '<i class="fas fa-check-circle text-success" title="Товар по коду найден!"></i> ' + '<span title="цена за ' + quantity + ' ед.">' + (($price * quantity).toFixed(2)) + '</span>';
                                  return searchedItem;
                              }
                          });
                      }
                  }
                  if (data?.error !== undefined) {
                      for (let key in data.error) {
                          let element = data.error[key],
                              element_code = element[0];
                          window.jsonObj.map(function (searchedItem) {
                              if (searchedItem[0] == element_code) searchedItem[3] = '<i class="fas fa-exclamation-triangle text-danger" title="Товар по коду не найден!"></i> Код не найден!';
                              return searchedItem;
                          });
                      }
                  }
                  if (window.jsonObj?.length) {
                      BX.UI.Notification.Center.notify({
                          content: 'Данные обработаны',
                          position: "top-center",
                          autoHideDelay: 5000,
                          closeButton: true,
                          category: "checkDataTable-success",
                      });
                      $('table#excelDataTable').DataTable().clear().rows.add(window.jsonObj).draw();
                  } else {
                      throw 'Ошибка обработки ответа сервера!'
                  }
              },this),
              onfailure: BX.proxy(function (data, error) {
                  debugger
                  BX.UI.Notification.Center.notify({
                      content: error ?? data,
                      position: "top-center",
                      autoHideDelay: 5000,
                      closeButton: true,
                      category: "checkDataTable-error",
                  });
              }, this)
          });
      }
      var Confirmer = null,
          AlertWindow = null,
          insertBasket = null;
      BX.ready(function () {
          // Создание визуального результата из поля ввода в виде таблицы
          window.basketResultWindow = new BX.PopupWindow("basketResult-message", null, {
              lightShadow: true,
              width: 400, // ширина окна
              content: `<div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div>`,
              closeIcon: {
                  right: "20px",
                  top: "10px"
              },
              titleBar: {
                  content: BX.create("span", {
                      html: '<h1 class="h4 py-2 text-center">...</h1>',
                      'props': {
                          'className': 'basketResult-title-bar'
                      }
                  })
              },
              zIndex: 0,
              offsetLeft: 0,
              offsetTop: 0,
              draggable: {
                  restrict: false
              },
              closeByEsc: true, // закрытие окна по esc
              // darkMode: true,
              overlay: true,
              autoHide: true,
              buttons: [
                  new BX.PopupWindowButton({
                      text: Loc.getMessage('LOAD_MORE'),
                      className: "popup-window-button-accept",
                      events: {
                          click: function () {
                              this.popupWindow.close();
                          }
                      }
                  }),
                  new BX.PopupWindowButton({
                      text: Loc.getMessage('SHOW_CART'),
                      className: "popup-window-button-accept",
                      events: {
                          click: function () {
                              BX.onCustomEvent('OnBasketImportGoToBasket');
                              this.popupWindow.close();
                          }
                      }
                  }),
              ]
          });
          let insertBasketNode = BX.create('div', {
              props: {
                  id: 'insertBasket',
              },
              attrs: {
                  className: 'insertBasketClass',
              },
              html: `
                      <section v-if="insertData.length" class="filter form-row row">
                          <div class="col-12">
                              <div class="row">
                              <div class="col col-sm-4 font-weight-bold">{{ title }}</label></div>
                      		<div class="col">
                      			<input id="basket_type_new" type="radio" name="basket_type" value="new" @change="onChangeParams" v-model="importType" placeholder="Выберите тип вставки" class="border-none" checked>
                                  <label class="inline-imput" for="basket_type_new">
                      				<span> {{mess.new}} </span>
                                  </label>
                      			<i> {{mess.newinfo}}</i>
                      			<input id="basket_type_real" type="radio" name="basket_type" value="real" @change="onChangeParams" v-model="importType" placeholder="Выберите тип вставки" class="border-none">
                                  <label class="inline-imput" for="basket_type_real">
                      				<span> {{mess.real}}</span>
                                  </label>
                              </div>
                          </div>
                          <div class="row">
  	                        <div class="col">
  	                		<br>
  	                		Параметры для заказа
                              <hr>
  	                        </div>
                          </div>
                          <div class="row">
                              <div v-if="importType == 'real'" class="col-12">
                                  <label class="w-100">{{mess.baskets}}:
                                      <select @change="onChangeParams"
                                          v-model="basket_id"
                                          :placeholder="mess.baskets"
                                          v-bind:size= "baskets.length < 10 ? baskets.length : 10"
                                          name="selectBasket"
                                          class="form-control">
                                          <option disabled hidden value="">{{mess.baskets}}</option>
                                          <option v-for="basket in baskets" :value="basket.ID">
                                              {{ basket.ID == active_basket_id ? mess.active+' ' : '&nbsp;&nbsp;' }}
                                              {{ basket.ACCOUNT_NUMBER }}
                                              {{ basket.CONTRAGENT && basket.CONTRAGENT.NAME ? basket.CONTRAGENT.NAME : "" }}
                                              {{ basket.ADDRESS && basket.ADDRESS.NAME ? '('+basket.ADDRESS.NAME+')' : "" }}
                                              {{ basket.USER.ID !== user_id ? '(общая)' : ''}}
                                          </option>
                                      </select>
                                      <div v-if="basket_id && baskets[basket_id]">
                                          <div>{{mess.selectedBasket}}:{{mess.id}} {{ baskets[basket_id].ACCOUNT_NUMBER }}</div>
                                          <div v-if="baskets[basket_id].CONTRAGENT && baskets[basket_id].CONTRAGENT.NAME">{{mess.contragent}}: {{ baskets[basket_id].CONTRAGENT.NAME }}</div>
                                          <div v-if="baskets[basket_id].ADDRESS && baskets[basket_id].ADDRESS.NAME">{{mess.address}}: {{ baskets[basket_id].ADDRESS.NAME }}</div>
                                          <div v-if="baskets[basket_id].COUNT">{{mess.items_count}}: {{ baskets[basket_id].COUNT }}</div>
                                          <div v-if="baskets[basket_id].SUMM_PRICE">{{mess.items_summ}}: {{ baskets[basket_id].SUMM_PRICE }}</div>
                                          <div v-if="baskets[basket_id].USER">{{mess.user}}: {{ baskets[basket_id].USER.LAST_NAME+' '+baskets[basket_id].USER.NAME+'('+baskets[basket_id].USER.LOGIN+')' }}</div>
                                      </div>
                                  </label>
                              </div>
                              <div v-if="importType != 'real'" class="col-12">
                                  <label v-if="contragents" class="w-100">
                      				<i class="fas fa-users"></i> {{mess.contragents}}
                                  </label>
                                      <select @change="onChangeParams"
                                          v-model="contragent_id"
                                          :placeholder="mess.contragents"
                                          name="contragent_id"
                                          class="form-control mb-3">
                                          <option disabled value="" hidden>{{mess.contragents}}</option>
                                          <option v-for="contragent in contragents" v-bind:value="contragent.ID">
                                              {{ contragent.NAME }}
                                          </option>
                                      </select>
                                  <label v-if="contragent_id && contragents[contragent_id] && contragents[contragent_id].ADDRESS" class="w-100">
                      				<i class="fas fa-map-marker-alt"></i> {{mess.address}}
                                  </label>
                                      <select @change="onChangeParams"
                                          v-model="address_id"
                                          :placeholder="mess.address"
                                          name="address_id"
                                          class="form-control mb-3">
                                          <option v-if="addresslength==1" disabled hidden value="">{{mess.selectaddress}}</option>
                                          <option v-else value="" hidden>{{mess.selectaddress}}</option>
                                          <option v-for="address in contragents[contragent_id].ADDRESS" v-bind:value="address.ID">
                                              {{ address.NAME }}
                                          </option>
                                      </select>
                              </div>
                          </div>
                      </section>
                      <section v-else>
                          {{ emptyTitle }}
                      </section>
                  `
          });
          Confirmer = BX.PopupWindowManager.create("basketConfirmer-message", null, {
              width: 580, // ширина окна
              content: insertBasketNode,
              closeIcon: {
                  right: "20px",
                  top: "10px"
              },
              titleBar: {
                  content: BX.create("span", {
                      html: '<h1 class="h4 py-2 text-center font-weight-bold">Загрузка номенклатуры в заказ-корзину</h1>',
                      'props': {
                          'className': 'basketConfirmer-title-bar'
                      }
                  })
              },
              zIndex: 0,
              offsetLeft: 0,
              offsetTop: 0,
              draggable: {
                  restrict: false
              },
              closeByEsc: false, // закрытие окна по esc
              // darkMode: true,
              // lightShadow : true,
              // overlay: {backgroundColor: 'black', opacity: '80' },
              overlay: true,
              autoHide: true,
              buttons: [
                  new BX.PopupWindowButton({
                      text: ' добавить',
                      className: "popup-window-button-accept",
                      events: {
                          click: function () {
                              let basketUrl = '/local/components/germes/sale.cart.import/ajax.php',
                                  basketParams = {
                                      'AJAX': 'Y',
                                      'basket': window.data,
                                      'basket_hash': window.data_Hash,
                                  };
                              if (insertBasket) {
                                  basketParams.importType = insertBasket.importType;
                                  if (insertBasket.importType == 'new') {
                                      basketParams.contragent = insertBasket.contragent_id;
                                      if (!insertBasket.address_id) {
                                          BX.UI.Notification.Center.notify({
                                              content: 'Не указан адрес доставки!',
                                              position: "top-center",
                                              autoHideDelay: 5000,
                                              closeButton: true,
                                              category: "OnFileUploadSuccess-error",
                                          });
                                          return false;
                                      }
                                      basketParams.address = insertBasket.address_id;
                                  } else {
                                      basketParams.basket_id = insertBasket.basket_id;
                                  }
                              }
                              window.test_data = null;
                              basketParams.action = "BASKET_IMPORT";
                              window.basketResultWindow.contentContainer.innerHTML = "<div style='text-align:center;'>" + loader + "</div>";
                              window.basketResultWindow.titleBar.innerHTML = '<span class="basketResult-title-bar"><h1 class="h4 py-2 text-center">Обработка...</h1></span>';
                              window.basketResultWindow.buttonsContainer.style.display = 'none';
                              window.basketResultWindow.show();
                              BX.ajax({
                                  method: 'POST',
                                  dataType: 'json',
                                  url: basketUrl,
                                  timeout: 600,
                                  data: basketParams,
                                  onsuccess: BX.proxy(function (data) {
                                      if (data && data.content) {
                                          // TODO доработать до красивого варианта
                                          if (data.answer && data.baskets && data.baskets[data.answer]) {
                                              let userBasket = data.baskets[data.answer];
                                              if (userStore && data.basket) {
                                                  userStore.commit('basket/setBasket', data.basket);
                                              } else {
                                                  window.user_basket = userBasket;
                                              }
                                          } else if (data.answer && data.basket) {
                                              if (userStore && data.basket) {
                                                  userStore.commit('basket/setBasket', data.basket);
                                              } else {
                                                  window.user_basket = data.basket;
                                              }
                                          }
                                          // BX.onCustomEvent('OnBasketImportDone');
                                          BX.onCustomEvent('OnBasketChange');
                                          // TODO вынести в настройки
                                          ym(57490780, 'reachGoal', 'basketImport');
                                          // BX.onCustomEvent('OnSwitchBasket');
                                          if (BX.UI.Notification != undefined) {
                                              BX.UI.Notification.Center.notify({
                                                  content: "Загрузка завершена",
                                                  position: "top-center",
                                                  autoHideDelay: 5000,
                                                  closeButton: true,
                                                  category: "basket-import-info",
                                              });
                                          }
                                          window.basketResultWindow.contentContainer.innerHTML = "<div>" + data.content + "</div>";
                                          window.basketResultWindow.titleBar.innerHTML = '<span class="basketResult-title-bar"><h1 class="h4 py-2 text-center">Загрузка завершена</h1></span>';
                                          window.basketResultWindow.buttonsContainer.style.display = 'block';
                                          window.basketResultWindow.show();
                                      } else if (data == null) {
                                          throw BX.message("EMPTY_SERVER_RESPONSE")
                                      } else if (data?.error) {
                                          let error = BX.message("EMPTY_SERVER_RESPONSE")
                                          if (data?.error) error = BX.message(data.error.replace(/[-'`~!@#$%^&*()_|+=?;:'",.<>\{\}\[\]\\\/]/gi, '_')?.toUpperCase()) ?? data.error;
                                          throw error;
                                      } else {
                                          window.basketResultWindow.contentContainer.innerHTML = "<div>" + data + "</div>";
                                          window.basketResultWindow.titleBar.innerHTML = '<span class="basketResult-title-bar"><h1 class="h4 py-2 text-center">Ошибка при обработке!</h1></span>';
                                          window.basketResultWindow.buttonsContainer.style.display = 'block';
                                          window.basketResultWindow.show();
                                      }
  
                                      window.data = null;
                                      window.test_data = null;
                                      $("#file-selectdialog-mfiNAME_INPUT .files-list").find("tr").each(function () {
                                          var file_id = this.id.replace('wd-doc', '');
                                          delete window.StringDataObj[file_id];
                                          delete $(this).remove();
                                      });
                                      $("textarea#excelPasteBox").val("");
                                      $('table#excelDataTable').find('tbody').remove();
                                  }, this),
                                  onfailure: BX.proxy(function (error, text) {
                                      // BX.onCustomEvent('OnBasketImportDone');
                                      BX.onCustomEvent('OnBasketChange');
                                      window.basketResultWindow.contentContainer.innerHTML = "<div>" + error + ": " + text + "</div>";
                                      window.basketResultWindow.titleBar.innerHTML = '<span class="basketResult-title-bar"><h1 class="h4 py-2 text-center">Ошибка при загрузке!</h1></span>';
                                      window.basketResultWindow.buttonsContainer.style.display = 'block';
                                      window.basketResultWindow.show();
                                  }, this),
                              });
                              this.popupWindow.close();
                          }
                      }
                  }), new BX.PopupWindowButton({
                      text: ' Отменить',
                      className: "webform-button-link-cancel",
                      events: {
                          click: function () {
                              this.popupWindow.close();
                          }
                      }
                  })
              ],
              events: {
                  onPopupShow: function () {
                      if (!BX.findChild(BX("basketConfirmer-message"), {
                          "className": 'fa-cart-plus'
                      }, true)) {
                          BX.prepend(BX.create("i", {
                              html: ' ',
                              'props': {
                                  'className': 'fas fa-cart-plus'
                              }
                          }), BX.findChild(BX("basketConfirmer-message"), {
                              "className": 'popup-window-button-accept'
                          }, true));
                          BX.prepend(BX.create("i", {
                              html: ' ',
                              'props': {
                                  'className': 'fas fa-close'
                              }
                          }), BX.findChild(BX("basketConfirmer-message"), {
                              "className": 'webform-button-link-cancel'
                          }, true));
                      }
                  },
                  onPopupClose: function () {
                      // Событие при закрытии окна
                  }
              }
          });
          AlertWindow = BX.PopupWindowManager.create("basketAlert-message", null, {
              width: 400, // ширина окна
              closeIcon: {
                  right: "20px",
                  top: "10px"
              },
              titleBar: {
                  content: BX.create("span", {
                      html: '<h1 class="h4 py-2 text-center">Нет данных</h1>',
                      'props': {
                          'className': 'basketConfirmer-title-bar'
                      }
                  })
              },
              content: "<div>Сначала загрузите данные.</div>",
              zIndex: 0,
              offsetLeft: 0,
              offsetTop: 0,
              draggable: {
                  restrict: false
              },
              closeByEsc: true, // закрытие окна по esc
              // darkMode: true,
              // lightShadow : true,
              // overlay: {backgroundColor: 'black', opacity: '80' },
              overlay: true,
              autoHide: true
          });
          // TODO это временно, перенести в компоненты
          let requestCartId = BX.Sale.CartImportComponent.result?.VARIABLES?.ID;
          insertBasket = BX.Vue.createApp({
              el: '#insertBasket',
              store: userStore,
              data() {
                  return {
                      requestCartId: requestCartId,
                      user_basket_id: null,
                      user_contragent_id: null,
                      user_address_id: null,
                      importType: "new",
                      insertData: [],
                      title: 'Добавим данные в:',
                      emptyTitle: 'Вы ещё не внесли данные в п.2',
                      mess: {
                          id: '№',
                          // active: '(активная)',
                          active: '•',
                          selectedBasket: 'Выбрана корзина',
                          items_count: 'Товаров в корзине',
                          items_summ: 'Итого в корзине',
                          contragents: 'Контрагенты',
                          contragent: 'Контрагент',
                          address: 'Адрес доставки',
                          selectaddress: 'Выберите адрес доставки',
                          baskets: 'Корзины (10 последних активных)',
                          user: 'Владелец',
                          new: 'новую корзину',
                          newinfo: '(будет создана новая корзина)',
                          real: 'существующую корзину',
                      },
                  };
              },
              computed: {
                  cartId: (state) =>
                      state.requestCartId ?? state.$store.getters['basket/getCurrentBasketId'],
                  cart: (state) =>
                      state.$store.getters['basket/getBasket'](state.cartId),
  
                  basket: (state) => state.cart,
                  active_basket_id: (state) => state.cartId,
                  baskets: (state) => state.$store.getters['getCartList'],
                  user_id: (state) => state.cart?.USER_ID,
                  contragents: (state) => state.cart?.POSSIBLE_CONTRAGENTS,
                  contragent: (state) => state.cart?.CONTRAGENT,
                  address: (state) => state.cart?.ADDRESS,
                  addresslength: (state) => Object.keys(state.contragent?.ADDRESS)?.length,
  
                  contragent_id: {
                      get() {
                          return this.user_contragent_id != undefined
                              ? this.user_contragent_id
                              : this.$store.getters['basket/getContragentId'];
                      },
                      set(val) {
                          this.user_address_id = null;
                          return this.user_contragent_id = val;
                      }
                  },
                  address_id: {
                      get() {
                          if (this.addresslength == 1 && !this.user_address_id) {
                              for (var i in this.contragent.ADDRESS) {
                                  return this.contragent.ADDRESS[i].ID;
                              }
                          } else if (this.addresslength > 1 && !this.user_address_id) {
                              return '';
                          }
                          return this.user_address_id;
                      },
                      set(val) {
                          return this.user_address_id = val;
                      }
                  },
                  basket_id: {
                      get() {
                          return !!this.user_basket_id ? this.user_basket_id : this.active_basket_id;
                      },
                  },
                  localize: (state) => BX.Vue.getFilteredPhrases('CART_IMPORT'),
              },
          });
      });
      document.addEventListener('DOMContentLoaded', function () {
  
      });
  })(window);
  // временное решение по печати данных
  function printTable(selector) {
      if (!BX(selector)) return false;
      let outerHeight = window.outerHeight / 2,
          outerWidth = window.outerWidth / 2;
      var mywindow = window.open('', 'Выгрузка позиций в корзину fit24.ru', `height=${outerHeight},width=${outerWidth}`);
      mywindow.document.write('<html><head><title>Выгрузка позиций в корзину</title>');
      /*optional stylesheet*/ //
      mywindow.document.write('<link rel="stylesheet" href="//cdn.datatables.net/v/dt/dt-1.10.18/fh-3.1.4/r-2.2.2/sc-2.0.0/sl-1.3.0/datatables.min.css" type="text/css" />');
      mywindow.document.write('<link rel="stylesheet" href="//use.fontawesome.com/releases/v5.10.0/css/all.css" type="text/css" />');
      mywindow.document.write('</head><body >');
      mywindow.document.write(BX(selector).innerHTML);
      if (BX.browser.IsFirefox()) {
          mywindow.document.write('<script>window.print();</script>');
      }
      mywindow.document.write('</body></html>');
      if (BX.browser.IsIE10()) {
          // mywindow.document.close(); // necessary for IE >= 10
          mywindow.focus(); // necessary for IE >= 10
      }
      if (!BX.browser.IsFirefox()) {
          mywindow.print();
          // mywindow.close();
      }
      return true;
  }
  // загрузка скриптов
  function loadScript(src) {
      let script = document.createElement('script');
      script.src = src;
      script.async = false;
      // script.crossorigin = "anonymous";
      document.head.append(script);
  }
  
  ; (function () {
      'use strict';
  
      BX.namespace('BX.Sale.CartImportComponent');
  
      BX.Sale.CartImportComponent = {
          maxItemsShowCount: 30,
          precisionFactor: Math.pow(10, 6),
          stickyHeaderOffset: 0,
          instance: false,
  
          duration: {
              priceAnimation: 600,
              filterTimer: 300
          },
  
          ids: {
              col_code_num: 'col_code_num_input',
              col_count_num: 'col_count_num_input',
              col_barcode_num: 'col_barcode_num_input',
              baskets_count: 'baskets_count',
          },
  
          initializePrimaryFields: function () {
              this.nodes = {
                  col_code_num: BX(this.ids.col_code_num),
                  col_count_num: BX(this.ids.col_count_num),
                  col_barcode_num: BX(this.ids.col_barcode_num),
                  baskets_count: BX(this.ids.baskets_count)
              };
              this.values = {
                  col_code_num: this.params.COL_CODE_NUM,
                  col_count_num: this.params.COL_COUNT_NUM,
                  col_barcode_num: this.params.COL_BARCODE_NUM,
                  baskets_count: this.params.BASKETS_COUNT
              }
  
              this.isMobile = BX.browser.IsMobile();
              this.isTouch = BX.hasClass(document.documentElement, 'bx-touch');
          },
  
          init: function (parameters) {
              if (this.instance) return;
              this.params = parameters.params || {};
              this.result = parameters.result || {};
  
              this.initializePrimaryFields();
              this.template = parameters.template || '';
              this.signedParamsString = parameters.signedParamsString || '';
              this.siteId = parameters.siteId || '';
              this.siteTemplateId = parameters.siteTemplateId || '';
              this.ajaxUrl = this.params.AJAX_PATH || '';
  
              this.bindInitialEvents();
              this.restoreUserSettings();
              this.instance = true;
          },
          bindInitialEvents: function () {
              BX.bind(this.nodes.col_code_num, 'change', BX.proxy(this.saveSettings, this));
              BX.bind(this.nodes.col_count_num, 'change', BX.proxy(this.saveSettings, this));
              BX.bind(this.nodes.col_barcode_num, 'change', BX.proxy(this.saveSettings, this));
              BX.bind(this.nodes.baskets_count, 'change', BX.proxy(this.saveSettings, this));
          },
          restoreUserSettings: function () {
              if (typeof window.userOptions != 'undefined' &&
                  window.userOptions.multibasket != undefined &&
                  window.userOptions.multibasket.basket_import != undefined
              ) {
                  this.values.col_code_num = window.userOptions.multibasket.basket_import.col_code_num || this.values.col_code_num;
                  this.values.col_count_num = window.userOptions.multibasket.basket_import.col_count_num || this.values.col_count_num;
                  this.values.col_barcode_num = window.userOptions.multibasket.basket_import.col_barcode_num || this.values.col_barcode_num;
                  this.values.baskets_count = window.userOptions.multibasket.basket_import.baskets_count || this.values.baskets_count;
              } else {
                  this.values.col_code_num = BX.getCookie('multibasket.basket_import.col_code_num') || this.values.col_code_num;
                  this.values.col_count_num = BX.getCookie('multibasket.basket_import.col_count_num') || this.values.col_count_num;
                  this.values.col_barcode_num = BX.getCookie('multibasket.basket_import.col_barcode_num') || this.values.col_barcode_num;
                  this.values.baskets_count = BX.getCookie('multibasket.basket_import.baskets_count') || this.values.baskets_count;
              }
              if (this.nodes.col_code_num) {
                  this.nodes.col_code_num.value = parseInt(this.values.col_code_num);
              }
              if (this.nodes.col_count_num) {
                  this.nodes.col_count_num.value = parseInt(this.values.col_count_num);
              }
              if (this.nodes.col_barcode_num) {
                  this.nodes.col_barcode_num.value = parseInt(this.values.col_barcode_num);
              }
              if (this.nodes.baskets_count) {
                  this.nodes.baskets_count.value = parseInt(this.values.baskets_count);
              }
          },
          saveSettings: function (params) {
              this.values.col_code_num = parseInt(this.nodes.col_code_num.value);
              this.values.col_count_num = parseInt(this.nodes.col_count_num.value);
              this.values.col_barcode_num = parseInt(this.nodes.col_barcode_num.value);
              if (typeof BX.userOptions != 'undefined') {
                  BX.userOptions.save('germes.multibasket', 'basket_import', 'col_code_num', '' + this.values.col_code_num);
                  BX.userOptions.save('germes.multibasket', 'basket_import', 'col_count_num', '' + this.values.col_count_num);
                  BX.userOptions.save('germes.multibasket', 'basket_import', 'col_barcode_num', '' + this.values.col_barcode_num);
                  BX.userOptions.save('germes.multibasket', 'basket_import', 'baskets_count', '' + this.values.baskets_count);
                  BX.userOptions.send(BX.proxy(function () {
                      if (typeof BX.UI.Notification != 'undefined') {
                          BX.UI.Notification.Center.notify({
                              content: "Настройки сохранены.",
                              position: "bottom-right",
                              autoHideDelay: 2000,
                              closeButton: true,
                              category: "multibasket-savesettings",
                              actions: []
                          });
                      }
                  }, this));
              } else {
                  BX.setCookie('multibasket.basket_import.col_code_num', this.values.col_code_num);
                  BX.setCookie('multibasket.basket_import.col_count_num', this.values.col_count_num);
                  BX.setCookie('multibasket.basket_import.col_barcode_num', this.values.col_barcode_num);
                  BX.setCookie('multibasket.basket_import.baskets_count', this.values.baskets_count);
              }
          }
      }
  })();
  