var setre = setre || {};
(function () {
  /* Application paths *****************************************/
  var url = document.URL;
  // var appPath = 'http://api.setre.com/api/';
  var appPath;
  if (url.indexOf("localhost") >= 0) {
    appPath = "https://localhost:44324/api/"

  } else {
    appPath = "https://api.setre.com/api/"

  }
  //if (url.indexOf('85.111.31.69') >= 0) {
  //    appPath = 'http://api.setre.com/api/';
  //} else {
  //    if (url.indexOf('192.168.2.32') >= 0) {
  //        appPath = 'http://api.setre.com/api/';
  //    } else if (url.indexOf('titan') >= 0) {
  //        appPath = 'http://api.setre.com/api/';
  //    } else {
  //        appPath = 'https://localhost:44324/api/';
  //    }
  //}


  // Current application root path (including virtual directory if exists).
  setre.appPath = setre.appPath || appPath;


  /* SECURITY ***************************************/
  const tokenCookieName = "setre.AuthToken";

  const token = localStorage[tokenCookieName];


  /* AUTHORIZATION **********************************************/
  //Implements Authorization API that simplifies usage of authorization scripts generated by setre.

  setre.auth = setre.auth || {};

  setre.auth.allPermissions = setre.auth.allPermissions || {};

  setre.auth.grantedPermissions = setre.auth.grantedPermissions || {};

  //Deprecated. Use setre.auth.isGranted instead.
  setre.auth.hasPermission = function (permissionName) {
    return setre.auth.isGranted.apply(this, arguments);
  };

  //Deprecated. Use setre.auth.isAnyGranted instead.
  setre.auth.hasAnyOfPermissions = function () {
    return setre.auth.isAnyGranted.apply(this, arguments);
  };

  //Deprecated. Use setre.auth.areAllGranted instead.
  setre.auth.hasAllOfPermissions = function () {
    return setre.auth.areAllGranted.apply(this, arguments);
  };

  setre.auth.isGranted = function (permissionName) {
    return setre.auth.allPermissions[permissionName] !== undefined && setre.auth.grantedPermissions[permissionName] !== undefined;
  };

  setre.auth.isAnyGranted = function () {
    if (!arguments || arguments.length <= 0) {
      return true;
    }

    for (let i = 0; i < arguments.length; i++) {
      if (setre.auth.isGranted(arguments[i])) {
        return true;
      }
    }

    return false;
  };

  setre.auth.areAllGranted = function () {
    if (!arguments || arguments.length <= 0) {
      return true;
    }

    for (var i = 0; i < arguments.length; i++) {
      if (!setre.auth.isGranted(arguments[i])) {
        return false;
      }
    }

    return true;
  };

  setre.auth.tokenName = "setre.AuthToken";

  setre.auth.setTokenStorage = function (authToken) {
    setre.utils.setLocalStorage(setre.auth.tokenName, authToken);
  };

  setre.auth.getTokenStorage = function () {
    setre.utils.getLocalStorage(setre.auth.tokenName);
  };

  setre.auth.clearTokenStorage = function () {
    setre.utils.deleteLocalStorage(setre.auth.tokenName);
  };

  setre.auth.setToken = function (authToken, expireDate) {
    setre.utils.setCookieValue(setre.auth.tokenName, authToken, expireDate, setre.appPath, setre.domain);
  };

  setre.auth.getToken = function () {
    return setre.utils.getCookieValue(setre.auth.tokenName);
  };

  setre.auth.clearToken = function () {
    setre.auth.setToken();
  };


  /* ALERT NOTIFICATION ***************************************/

  setre.alert = setre.alert || {};

  //const Toast = Swal.mixin({
  //    toast: true,
  //    position: "top-end",
  //    showConfirmButton: false,
  //    timer: 30000,
  //    timerProgressBar: true,
  //    didOpen: (toast) => {
  //        toast.addEventListener('mouseenter', Swal.stopTimer);
  //        toast.addEventListener('mouseleave', Swal.resumeTimer);
  //    }
  //});

  setre.alert.error =
    function (message = "İşleminizi gerçekleştiremedik. Lütfen tekrar deneyiniz") {
      return DevExpress.ui.notify(message, "error", 3000);
    };

  setre.alert.success =
    function (message = "İşleminiz gerçekleştirilmiştir") {
      //return Toast.fire({
      //    icon: 'success',
      //    title: message
      //});
      return DevExpress.ui.notify(message, "success", 3000);
    };

  setre.alert.requiredMessage =
    function (message = "Lütfen gerekli alanları doldurunuz") {
      return DevExpress.ui.notify(message, "info", 3000);
    };

  /* UTILS ***************************************************/

  setre.utils = setre.utils || {};


  setre.utils.setreV3ImagePath = () => {
    const imagePathUrl = document.URL;
    let imagePath;
    return imagePath = "https://api.setre.com/StaticFiles";

    //if (imagePathUrl.indexOf("85.111.31.69") >= 0) {
    //} else {
    //  if (imagePathUrl.indexOf("192.168.2.32") >= 0) {
    //    return imagePath = "http://192.168.1.207:5656";
    //  } else {
    //    return imagePath = "http://192.168.1.207:5656";
    //  }
    //}
  };

  setre.utils.getImagePath = () => {
    const imagePathUrl = document.URL;
    let imagePath;

    return imagePath = "http://api.setre.com/Uploads/";

    //if (imagePathUrl.indexOf("85.111.31.69") >= 0) {
    //} else {
    //  if (imagePathUrl.indexOf("192.168.2.32") >= 0) {
    //    return imagePath = "https://api.setre.com/Uploads/";
    //  } else {
    //    return imagePath = "http://api.setre.com/Uploads/";
    //  }
    //}
  };

  setre.utils.getImagePathPictureArchive = () => {
    const imagePathUrl = document.URL;
    let imagePath;
    return imagePath = "http://api.setre.com/";

    //if (imagePathUrl.indexOf("85.111.31.69") >= 0) {
    //} else {
    //  if (imagePathUrl.indexOf("192.168.2.32") >= 0) {
    //    return imagePath = "https://api.setre.com/";
    //  } else {
    //    return imagePath = "http://api.setre.com/";
    //  }
    //}
  };

  setre.utils.getEditId = a => {
    return (a = document.createElement('a'), a.href = window.location.pathname, a.pathname).split('/').pop();
  };

  setre.utils.isNullorEmpty = key => {
    if (key === 0 || key === "" || key === null || key === undefined || key === "undefined" || Object.keys(key).length === 0 && key.constructor === Object) return true;
    else return false;
  };

  setre.utils.createNamespace = function (root, ns) {
    var parts = ns.split('.');
    for (var i = 0; i < parts.length; i++) {
      if (typeof root[parts[i]] === 'undefined') {
        root[parts[i]] = {};
      }

      root = root[parts[i]];
    }

    return root;
  };

  setre.utils.replaceAll = function (str, search, replacement) {
    var fix = search.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    return str.replace(new RegExp(fix, 'g'), replacement);
  };

  setre.utils.formatString = function () {
    if (arguments.length < 1) {
      return null;
    }

    var str = arguments[0];

    for (var i = 1; i < arguments.length; i++) {
      var placeHolder = '{' + (i - 1) + '}';
      str = setre.utils.replaceAll(str, placeHolder, arguments[i]);
    }

    return str;
  };

  setre.utils.toPascalCase = function (str) {
    if (!str || !str.length) {
      return str;
    }

    if (str.length === 1) {
      return str.charAt(0).toUpperCase();
    }

    return str.charAt(0).toUpperCase() + str.substr(1);
  };

  setre.utils.toCamelCase = function (str) {
    if (!str || !str.length) {
      return str;
    }

    if (str.length === 1) {
      return str.charAt(0).toLowerCase();
    }

    return str.charAt(0).toLowerCase() + str.substr(1);
  };

  setre.utils.truncateString = function (str, maxLength) {
    if (!str || !str.length || str.length <= maxLength) {
      return str;
    }

    return str.substr(0, maxLength);
  };

  setre.utils.truncateStringWithPostfix = function (str, maxLength, postfix) {
    postfix = postfix || '...';

    if (!str || !str.length || str.length <= maxLength) {
      return str;
    }

    if (maxLength <= postfix.length) {
      return postfix.substr(0, maxLength);
    }

    return str.substr(0, maxLength - postfix.length) + postfix;
  };

  setre.utils.isFunction = function (obj) {
    if ($) {
      //Prefer to use jQuery if possible
      return $.isFunction(obj);
    }

    //alternative for $.isFunction
    return !!(obj && obj.constructor && obj.call && obj.apply);
  };

  setre.utils.buildQueryString = function (parameterInfos, includeQuestionMark) {
    if (includeQuestionMark === undefined) {
      includeQuestionMark = true;
    }


    var qs = '';

    function addSeperator() {
      if (!qs.length) {
        if (includeQuestionMark) {
          qs = qs + '?';
        }
      } else {
        qs = qs + '&';
      }
    }

    for (var i = 0; i < parameterInfos.length; ++i) {
      var parameterInfo = parameterInfos[i];
      if (parameterInfo.value === undefined) {
        continue;
      }

      if (parameterInfo.value === null) {
        parameterInfo.value = '';
      }

      addSeperator();

      if (parameterInfo.value.toJSON && typeof parameterInfo.value.toJSON === "function") {
        qs = qs + parameterInfo.name + '=' + encodeURIComponent(parameterInfo.value.toJSON());
      } else if (Array.isArray(parameterInfo.value) && parameterInfo.value.length) {
        for (var j = 0; j < parameterInfo.value.length; j++) {
          if (j > 0) {
            addSeperator();
          }

          qs = qs + parameterInfo.name + '[' + j + ']=' + encodeURIComponent(parameterInfo.value[j]);
        }
      } else {
        qs = qs + parameterInfo.name + '=' + encodeURIComponent(parameterInfo.value);
      }
    }

    return qs;
  };

  setre.utils.setLocalStorage = function (key, value) {
    localStorage.setItem(key, value);
  };

  setre.utils.getLocalStorage = function (key) {
    return localStorage.getItem(key);
  };

  setre.utils.deleteLocalStorage = function (key) {
    localStorage.removeItem(key);
  };

  setre.utils.setCookieValue = function (key, value, expireDate, path, domain) {
    var cookieValue = encodeURIComponent(key) + '=';

    if (value) {
      cookieValue = cookieValue + encodeURIComponent(value);
    }

    if (expireDate) {
      cookieValue = cookieValue + "; expires=" + expireDate.toUTCString();
    }

    if (path) {
      cookieValue = cookieValue + "; path=" + path;
    }

    if (domain) {
      cookieValue = cookieValue + "; domain=" + domain;
    }

    document.cookie = cookieValue;
  };

  setre.utils.getCookieValue = function (key) {
    var equalities = document.cookie.split('; ');
    for (var i = 0; i < equalities.length; i++) {
      if (!equalities[i]) {
        continue;
      }

      var splitted = equalities[i].split('=');
      if (splitted.length !== 2) {
        continue;
      }

      if (decodeURIComponent(splitted[0]) === key) {
        return decodeURIComponent(splitted[1] || '');
      }
    }

    return null;
  };

  setre.utils.deleteCookie = function (key, path) {
    var cookieValue = encodeURIComponent(key) + '=';

    cookieValue = cookieValue + "; expires=" + (new Date(new Date().getTime() - 86400000)).toUTCString();

    if (path) {
      cookieValue = cookieValue + "; path=" + path;
    }

    document.cookie = cookieValue;
  };

  setre.utils.checkImage = img => {
    var image = new Image();
    image.src = `https://api.setre.com/Uploads/${img}`;
    if (image.width === 0) {
      return false;
    } else {
      return true;
    }
  };

  setre.utils.checkImageFunction = (imageSrc, good, bad) => {
    let img = new Image();
    img.onload = good;
    img.onerror = bad;
    img.src = imageSrc;
  };


  setre.utils.buildFormData = function (formData, data, parentKey) {
    if (data && typeof data === "object" && !(data instanceof Date) && !(data instanceof File)) {
      Object.keys(data).forEach(key => {
        setre.utils.buildFormData(formData, data[key], parentKey ? `${parentKey}[${key}]` : key);
      });
    } else {
      const value = data === null ? "" : data;

      formData.append(parentKey, value);
    }
  };

  setre.utils.jsonToFormData = convertData => {

    const formData = new FormData();
    setre.utils.buildFormData(formData, convertData);
    return formData;
  };

  /* TIMING *****************************************/
  setre.timing = setre.timing || {};

  setre.timing.utcClockProvider = (function () {

    var toUtc = function (date) {
      return Date.UTC(
        date.getUTCFullYear(),
        date.getUTCMonth(),
        date.getUTCDate(),
        date.getUTCHours(),
        date.getUTCMinutes(),
        date.getUTCSeconds(),
        date.getUTCMilliseconds()
      );
    };

    var now = function () {
      return new Date();
    };

    var normalize = function (date) {
      if (!date) {
        return date;
      }

      return new Date(toUtc(date));
    };

    // Public interface ///////////////////////////////////////////////////

    return {
      now: now,
      normalize: normalize,
      supportsMultipleTimezone: true
    };
  })();

  setre.timing.localClockProvider = (function () {

    var toLocal = function (date) {
      return new Date(
        date.getFullYear(),
        date.getMonth(),
        date.getDate(),
        date.getHours(),
        date.getMinutes(),
        date.getSeconds(),
        date.getMilliseconds()
      );
    };

    var now = function () {
      return toLocal(new Date());
    };

    var normalize = function (date) {
      if (!date) {
        return date;
      }

      return toLocal(date);
    };

    // Public interface ///////////////////////////////////////////////////

    return {
      now: now,
      normalize: normalize,
      supportsMultipleTimezone: false
    };
  })();

  setre.timing.unspecifiedClockProvider = (function () {

    var now = function () {
      return new Date();
    };

    var normalize = function (date) {
      return date;
    };

    // Public interface ///////////////////////////////////////////////////

    return {
      now: now,
      normalize: normalize,
      supportsMultipleTimezone: false
    };
  })();

  setre.timing.convertToUserTimezone = function (date) {
    var localTime = date.getTime();
    var utcTime = localTime + date.getTimezoneOffset() * 60000;
    var targetTime = parseInt(utcTime) + parseInt(setre.timing.timeZoneInfo.windows.currentUtcOffsetInMilliseconds);
    return new Date(targetTime);
  };

  /* CLOCK *****************************************/
  setre.clock = setre.clock || {};

  setre.clock.now = function () {
    if (setre.clock.provider) {
      return setre.clock.provider.now();
    }

    return new Date();
  };

  setre.clock.normalize = function (date) {
    if (setre.clock.provider) {
      return setre.clock.provider.normalize(date);
    }

    return date;
  };

  setre.clock.provider = setre.timing.unspecifiedClockProvider;

  /* DevExtreme Library ***************************************/


  DevExpress.config({
    editorStylingMode: "outlined"
  });

  setre.utils.customStore = (id, moduleName, getMethod, insertMethod, customQuery = "") => {
    insertMethod = insertMethod.length === 0 ? "Insert" : insertMethod;
    var query = customQuery.length === 0 ? "" : customQuery;
    return new DevExpress.data.CustomStore({
      key: id,
      load: function (loadOptions) {
        return setre.requests.dxRequest(moduleName + "/" + getMethod + query);
      },
      insert: function (values) {
        return setre.requests.dxRequest(moduleName + "/" + insertMethod, "POST", JSON.stringify(values));
      },
      update: function (key, values) {
        return setre.requests.dxRequest(moduleName + "/Update", "PUT", JSON.stringify(values));
      },
      remove: function (key) {
        var values = setre.requests.getById(moduleName + "/GetById", key);
        return setre.requests.dxRequest(moduleName + "/Delete", "DELETE", JSON.stringify(values));
      }
    });
  };

  setre.utils.arrayStore = (id, moduleName, getMethod, insertMethod) => {
    insertMethod = insertMethod.length === 0 ? "Insert" : insertMethod;
    return new DevExpress.data.DataSource({
      load: function () {
        return setre.requests.dxRequest(moduleName + "/" + getMethod);
      },
      insert: function (values) {
        return setre.requests.dxRequestCustom(moduleName + "/" + insertMethod, "POST", JSON.stringify(values));
      },
      update: function (key, values) {
        return setre.requests.dxRequestCustom(moduleName + "/Update", "PUT", JSON.stringify(values));
      },
      remove: function (key) {
        const values = setre.requests.getById(moduleName + "/GetById", key.id);
        return setre.requests.dxRequestCustom(moduleName + "/Delete", "DELETE", JSON.stringify(values));
      }
    });
  };

  /* Request Library ***************************************/

  var errorSelector = err => {

    if (err.status === 401 || err.status === 403)
      DevExpress.ui.notify({
        message: setre.utils.isNullorEmpty(err.message) ? "Bu modül üzerinde görüntüleme yetkiniz yok!!" : err.message
      }, "warning", 3000);
    else if (err.status === 400)
      DevExpress.ui.notify({
        message: setre.utils.isNullorEmpty(err.message) ? "Bad Request, Eksik parametre veya yanlış adres nedeniyle istek yerine getirilemiyor." : err.message
      }, "warning", 3000);
    else if (err.status === 404)
      DevExpress.ui.notify({
        message: setre.utils.isNullorEmpty(err.message) ? "İstek yapılan adres bulunamadı." : err.message
      }, "warning", 3000);
    else if (err.status === 409)
      DevExpress.ui.notify({
        message: setre.utils.isNullorEmpty(err.message) ? "İstek, kaynağın mevcut durumu ile bir çakışma nedeniyle tamamlanamadı." : err.message
      }, "warning", 3000);
    else if (err.status === 500)
      DevExpress.ui.notify({
        message: setre.utils.isNullorEmpty(err.message) ? "Sunucu hatası, bir şeyler yanlış gitti." : err.message
      }, "warning", 3000);
    else if (err.status === 502)
      DevExpress.ui.notify({
        message: setre.utils.isNullorEmpty(err.message) ? "Sunucu hatası, bir şeyler yanlış gitti. " : err.message
      }, "warning", 3000);
    else
      DevExpress.ui.notify({
        message: setre.utils.isNullorEmpty(err.message) ? "Sunucu hatası, bir şeyler yanlış gitti." : err.message
      }, "warning", 3000);
  };


  setre.utils.responseMessage = err => {

    if (!err.responseJSON) {
      if (err.status === 401)
        return !err.responseText
          ? "Bu modül üzerinde görüntüleme yetkiniz yok!!"
          : err.responseText;
      else if (err.status === 403)
        return !err.responseText
          ? "Bu işlemi yapmaya yetkiniz yoktur!"
          : err.responseText;
      else if (err.status === 400)
        return !err.responseText
          ? "Bad Request, Eksik parametre veya yanlış adres nedeniyle istek yerine getirilemiyor."
          : err.responseText;
      else if (err.status === 404)
        return !err.responseText
          ? "İstek yapılan adres bulunamadı."
          : err.responseText;
      else if (err.status === 409)
        return !err.responseText
          ? "İstek, kaynağın mevcut durumu ile bir çakışma nedeniyle tamamlanamadı."
          : err.responseText;
      else if (err.status === 500)
        return !err.responseText
          ? "Sunucu hatası, bir şeyler yanlış gitti."
          : err.responseText;
      else if (err.status === 502)
        return !err.responseText
          ? "Sunucu hatası, bir şeyler yanlış gitti. "
          : err.responseText;
      else
        return !err.responseText
          ? "Sunucu hatası, bir şeyler yanlış gitti."
          : err.responseText;
    } else {


      if (err.status === 401)
        return !err.responseJSON
          ? "Bu modül üzerinde görüntüleme yetkiniz yok!!"
          : err.responseJSON.message;
      else if (err.status === 403)
        return !err.responseJSON
          ? "Bu işlemi yapmaya yetkiniz yoktur!"
          : err.responseJSON.message;
      else if (err.status === 400)
        return !err.responseJSON
          ? "Bad Request, Eksik parametre veya yanlış adres nedeniyle istek yerine getirilemiyor."
          : err.responseJSON.message;
      else if (err.status === 404)
        return !err.responseJSON
          ? "İstek yapılan adres bulunamadı."
          : err.responseJSON.message;
      else if (err.status === 409)
        return !err.responseJSON
          ? "İstek, kaynağın mevcut durumu ile bir çakışma nedeniyle tamamlanamadı."
          : err.responseJSON.Mmessage;
      else if (err.status === 500)
        return !err.responseJSON
          ? "Sunucu hatası, bir şeyler yanlış gitti."
          : err.responseJSON.message;
      else if (err.status === 502)
        return !err.responseJSON
          ? "Sunucu hatası, bir şeyler yanlış gitti. "
          : err.responseJSON.message;
      else
        return !err.responseJSON
          ? "Sunucu hatası, bir şeyler yanlış gitti."
          : err.responseJSON.message;
    }
  };


  function Base64ToBytes(base64) {
    var s = window.atob(base64);
    var bytes = new Uint8Array(s.length);
    for (var i = 0; i < s.length; i++) {
      bytes[i] = s.charCodeAt(i);
    }
    return bytes;
  };

  setre.requests = setre.requests || {};
  setre.requests.downloadFile = (path, formData = null) => {
    let data;
    $.ajax({
      url: setre.appPath + path,
      dataType: "json",
      async: false,
      data: formData,
      beforeSend: function (xhr) {
        xhr.setRequestHeader("Authorization", "Bearer " + token);
      },
      success: function (result) {
        var bytes = Base64ToBytes(result.fileContents);

        //Convert Byte Array to BLOB.
        var blob = new Blob([bytes], { type: "application/octetstream" });

        //Check the Browser type and download the File.
        var isIE = false || !!document.documentMode;
        if (isIE) {
          window.navigator.msSaveBlob(blob, fileName);
        } else {
          var url = window.URL || window.webkitURL;
          link = url.createObjectURL(blob);
          var a = $("<a />");
          a.attr("download", result.fileDownloadName);
          a.attr("href", link);
          data = link;
          //$("body").append(a);
          //a[0].click();
          //$("body").remove(a);
        }
      },
      error: function (err) {
        // setre.alert.error(setre.utils.responseMessage(err));
        data = err;
        console.log("crudjs>downloadFile():", "Hata oluştu...=>" + JSON.stringify(err));
        result = err;
      }
    });
    return data;

  };
  setre.requests.downloadFiles = (path, formData = null) => {
    let data;
    $.ajax({
      url: path,
      dataType: "json",
      method: "POST",
      contentType: "application/json; charset=utf-8",
      async: true,
      data: formData,
      beforeSend: function (xhr) {
        xhr.setRequestHeader("Authorization", "Bearer " + token);
      },
      success: function (result) {
        var bytes = Base64ToBytes(result.fileContents);

        //Convert Byte Array to BLOB.
        var blob = new Blob([bytes], { type: "application/octetstream" });

        //Check the Browser type and download the File.
        var isIE = false || !!document.documentMode;
        if (isIE) {
          window.navigator.msSaveBlob(blob, fileName);
        } else {
          var url = window.URL || window.webkitURL;
          link = url.createObjectURL(blob);
          var a = $("<a />");
          a.attr("download", result.fileDownloadName);
          a.attr("href", link);
          data = link;
          //$("body").append(a);
          //a[0].click();
          //$("body").remove(a);
        }
      },
      error: function (err) {
        // setre.alert.error(setre.utils.responseMessage(err));
        data = err;
        console.log("crudjs>downloadFile():", "Hata oluştu...=>" + JSON.stringify(err));
        result = err;
      }
    });
    return data;

  };
  setre.requests.getAll = path => {
    let data;
    $.ajax({
      url: setre.appPath + path,
      dataType: "json",
      async: false,
      beforeSend: function (xhr) {
        xhr.setRequestHeader("Authorization", "Bearer " + token);
        xhr.setRequestHeader("Access-Control-Allow-Origin", "*")
      },
      success: function (result) {
        data = setre.utils.isNullorEmpty(result.data) ? result : result.data;
      },
      error: function (err) {
        errorSelector(err);
        console.log("crudjs>getAll():", "Hata oluştu...=>" + JSON.stringify(err));
      }
    });
    return data;

  };
  setre.requests.getById = (path, id) => {
    var data;
    $.ajax({
      url: setre.appPath + path + "?id=" + id,
      dataType: "json",
      async: false,
      beforeSend: function (xhr) {
        xhr.setRequestHeader("Authorization", "Bearer " + token);
      },
      success: function (result) {
        data = setre.utils.isNullorEmpty(result.data) ? result : result.data;
      },
      error: function (err) {
        errorSelector(err);

        console.log("crudjs>getById():", "Hata oluştu...=>" + JSON.stringify(err));
      }
    });
    return data;
  };
  setre.requests.getByObj = (path, data) => {
    var res;
    var query = '';
    if (!setre.utils.isNullorEmpty(data))
      query = setre.utils.buildQueryString(data);

    $.ajax({
      url: setre.appPath + path + query,
      async: false,
      beforeSend: function (xhr) {
        xhr.setRequestHeader("Authorization", "Bearer " + token);
      },
      success: function (result) {
        res = result; //isNullorEmpty(result.data) ? result : result.data;
      },
      error: function (err) {
        errorSelector(err);

        console.log("crudjs>getById():", "Hata oluştu...=>" + JSON.stringify(err));
      }
    });
    return res;
  };
  setre.requests.insert = (path, data, isFromQuery = false) => {
    var query = isFromQuery ? setre.utils.buildQueryString(data) : "";
    var result;
    $.ajax({
      url: setre.appPath + path + query,
      method: "POST",
      async: false,
      data: JSON.stringify(data),
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      beforeSend: function (xhr) {
        xhr.setRequestHeader("Authorization", "Bearer " + token);
      },
      success: function (response) {
        if (!setre.utils.isNullorEmpty(response)) {
          if (response.success) {
            setre.alert.success(response.message === null
              ? "İşleminiz başarıyla gerçekleşti."
              : response.message);
            result = response.data;
          }
        }
      },
      error: function (err) {
        setre.alert.error(setre.utils.responseMessage(err));
        console.log("crudjs>create():", "Hata oluştu...=>" + JSON.stringify(err));
        result = err;
      }
    });
    return result;
  };
  setre.requests.update = (path, data, isFromQuery = false) => {
    var query = isFromQuery ? setre.utils.buildQueryString(data) : '';
    var result;
    $.ajax({
      url: setre.appPath + path + query,
      method: "PUT",
      async: false,
      data: JSON.stringify(data),
      contentType: "application/json",
      beforeSend: function (xhr) {
        xhr.setRequestHeader("Authorization", "Bearer " + token);
      },
      success: function (response) {
        if (!setre.utils.isNullorEmpty(response)) {
          if (response.success) {
            setre.alert.success(response.message === null
              ? "İşleminiz başarıyla gerçekleşti."
              : response.message);
          }
        }
        result = response;
      },
      error: function (err) {
        errorSelector(err);
        console.log("crudjs>update():", "Hata oluştu...=>" + JSON.stringify(err));
        result = err;
      }
    });
    return result;
  };
  setre.requests.delete = (moduleName, data, isCustom = false) => {
    const customTag = isCustom ? "" : "/Delete";
    var result;
    $.ajax({
      url: setre.appPath + moduleName + customTag,
      method: "DELETE",
      async: false,
      data: JSON.stringify(data),
      contentType: "application/json",
      beforeSend: function (xhr) {
        xhr.setRequestHeader("Authorization", "Bearer " + token);
      },
      success: function (response) {
        if (!setre.utils.isNullorEmpty(response)) {
          if (response.success) {
            setre.alert.success(response.message === null
              ? "İşleminiz başarıyla gerçekleşti."
              : response.message);
          }
        }
        result = response;
      },
      error: function (err) {
        errorSelector(err);
        console.log("crudjs>del():", "Hata oluştu...=>" + JSON.stringify(err));
        result = err;
      }
    });
    return result;

  };
  setre.requests.logout = () => {
    var user = _user;
    $.ajax({
      url: "/Account/LogOff",
      async: true,
      success: function (result) {
        if (result.success) {
          localStorage.clear();
          location.href = "/Account/Login";
        } else errorSelector(result);
      },
      error: function (err) {
        errorSelector(err);
        console.log("crudjs>getAll():", "Hata oluştu...=>" + JSON.stringify(err));
      }
    });
  };
  setre.requests.login = data => {
    Notiflix.Loading.Dots("Giriş yapılıyor...");
    $.ajax({
      url: "/Account/Login",
      method: "POST",
      async: true,
      data: JSON.stringify(data),
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function (response) {
        if (!setre.utils.isNullorEmpty(response)) {
          if (response.success) {
            localStorage.clear();
            setre.auth.setTokenStorage(response.data.token);
            delete response.data.token;
            delete response.data.isAuthenticated;
            delete response.data.expiration;
            setre.utils.setLocalStorage("user", JSON.stringify(setre.requests.getById("User/GetById", response.data.userId)));
            setre.alert.success(response.message);
            window.location = response.data.returnUrl;
          } else {
            errorSelector(response);
          }
        }
        Notiflix.Loading.Remove(600);
      },
      error: function (err) {
        errorSelector(err);
        console.log("crudjs>getAll():", "Hata oluştu...=>" + JSON.stringify(err));
        Notiflix.Loading.Remove(600);
      }
    });
  };
  setre.requests.importFile = async (path, data, method = "POST") => {
    var result;
    await $.ajax({
      url: setre.appPath + path,
      method: method,
      data: data,
      contentType: false,
      async: true,
      cache: false,
      processData: false,
      beforeSend: function (xhr) {
        xhr.setRequestHeader("Authorization", "Bearer " + token);
      },
      success: function (response) {
        if (!setre.utils.isNullorEmpty(response)) {
          if (response.success) {
            setre.alert.success(response.message === null
              ? "İşleminiz başarıyla gerçekleşti."
              : response.message);
          }
        }
        result = response;
      },
      error: function (err) {
        errorSelector(err);
        console.log("crudjs>del():", "Hata oluştu...=>" + JSON.stringify(err));
        result = err;
      }
    });
    return result;

  };

  setre.requests.uploadFile = (path, data, method = "POST") => {
    var result;
    $.ajax({
      url: setre.appPath + path,
      method: method,
      data: data,
      contentType: false,
      async: false,
      cache: false,
      processData: false,
      beforeSend: function (xhr) {
        xhr.setRequestHeader("Authorization", "Bearer " + token);
      },
      success: function (response) {
        if (!setre.utils.isNullorEmpty(response)) {
          if (response.success) {
            setre.alert.success(response.message === null
              ? "İşleminiz başarıyla gerçekleşti."
              : response.message);
          }
        }
        result = response;
      },
      error: function (err) {
        errorSelector(err);
        console.log("crudjs>del():", "Hata oluştu...=>" + JSON.stringify(err));
        result = err;
      }
    });
    return result;

  };
  setre.requests.dxRequest = (path, method, data, isFromQuery = false) => {
    var query = isFromQuery ? setre.utils.buildQueryString(data) : "";
    var d = $.Deferred();
    method = method || "GET";


    $.ajax(setre.appPath + path + query, {
      method: method,
      data: data,
      cache: false,
      xhrFields: {
        withCredentials: false
      },
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      beforeSend: function (xhr) {
        xhr.setRequestHeader("Authorization", `Bearer ${token}`);
      }
    }).done(function (response) {
      d.resolve(method === "GET" ? response.data : response);
      if (!setre.utils.isNullorEmpty(response)) {
        if (response.success)
          setre.alert.success(response.message === null
            ? "Listeleme işlemi başarıyla gerçekleşti."
            : response.message);
      }
    }).fail(function (xhr) {
      setre.alert.error(setre.utils.responseMessage(xhr));
      d.reject(setre.utils.responseMessage(xhr));
    });

    return d.promise();
  };


  setre.requests.dxRequestCustom = (path, method, data, isFromQuery = false) => {
    var query = isFromQuery ? setre.utils.buildQueryString(data) : "";
    var d = $.Deferred();
    method = method || "GET";


    if (method === "GET") {
      d.resolve(data);
    } else {
      $.ajax(setre.appPath + path + query, {
        method: method,
        data: data,
        cache: false,
        xhrFields: {
          withCredentials: false
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        beforeSend: function (xhr) {
          xhr.setRequestHeader("Authorization", `Bearer ${token}`);
        }
      }).done(function (response) {
        d.resolve(method === "GET" ? response.data : response);
        if (!setre.utils.isNullorEmpty(response)) {
          if (response.success)
            setre.alert.success(response.message === null
              ? "Listeleme işlemi başarıyla gerçekleşti."
              : response.message);
        }
      }).fail(function (xhr) {
        setre.alert.error(setre.utils.responseMessage(xhr));
        d.reject(setre.utils.responseMessage(xhr));
      });
    }

    return d.promise();
  };
})();

bu js kodunu react typescript koduna çevirir misin?