//константы для работы подписания через egov mobile
const SERVER_SIGN_EGOV = "https://mobile-sign.arta.pro";
const ORG_ID = "f9918571-508f-46cc-9cea-6ed1a1af30b4";

const getDataForSign = async documentID => {
  return new Promise(async resolve => {
    try {
      const {login, password} = Cons.creds;
      const url = `../Synergy/rest/api/data-for-sign?documentID=${documentID}`;
      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.json());
    } catch (err) {
      console.log(`ERROR [ getDataForSign ]: ${err.message}`);
      resolve({
        errorCode: 666,
        errorMessage: err.message
      });
    }
  });
}

const generateOrgToken = async () => {
  return new Promise(async resolve => {
    try {
      const url = `${SERVER_SIGN_EGOV}/auth/generate-token`;
      const headers = new Headers();
      headers.append("Authorization", "Basic " + btoa(unescape(encodeURIComponent(`1:1`))));
      headers.append("Content-Type", "application/json; charset=utf-8");

      const body = JSON.stringify({"organizationID": ORG_ID});
      const response = await fetch(url, {method: 'POST', headers, body});
      resolve(response.json());
    } catch (err) {
      console.log(`ERROR [ generateOrgToken ]: ${err.message}`);
      resolve({
        errorCode: 666,
        errorMessage: err.message
      });
    }
  });
}

const documentUpload = async (formdata, orgToken) => {
  return new Promise(async resolve => {
    try {
      const url = `${SERVER_SIGN_EGOV}/documents/upload`;
      const headers = new Headers();
      headers.append("Authorization", `Bearer ${orgToken}`);

      const response = await fetch(url, {method: 'POST', headers, body: formdata});
      resolve(response.json());
    } catch (err) {
      console.log(`ERROR [ documentUpload ]: ${err.message}`);
      resolve({
        errorCode: 666,
        errorMessage: err.message
      });
    }
  });
}

const getDocumentInfo = async 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);
    });
  });
}

const getPrintFilePDF = async dataUUID => {
  return new Promise(async resolve => {
    try {
      const {login, password} = Cons.creds;
      const url = `../Synergy/rest/api/asforms/data/print`;
      const headers = new Headers();
      headers.append("Authorization", "Basic " + btoa(unescape(encodeURIComponent(`${login}:${password}`))));
      headers.append("Content-Type", "application/json");
      headers.append("Content-disposition", "attachment; filename=printFile.pdf");
      const response = await fetch(url, {
        method: 'POST',
        headers,
        body: JSON.stringify({dataUUID, format: 'PDF'})
      });
      resolve(response.blob());
    } catch (err) {
      console.log(`ERROR [ getPrintFilePDF ]: ${err.message}`);
      resolve(null);
    }
  });
}

const openQRCodeDialog = (text, succesHandler) => {
  const contaienr = $('<div>', {style: 'display: flex; justify-content: center; align-items: center;'});
  const qr = $('<div>');

  new QRCode(qr[0], {
    text,
    width: 300,
    height: 300,
    colorDark : "#485156",
    colorLight : "transparent",
    correctLevel : QRCode.CorrectLevel.H
  });

  contaienr.append(qr);

  const dialog = UTILS.getSmallModalDialog(i18n.tr('QR-код для подписания'), contaienr);

  UIkit.modal(dialog).show();
  dialog.on('hidden', () => {
    dialog.remove();
    if(succesHandler && typeof succesHandler === 'function') succesHandler();
  });
}

/*
@worktype – тип подписания:
sign – вызывает API /rest/api/docflow/sign
finish – вызывает API /rest/api/workflow/finish_process
*/
this.generateQRCodeEgov = async (param, succesHandler) => {
  Cons.showLoader();
  try {
    const {documentID, worktype, procInstID, signal, comment} = param;

    const dataForSign = await getDataForSign(documentID);
    if(dataForSign.hasOwnProperty('errorCode') && dataForSign.errorCode != 0) throw new Error(dataForSign.errorMessage);

    const orgData = await generateOrgToken();
    if(orgData.hasOwnProperty('errorCode') && orgData.errorCode != 0) throw new Error(orgData.errorMessage);

    const {asfDataID, hasPrintable, name} = await getDocumentInfo(documentID);

    const formdata = new FormData();
    formdata.append("name", name);
    formdata.append("description", name);
    formdata.append("base64", dataForSign.rawdata);
    formdata.append("organisationID", ORG_ID);
    formdata.append("synergyDocID", documentID);
    formdata.append("synergyAuthToken", dataForSign.token);
    formdata.append("synergyUserID", AS.OPTIONS.currentUser.userid);
    formdata.append("worktype", worktype);

    if(AS.OPTIONS.currentUser.hasOwnProperty('iin') && AS.OPTIONS.currentUser.iin && AS.OPTIONS.currentUser.iin != '') {
      formdata.append("iin", AS.OPTIONS.currentUser.iin);
    }

    if(procInstID) formdata.append("procInstID", procInstID);
    if(signal) formdata.append("signal", signal);
    if(comment) formdata.append("comment", comment);

    if(asfDataID && hasPrintable && hasPrintable == "true") {
      const file = await getPrintFilePDF(asfDataID);
      if(file) {
        const newFile = new File([file], "print.pdf", {type: 'application/pdf'});
        formdata.append("file", newFile);
      }
    }

    const resultUpload = await documentUpload(formdata, orgData.token);
    if(resultUpload.hasOwnProperty('errorCode') && resultUpload.errorCode != 0) throw new Error(resultUpload.errorMessage);

    const qrCodeText = `mobileSign:${resultUpload.link}`;
    openQRCodeDialog(qrCodeText, succesHandler);

    Cons.hideLoader();
  } catch (err) {
    UIkit.notification.closeAll();
    Cons.hideLoader();
    showMessage(err.message, 'error');
  }
}
