this.appAPI = {
  getWorkInfo: async function(actionID){
    return new Promise(async resolve => {
      rest.synergyGet(`api/workflow/works_by_id?workID=${actionID}`,
        res => resolve(res[0]),
        err => {
        console.log(`ERROR [ getWorkInfo ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getSubworks: async function(workID){
    return new Promise(async resolve => {
      rest.synergyGet(`api/workflow/subworks/${workID}`, resolve, err => {
        console.log(`ERROR [ getSubworks ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getCompletionForm: async function(completionFormID){
    return new Promise(async resolve => {
      rest.synergyGet(`api/formPlayer/getCompletionForm?completionFormID=${completionFormID}`,
        res => {
          if(res.errorCode && res.errorCode != 0) {
            console.log(`ERROR [ getCompletionForm ]: ${JSON.stringify(res)}`);
            resolve(null);
          } else {
            resolve(res);
          }
        },
        err => {
        console.log(`ERROR [ getCompletionForm ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getFormForResult: async function(formCode, workID) {
    return new Promise(async resolve => {
      rest.synergyGet(`api/workflow/work/get_form_for_result?formCode=${formCode}&workID=${workID}&locale=${AS.OPTIONS.locale}`, resolve, err => {
        console.log(`ERROR [ getFormForResult ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  setProgressWork: async function(progress, workID) {
    return new Promise(async resolve => {
      rest.synergyGet(`api/workflow/work/set_progress?progress=${progress}&workID=${workID}`, resolve, err => {
        console.log(`ERROR [ setProgressWork ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  searchWork: async function(value) {
    const url = `api/workflow/works/list_ext?userID=${AS.OPTIONS.currentUser.userid}&search=${encodeURIComponent(value)}&locale=${AS.OPTIONS.locale}`;
    return new Promise(async resolve => {
      rest.synergyGet(url, resolve, err => {
        console.log(`ERROR [ searchWork ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  finishWork: async function(finishWorkBody){
    return new Promise(async resolve => {
      AS.FORMS.ApiUtils.simpleAsyncPost("rest/api/workflow/work/set_result", result => {
        if(result.errorCode && result.errorCode != '0') {
          console.log(`ERROR [ finishWork ]: ${JSON.stringify(result)}`);
          resolve(null);
        } else {
          resolve(result);
        }
      }, null, finishWorkBody, "application/x-www-form-urlencoded; charset=UTF-8", err => {
        console.log(`ERROR [ finishWork ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  //Метод завершает процесс согласования/утверждения/ознакомления
  finishProcess: async function(data){
    return new Promise(async resolve => {
      AS.FORMS.ApiUtils.simpleAsyncPost("rest/api/workflow/finish_process", result => {
        if(result.errorCode && result.errorCode != '0') {
          console.log(`ERROR [ finishProcess ]: ${JSON.stringify(result)}`);
          resolve(null);
        } else {
          resolve(result);
        }
      }, null, data, "application/x-www-form-urlencoded; charset=UTF-8", err => {
        console.log(`ERROR [ finishProcess ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  acceptResultWork: async function(resultID, workID) {
    return new Promise(async resolve => {
      rest.synergyGet(`api/workflow/work/accept_result?resultID=${resultID}&workID=${workID}`, resolve, err => {
        console.log(`ERROR [ acceptResultWork ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  createWork: async function(body){
    return new Promise(async resolve => {
      try {
        const {login, password} = Cons.creds;
        const url = `../Synergy/rest/api/workflow/work/create?locale=${AS.OPTIONS.locale}`;
        const headers = new Headers();
        headers.append("Authorization", "Basic " + btoa(unescape(encodeURIComponent(`${login}:${password}`))));
        headers.append("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        const response = await fetch(url, {method: 'POST', headers, body});
        resolve(response.json());
      } catch (err) {
        console.log(`ERROR [ createWork ]: ${err.message}`);
        resolve({
          errorCode: 666,
          errorMessage: err.message
        });
      }
    });
  },

  saveWork: async function(body){
    return new Promise(async resolve => {
      try {
        const {login, password} = Cons.creds;
        const url = `../Synergy/rest/api/workflow/work/save?locale=${AS.OPTIONS.locale}`;
        const headers = new Headers();
        headers.append("Authorization", "Basic " + btoa(unescape(encodeURIComponent(`${login}:${password}`))));
        headers.append("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        const response = await fetch(url, {method: 'POST', headers, body});
        resolve(response.json());
      } catch (err) {
        console.log(`ERROR [ saveWork ]: ${err.message}`);
        resolve({
          errorCode: 666,
          errorMessage: err.message
        });
      }
    });
  },

  startRouteWork: async function(body){
    return new Promise(async resolve => {
      try {
        const {login, password} = Cons.creds;
        const url = `../Synergy/rest/api/workflow/work/start_route?locale=${AS.OPTIONS.locale}`;
        const headers = new Headers();
        headers.append("Authorization", "Basic " + btoa(unescape(encodeURIComponent(`${login}:${password}`))));
        headers.append("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        const response = await fetch(url, {method: 'POST', headers, body});
        resolve(response.json());
      } catch (err) {
        console.log(`ERROR [ startRouteWork ]: ${err.message}`);
        resolve({
          errorCode: 666,
          errorMessage: err.message
        });
      }
    });
  },

  forwardWork: async function(body){
    return new Promise(async resolve => {
      try {
        const {login, password} = Cons.creds;
        const url = `../Synergy/rest/api/docflow/doc/send?locale=${AS.OPTIONS.locale}`;
        const headers = new Headers();
        headers.append("Authorization", "Basic " + btoa(unescape(encodeURIComponent(`${login}:${password}`))));
        headers.append("Content-Type", "application/json; charset=utf-8");
        const response = await fetch(url, {method: 'POST', headers, body: JSON.stringify(body)});
        resolve(response.json());
      } catch (err) {
        console.log(`ERROR [ forwardWork ]: ${err.message}`);
        resolve({
          errorCode: 666,
          errorMessage: err.message
        });
      }
    });
  },

  transferWork: async function(body){
    return new Promise(async resolve => {
      try {
        const {login, password} = Cons.creds;
        const url = `../Synergy/rest/api/workflow/work/transfer?locale=${AS.OPTIONS.locale}`;
        const headers = new Headers();
        headers.append("Authorization", "Basic " + btoa(unescape(encodeURIComponent(`${login}:${password}`))));
        headers.append("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        const response = await fetch(url, {method: 'POST', headers, body});
        resolve(response.json());
      } catch (err) {
        console.log(`ERROR [ transferWork ]: ${err.message}`);
        resolve({
          errorCode: 666,
          errorMessage: err.message
        });
      }
    });
  },

  getExecutionProcess: async function(workID) {
    return new Promise(async resolve => {
      rest.synergyGet(`api/workflow/get_execution_process?workID=${workID}&locale=${AS.OPTIONS.locale}`, resolve, err => {
        console.log(`ERROR [ getExecutionProcess ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getProcessInfo: async function(workID) {
    return new Promise(async resolve => {
      rest.synergyGet(`api/workflow/process_info?workID=${workID}&locale=${AS.OPTIONS.locale}`, resolve, err => {
        console.log(`ERROR [ getProcessInfo ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getWorkDocument: async function(actionID) {
    return new Promise(async resolve => {
      rest.synergyGet(`api/workflow/work/${actionID}/document?locale=${AS.OPTIONS.locale}`, res => resolve(res.documentID), err => {
        console.log(`ERROR [ getWorkDocument ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  deleteWork: async function(workID) {
    return new Promise(resolve => {
      rest.synergyGet(`api/workflow/work/delete?workID=${workID}&locale=${AS.OPTIONS.locale}`, resolve, err => {
        console.log(`ERROR [ deleteWork ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getAsfDataUUID: async function(documentID) {
    return new Promise(async resolve => {
      AS.FORMS.ApiUtils.simpleAsyncGet(`rest/api/formPlayer/getAsfDataUUID?documentID=${documentID}`,
        resolve, 'text',  null,
        err => {
          console.log(`ERROR [ getAsfDataUUID ]: ${JSON.stringify(err)}`);
          resolve(null);
        }
      );
    });
  },

  getDocumentIdentifier: async function(dataUUID) {
    return new Promise(async resolve => {
      AS.FORMS.ApiUtils.simpleAsyncGet(`rest/api/formPlayer/documentIdentifier?dataUUID=${dataUUID}`,
        resolve, 'text',  null,
        err => {
          console.log(`ERROR [ getDocumentIdentifier ]: ${JSON.stringify(err)}`);
          resolve(null);
        }
      );
    });
  },

  getDocMeaningContent: async function(asfDataUUID) {
    return new Promise(async resolve => {
      AS.FORMS.ApiUtils.simpleAsyncGet(`rest/api/formPlayer/getDocMeaningContent?asfDataUUID=${asfDataUUID}`,
        resolve, 'text',  null,
        err => {
          console.log(`ERROR [ getDocMeaningContent ]: ${JSON.stringify(err)}`);
          resolve(null);
        }
      );
    });
  },

  startUpload: async function() {
    return new Promise(async resolve => {
      rest.synergyGet(`api/storage/start_upload`, resolve, err => {
        console.log(`ERROR [ startUpload ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  uploadPart: async function(filePath, data) {
    return new Promise(async resolve => {
      try {
        const {login, password} = Cons.creds;
        const auth = "Basic " + btoa(unescape(encodeURIComponent(`${login}:${password}`)));
        $.ajax({
          url: `${window.location.origin}/Synergy/rest/api/storage/upload_part?file=${encodeURIComponent(filePath)}`,
          data: data,
          cache: false,
          contentType: false,
          processData: false,
          type: 'POST',
          headers: {"Authorization": auth}
        }).done(response => {
          resolve(response);
        }).fail((jqXHR, textStatus) => {
          console.log(`ERROR uploadPart`, textStatus, jqXHR);
          resolve(false);
        });
      } catch (e) {
        console.log(`ERROR [ uploadPart ]: ${e.message}`);
        resolve(false);
      }
    });
  },

  getTranslate: async function(value, locale = AS.OPTIONS.locale) {
    return new Promise(async resolve => {
      try {
        const {login, password} = Cons.creds;
        const auth = "Basic " + btoa(unescape(encodeURIComponent(`${login}:${password}`)));
        const url = `../Synergy/rest/api/formPlayer/translate?value=${encodeURIComponent(value)}&locale=${locale}`;
        const response = await fetch(url, {method: 'GET', headers: {"Authorization": auth}});

        if(!response.ok) throw new Error(`HTTP: ${response.status}, message: ${response.statusText} [ ${response.text()} ]`);
        resolve(response.text());
      } catch (err) {
        console.log(`ERROR [ getTranslate ]: ${err.message}`);
        resolve(value);
      }
    });
  },

  getTranslateMultiple: async function(values) {
    return new Promise(async resolve => {
      rest.synergyGet(`api/formPlayer/translateMultiple?locale=${AS.OPTIONS.locale}&value=${values}`, resolve, err => {
        console.log(`ERROR [ getTranslateMultiple ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getSystemSettings: async function() {
    return new Promise(async resolve => {
      rest.synergyGet(`api/settings/get?locale=${AS.OPTIONS.locale}`, resolve, err => {
        console.log(`ERROR [ getSystemSettings ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getSystemLocales: async function() {
    return new Promise(async resolve => {
      rest.synergyGet(`translation/locales`, resolve, err => {
        console.log(`ERROR [ getSystemLocales ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getDialogInfo: async function(type = 'WORK') {
    return new Promise(async resolve => {
      rest.synergyGet(`api/workflow/get_dialog_info?type=${type}&locale=${AS.OPTIONS.locale}`, resolve, err => {
        console.log(`ERROR [ getDialogInfo ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getSendWorkInfo: async function(params) {
    return new Promise(async resolve => {
      const param = $.param({...params, locale: AS.OPTIONS.locale});
      rest.synergyGet(`api/workflow/send_work_info?${param}`, resolve, err => {
        console.log(`ERROR [ getSendWorkInfo ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getDefaultParamWork: async function() {
    return new Promise(async resolve => {
      rest.synergyGet(`api/workflow/work/create_defaults?locale=${AS.OPTIONS.locale}`, resolve, err => {
        console.log(`ERROR [ getDefaultParamWork ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getWorkAttachments: async function(workID) {
    return new Promise(async resolve => {
      rest.synergyGet(`api/workflow/work/${workID}/attachments?locale=${AS.OPTIONS.locale}`, resolve, err => {
        console.log(`ERROR [ getWorkAttachments ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getDocumentAttachments: async function(documentID){
    return new Promise(resolve => {
      rest.synergyGet(`api/docflow/doc/attachments?documentID=${documentID}&locale=${AS.OPTIONS.locale}`, resolve, err => {
        console.log(`ERROR [ getAttachments ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getWorkActions: async function(workID) {
    return new Promise(async resolve => {
      rest.synergyGet(`api/workflow/work_actions?workID=${workID}&locale=${AS.OPTIONS.locale}`, resolve, err => {
        console.log(`ERROR [ getWorkActions ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  addFileToWork: async function(workID, fileName, filePath, path) {
    return new Promise(async resolve => {
      rest.synergyPost(`api/workflow/work/${workID}/attachment/create?locale=${AS.OPTIONS.locale}`,
        {fileName, filePath, path},
        "application/x-www-form-urlencoded; charset=UTF-8",
        resolve,
        resolve
      );
    });
  },

  addFileToDocument: async function(documentID, fileName, filePath, path) {
    return new Promise(resolve => {
      rest.synergyPost(`api/docflow/doc/attachment/create?locale=${AS.OPTIONS.locale}`,
        {documentID, fileName, filePath, path},
        "application/x-www-form-urlencoded; charset=UTF-8",
        resolve,
        resolve
      );
    });
  },

  getFile: async function(identifier, type = 'blob') {
    return new Promise(async resolve => {
      try {
        const {login, password} = Cons.creds;
        const auth = "Basic " + btoa(unescape(encodeURIComponent(`${login}:${password}`)));
        const url = `../Synergy/rest/api/storage/file/get?identifier=${identifier}&inline=true`;
        const response = await fetch(url, {method: 'GET', headers: {"Authorization": auth}});
        if(!response.ok) throw new Error(`HTTP: ${response.status}, message: ${response.statusText} [ ${response.text()} ]`);
        switch (type) {
          case 'json': resolve(response.json()); break;
          default: resolve(response.blob());
        }
      } catch (err) {
        console.log(`ERROR [ getFile ]: ${JSON.stringify(err)}`);
        resolve(false);
      }
    });
  },

  getPdfFile: async function(identifier) {
    return new Promise(async resolve => {
      try {
        const {login, password} = Cons.creds;
        const auth = "Basic " + btoa(unescape(encodeURIComponent(`${login}:${password}`)));
        const url = `../Synergy/rest/api/storage/pdf/get?identifier=${identifier}&inline=true`;
        const response = await fetch(url, {method: 'GET', headers: {"Authorization": auth}});
        if(!response.ok) throw new Error(`HTTP: ${response.status}, message: ${response.statusText} [ ${response.text()} ]`);
        resolve(response.blob());
      } catch (err) {
        console.log(`ERROR [ getPdfFile ]: ${JSON.stringify(err)}`);
        resolve(false);
      }
    });
  },

  getRegisterInfo: async function(registerID) {
    return new Promise(resolve => {
      rest.synergyGet(`api/docflow/register/info?locale=${AS.OPTIONS.locale}&registerID=${registerID}`, resolve, err => {
        console.log(`ERROR [ getRegisterInfo ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getDocumentRCC: async function(documentID) {
    return new Promise(async resolve => {
      rest.synergyGet(`api/docflow/doc/rcc?documentID=${documentID}&locale=${AS.OPTIONS.locale}`, resolve, err => {
        console.log(`ERROR [ getDocumentRCC ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getDocumentInfo: async function(documentID) {
    return new Promise(async resolve => {
      rest.synergyGet(`api/docflow/doc/document_info?documentID=${documentID}&locale=${AS.OPTIONS.locale}`, resolve, err => {
        console.log(`ERROR [ getDocumentInfo ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getDoctypes: async function(registerID) {
    return new Promise(async resolve => {
      let url = `api/docflow/doctypes?locale=${AS.OPTIONS.locale}`;
      if(registerID) url += `&registerID=${registerID}`;
      rest.synergyGet(url, resolve, err => {
        console.log(`ERROR [ getDoctypes ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getSignList: async function(documentID) {
    return new Promise(async resolve => {
      rest.synergyGet(`api/docflow/doc/sign_list?documentID=${documentID}&locale=${AS.OPTIONS.locale}`, resolve, err => {
        console.log(`ERROR [ getSignList ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getSignListXML: async function(docID, type) {
    return new Promise(async resolve => {
      const response = await fetch(`../Synergy/docsightings?docID=${docID}&type=${type}&locale=${AS.OPTIONS.locale}`);
      const signxml = await response.text();
      resolve(UTILS.parseSignXML(signxml));
    });
  },

  getDocumentHistory: async function(documentID) {
    return new Promise(async resolve => {
      AS.FORMS.ApiUtils.simpleAsyncPost(`rest/api/docflow/doc/getDocumentHistory?documentID=${documentID}&locale=${AS.OPTIONS.locale}`,
        resolve, null, null, null,
        err => {
          console.log(`ERROR [ getDocumentHistory ]: ${JSON.stringify(err)}`);
          resolve(null);
      });
    });
  },

  getDocHistoryHTML: async function(documentID) {
    return new Promise(async resolve => {
      AS.FORMS.ApiUtils.simpleAsyncGet(`processhistory?documentID=${documentID}&QR=null&locale=${AS.OPTIONS.locale}`, resolve, 'text', null, err => {
        console.log(`ERROR [ getDocHistoryHTML ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getDocChangesHTML: async function(documentID) {
    return new Promise(async resolve => {
      AS.FORMS.ApiUtils.simpleAsyncGet(`printdocchanges?documentID=${documentID}&QR=null&locale=${AS.OPTIONS.locale}`, resolve, 'text', null, err => {
        console.log(`ERROR [ getDocChangesHTML ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getDocChanges: async function(documentID) {
    return new Promise(async resolve => {
      rest.synergyGet(`api/docflow/doc/changes?documentID=${documentID}&locale=${AS.OPTIONS.locale}`, resolve, err => {
        console.log(`ERROR [ getDocChanges ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getDictionary: async function(code, getColumns = true, getItems = true) {
    return new Promise(async resolve => {
      rest.synergyGet(`api/dictionaries/${code}?getColumns=${getColumns}&getItems=${getItems}&locale=${AS.OPTIONS.locale}`, resolve, err => {
        console.log(`ERROR [ getDictionary ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getDictionaryByCode: async function(code) {
    return new Promise(async resolve => {
      rest.synergyGet(`api/dictionary/get_by_code?dictionaryCode=${code}&locale=${AS.OPTIONS.locale}`, resolve, err => {
        console.log(`ERROR [ getDictionaryByCode ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getFileDescription: async function(elementID) {
    return new Promise(async resolve => {
      rest.synergyGet(`api/storage/description?elementID=${elementID}&locale=${AS.OPTIONS.locale}`, resolve, err => {
        console.log(`ERROR [ getFileDescription ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  deleteFile: async function(elementID) {
    return new Promise(async resolve => {
      rest.synergyPost(`api/storage/remove?locale=${AS.OPTIONS.locale}`, {elementID}, "application/x-www-form-urlencoded", resolve, err => {
        console.log(`ERROR [ deleteFile ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  createCorrespondentOrg: async function(name) {
    return new Promise(async resolve => {
      rest.synergyPost(`api/docflow/doc/create_correspondent_org`, {name},
        "application/x-www-form-urlencoded; charset=UTF-8", resolve, err => {
        console.log(`ERROR [ createCorrespondentOrg ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  saveRCC: async function(data) {
    return new Promise(async resolve => {
      try {
        const {login, password} = Cons.creds;
        const auth = "Basic " + btoa(unescape(encodeURIComponent(`${login}:${password}`)));
        const url = `../Synergy/rest/api/docflow/doc/save`;
        const response = await fetch(url, {
          method: 'POST',
          headers: {"Authorization": auth, "Content-Type": "application/json; charset=UTF-8"},
          body: JSON.stringify(data)
        });
        if(!response.ok) throw new Error(`HTTP: ${response.status}, message: ${response.statusText} [ ${response.text()} ]`);
        resolve(response.json());
      } catch (err) {
        console.log(`ERROR [ saveRCC ]: ${JSON.stringify(err)}`);
        resolve(null);
      }
    });
  },

  stopRoute: async function(documentID) {
    return new Promise(resolve => {
      rest.synergyPost(`api/docflow/doc/stop_route?documentID=${documentID}&locale=${AS.OPTIONS.locale}`, null, "application/json; charset=UTF-8", resolve, err => {
        console.log(`ERROR [ stopRoute ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getRegistryList: async function() {
    return new Promise(async resolve => {
      rest.synergyGet(`api/registry/list?locale=${AS.OPTIONS.locale}`, resolve, err => {
        console.log(`ERROR [ getRegistryList ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getRegistryListWithFilters: async function() {
    return new Promise(async resolve => {
      rest.synergyGet(`api/registry/listWithFilters?locale=${AS.OPTIONS.locale}`, resolve, err => {
        console.log(`ERROR [ getRegistryListWithFilters ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getRegistryInfo: async function(registryCode) {
    return new Promise(async resolve => {
      rest.synergyGet(`api/registry/info?code=${registryCode}&locale=${AS.OPTIONS.locale}`, resolve, err => {
        console.log(`ERROR [ getRegistryInfo ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getRegistryInfoByID: async function(registryID) {
    return new Promise(async resolve => {
      rest.synergyGet(`api/registry/info?registryID=${registryID}&locale=${AS.OPTIONS.locale}`, resolve, err => {
        console.log(`ERROR [ getRegistryInfo ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getRegistryFilters: async function(registryCode) {
    return new Promise(async resolve => {
      rest.synergyGet(`api/registry/filters?registryCode=${registryCode}&locale=${AS.OPTIONS.locale}&type=service`, resolve, err => {
        console.log(`ERROR [ getRegistryFilters ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  mergeFormData: async function(data) {
    return new Promise(async resolve => {
      try {
        const {login, password} = Cons.creds;
        const auth = "Basic " + btoa(unescape(encodeURIComponent(`${login}:${password}`)));
        const url = `../Synergy/rest/api/asforms/data/merge`;
        const response = await fetch(url, {
          method: 'POST',
          headers: {"Authorization": auth, "Content-Type": "application/json; charset=UTF-8"},
          body: JSON.stringify(data)
        });
        if(!response.ok) throw new Error(`HTTP: ${response.status}, message: ${response.statusText} [ ${response.text()} ]`);
        resolve(response.json());
      } catch (err) {
        console.log(`ERROR [ mergeFormData ]: ${JSON.stringify(err)}`);
        resolve(null);
      }
    });
  },

  createDoc: async function(registryCode) {
    return new Promise(resolve => {
      rest.synergyGet(`api/registry/create_doc?registryCode=${registryCode}`, resolve, err => {
        console.log(`ERROR [ createDoc ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  createDocRegistryID: async function(registryID) {
    return new Promise(resolve => {
      rest.synergyGet(`api/registry/create_doc?registryID=${registryID}`, resolve, err => {
        console.log(`ERROR [ createDocRegistryID ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  createDocRCC: async function(registryCode, asfData, sendToActivation = false) {
    return new Promise(async resolve => {
      try {
        const {login, password} = Cons.creds;
        const auth = "Basic " + btoa(unescape(encodeURIComponent(`${login}:${password}`)));
        const url = `../Synergy/rest/api/registry/create_doc_rcc`;
        const response = await fetch(url, {
          method: 'POST',
          headers: {"Authorization": auth, "Content-Type": "application/json; charset=UTF-8"},
          body: JSON.stringify({
            registryCode: registryCode,
            data: asfData,
            sendToActivation: sendToActivation
          })
        });
        if(!response.ok) throw new Error(`HTTP: ${response.status}, message: ${response.statusText} [ ${response.text()} ]`);
        resolve(response.json());
      } catch (err) {
        console.log(`ERROR [ createDocRCC ]: ${JSON.stringify(err)}`);
        resolve(null);
      }
    });
  },

  activateDoc: async function(dataUUID) {
    return new Promise(resolve => {
      rest.synergyGet(`api/registry/activate_doc?dataUUID=${dataUUID}&locale=${AS.OPTIONS.locale}`, resolve, err => {
        console.log(`ERROR [ activateDoc ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  modifyDoc: async function(dataUUID) {
    return new Promise(resolve => {
      rest.synergyGet(`api/registry/modify_doc?dataUUID=${dataUUID}&locale=${AS.OPTIONS.locale}`, resolve, err => {
        console.log(`ERROR [ modifyDoc ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  loadAsfData: async function(dataUUID, version = null) {
    const url = version == null ? `api/asforms/data/${dataUUID}?locale=${AS.OPTIONS.locale}` : `api/asforms/data/${dataUUID}?version=${version}&locale=${AS.OPTIONS.locale}`;
    return new Promise(resolve => {
      rest.synergyGet(url, resolve, err => {
        console.log(`ERROR [ loadAsfData ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getChildDocuments: async function(documentID) {
    return new Promise(async resolve => {
      rest.synergyGet(`api/docflow/doc/child_documents?documentID=${documentID}&locale=${AS.OPTIONS.locale}`, resolve, err => {
        console.log(`ERROR [ getChildDocuments ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  setChildDocuments: async function(documentID, childDocuments = []) {
    return new Promise(async resolve => {
      AS.FORMS.ApiUtils.simpleAsyncPost(`rest/api/docflow/doc/set_child_documents?documentID=${documentID}`, resolve, null, JSON.stringify(childDocuments), "application/json", err => {
        console.log(`ERROR [ setChildDocuments ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  deleteChildDocument: async function(parentDocID, childDocID) {
    return new Promise(resolve => {
      rest.synergyPost(`api/docflow/doc/delete_child_document?parent_documentID=${parentDocID}&child_documentID=${childDocID}`, null, "application/json; charset=UTF-8", resolve, err => {
        console.log(`ERROR [ deleteChildDocument ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getCollationInfo: async function(registry_code, collated_registry_code) {
    return new Promise(async resolve => {
      rest.synergyGet(`api/registry/collation_info?registry_code=${registry_code}&collated_registry_code=${collated_registry_code}`, resolve, err => {
        console.log(`ERROR [ getCollationInfo ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getCollationData: async function(collationGroup, dataUUID, formId, registryDocumentId) {
    let url = `rest/api/asforms/form/collate`;
    url += `?collationGroup=${collationGroup}`;
    url += `&dataUUID=${dataUUID}`;
    url += `&formId=${formId}`;
    url += `&registryDocumentId=${registryDocumentId}`;

    return new Promise(async resolve => {
      AS.FORMS.ApiUtils.simpleAsyncGet(url, resolve, 'text',  null,
        err => {
          console.log(`ERROR [ getCollationData ]: ${err}`);
          resolve(null);
        }
      );
    });
  },

  sendNotification: async function(body) {
    return new Promise(async resolve => {
      try {
        const {defaultUser, defaultUserPassword} = Cons.getCurrentApp();
        const auth = "Basic " + btoa(unescape(encodeURIComponent(`${defaultUser}:${defaultUserPassword}`)));
        const url = `../Synergy/rest/api/notifications/send`;
        const response = await fetch(url, {
          method: 'POST',
          headers: {"Authorization": auth, "Content-Type": "application/json; charset=UTF-8"},
          body: JSON.stringify(body)
        });

        if(!response.ok) {
          let rt = await response.text();
          rt = JSON.parse(rt);
          throw new Error(`http: ${response.status}, message: ${response.statusText}, errorMessage: ${rt.errorMessage}`);
        }
        resolve(response.json());
      } catch (err) {
        console.log(`ERROR [ sendNotification ]: ${err.message}`);
        resolve(null);
      }
    });
  },

  getAsfDefinition: async function(formID){
    return new Promise(async resolve => {
      rest.synergyGet(`api/asforms/form_ext?formID=${formID}`, resolve, err => {
        console.log(`ERROR [ getAsfDefinition ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getDocumentsFilters: async function(params) {
    return new Promise(async resolve => {
      rest.synergyGet(`api/docflow/doc/documents_filters?locale=${AS.OPTIONS.locale}${params ? '&'+params : ''}`, resolve, err => {
        console.log(`ERROR [ getDocumentsFilters ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  getFavoriteDocFilters: async function() {
    return new Promise(async resolve => {
      rest.synergyGet(`api/docflow/doc/favorite_doc_filters?locale=${AS.OPTIONS.locale}`, resolve, err => {
        console.log(`ERROR [ getFavoriteDocFilters ]: ${JSON.stringify(err)}`);
        resolve(null);
      });
    });
  },

  delegated: {
    get: async function() {
      return new Promise(async resolve => {
        rest.synergyGet(`api/delegation/delegated_actions?locale=${AS.OPTIONS.locale}`, resolve, err => {
          console.log(`ERROR [ delegated get ]: ${JSON.stringify(err)}`);
          resolve(null);
        });
      });
    },

    add: async function(body) {
      return new Promise(async resolve => {
        try {
          const {login, password} = Cons.creds;
          const url = `../Synergy/rest/api/delegation/add_delegated_actions?locale=${AS.OPTIONS.locale}`;
          const headers = new Headers();
          headers.append("Authorization", "Basic " + btoa(unescape(encodeURIComponent(`${login}:${password}`))));
          headers.append("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
          const response = await fetch(url, {method: 'POST', headers, body});
          resolve(response.json());
        } catch (err) {
          console.log(`ERROR [ delegated add ]: ${err.message}`);
          resolve({
            errorCode: 666,
            errorMessage: err.message
          });
        }
      });
    },

    del: async function(body) {
      return new Promise(async resolve => {
        try {
          const {login, password} = Cons.creds;
          const url = `../Synergy/rest/api/delegation/delete_delegated_actions?locale=${AS.OPTIONS.locale}`;
          const headers = new Headers();
          headers.append("Authorization", "Basic " + btoa(unescape(encodeURIComponent(`${login}:${password}`))));
          headers.append("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
          const response = await fetch(url, {method: 'POST', headers, body});
          resolve(response.json());
        } catch (err) {
          console.log(`ERROR [ delegated delete ]: ${err.message}`);
          resolve({
            errorCode: 666,
            errorMessage: err.message
          });
        }
      });
    }
  },

  resolution: {
    get: async function(param) {
      const {documentID, workID} = param;
      return new Promise(async resolve => {
        let url = `api/docflow/doc/get_resolution?locale=${AS.OPTIONS.locale}`;

        if(!documentID && !workID) {
          resolve(null);
          console.log(`ERROR [ resolution get ]: не переданы параметры documentID или workID`);
        }

        if(documentID) url += `&documentID=${documentID}`;
        if(workID) url += `&workID=${workID}`;

        rest.synergyGet(url, resolve, err => {
          console.log(`ERROR [ resolution get ]: ${JSON.stringify(err)}`);
          resolve(null);
        });
      });
    },

    save: async function(body){
      return new Promise(async resolve => {
        try {
          const {login, password} = Cons.creds;
          const url = `../Synergy/rest/api/docflow/doc/save_resolution?locale=${AS.OPTIONS.locale}`;
          const headers = new Headers();
          headers.append("Authorization", "Basic " + btoa(unescape(encodeURIComponent(`${login}:${password}`))));
          headers.append("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
          const response = await fetch(url, {method: 'POST', headers, body});
          resolve(response.json());
        } catch (err) {
          console.log(`ERROR [ saveResolution ]: ${err.message}`);
          resolve({
            errorCode: 666,
            errorMessage: err.message
          });
        }
      });
    }
  },

  filter: {
    info: async function(filterID){
      return new Promise(async resolve => {
        rest.synergyGet(`api/registry/filter_info?locale=${AS.OPTIONS.locale}&filterID=${filterID}`, resolve, err => {
          console.log(`ERROR [ filterInfo ]: ${JSON.stringify(err)}`);
          resolve(null);
        });
      });
    },

    save: async function(body){
      return new Promise(async resolve => {
        try {
          const {login, password} = Cons.creds;
          const url = `../Synergy/rest/api/registry/filters/users/save?locale=${AS.OPTIONS.locale}`;
          const headers = new Headers();
          headers.append("Authorization", "Basic " + btoa(unescape(encodeURIComponent(`${login}:${password}`))));
          headers.append("Content-Type", "application/json; charset=UTF-8");
          const response = await fetch(url, {method: 'POST', headers, body: JSON.stringify(body)});
          resolve(response.json());
        } catch (err) {
          console.log(`ERROR [ saveUsersFilter ]: ${err.message}`);
          resolve({
            errorCode: 666,
            errorMessage: err.message
          });
        }
      });
    },

    delete: async function(filterID){
      return new Promise(async resolve => {
        try {
          const {login, password} = Cons.creds;
          const url = `../Synergy/rest/api/registry/filters/users/delete?locale=${AS.OPTIONS.locale}&filterID=${filterID}`;
          const headers = new Headers();
          headers.append("Authorization", "Basic " + btoa(unescape(encodeURIComponent(`${login}:${password}`))));
          headers.append("Content-Type", "application/json; charset=UTF-8");
          const response = await fetch(url, {method: 'POST', headers});
          resolve(response.text());
        } catch (err) {
          console.log(`ERROR [ deleteUsersFilter ]: ${err.message}`);
          resolve(null);
        }
      });
    }
  }
}
