/*Data  loading  start here*/
import {getCookie, isAuthenticated} from "./cookiehelper.js";
import {getData, getDataObj} from "./base.js";
import {_serverUrl} from "./setting.js";
export var connection;

export function dateTimeFormat(dateTime) {
  var date = moment.utc(dateTime).local();
  var difmonths = moment().diff(date, "months");
  if (difmonths == 0) {
    return moment(dateTime).fromNow();
  }
  return date.format("DD MMM, YYYY HH:mm");
}
function createLoad(data) {
  let html = "";
  if (data.length != 0) {
    for (var i = 0; i < data.length; i++) {
      html += `<li class="p-0">
        <a href="javascript:;" class="dropdown-item create-form-btn" data-AppConfigType="${data[i].AppConfigType}" data-AppPermissionId="${data[i].AppPermissionId}" data-AppConfigurationId="${data[i].AppConfigurationId}" data-formid="${data[i].FormId}" data-installedAppid="${data[i].InstalledAppId}">${data[i].AppTitle}</a>
      </li>`;
    }
  } else {
    html += `<li class="p-0">Apps are Not Installed</li>`;
  }
  $("#crte-btn-lst").html(html);
  $(".create-form-btn").on("click", function () {
    const date = new Date();
    let number = date.getTime();
    let serverUrl = _serverUrl();
    let appName = $(this).text();
    let formId = $(this).attr("data-formid");
    let installedAppId = $(this).attr("data-installedappid");
    let appConfigurationId = $(this).attr("data-appconfigurationid");
    let pk_id = 0;
    const cookie = getCookie("_idty");
    let fomrhtml = "";
    let width = iFrmeWdth();
    if (cookie) {
      const {unibaseId, tenantId, userId} = JSON.parse(cookie);

      fomrhtml = `<div>
                    <div class="frm-ifre frm-ifre-${number}" data-formId="${formId}" id="frm-ifre-${number}" style="right:${width}px">
                      <div>
                        <ul class="m-0 p-0">
                          <li class="frm-hdr d-none" data-frm_hdr="true">
                            <div class="app-title-ifrm">${appName}</div>
                            <div class="ctrl">
                              <a href="javascript:;" class="minimize" data-unid="${number}" data-ispopup="true"><span><i class="la la-minus"></i></span></a>
                              <a href="javascript:;" class="maximum" data-unid="${number}"><span><i class="la la-expand"></i></span></a>
                              <a href="javascript:;" class="compress d-none" data-unid="${number}"><span><i class="las la-compress"></i></span></a>
                              <a href="javascript:;" class="close" data-unid="${number}"><span><i class="la la-times"></i></span></a>
                            </div>
                          </li>
                          <li class="frm-bdy">
                            <iframe class="ld-frm-src" data-ispopup="false" src="${serverUrl}#/${unibaseId}/${tenantId}/${userId}/${installedAppId}/${formId}/0/${appConfigurationId}/false/0/loadform"></iframe>
                          </li>
                          <li class="frm-ftr"></li>
                        </ul>
                      </div>
                    </div>
                  </div>`;
    }
    $("#list-page").parent("body").append(fomrhtml);
    window.window.postMessage("ld-frm-ifrme", "*");
    hdrCrtnClckEvnt(number);
  });
}

function hdrCrtnClckEvnt(number) {
  $(`.frm-ifre-${number} .minimize`).on("click", function () {
    let id = $(this).attr("data-unid");
    let isPopUpState = $(this).attr("data-ispopup");
    let height = $(`.frm-ifre-${id}`).find(".frm-hdr").height();
    $(".list-page").css({filter: "unset", opacity: 1});
    $(`.frm-ifre-${id} .frm-bdy`).toggleClass("d-none");
    if (isPopUpState == "true") {
      // popup large
      $(this).attr("data-ispopup", "false");
      $(this).parents('.frm-hdr').removeClass('d-none').attr('data-frm_hdr', 'false');
      $(`.frm-ifre-${id} .maximum`).addClass("d-none");
      $(`.frm-ifre-${id} .minimize`).attr("data-ispopup", "false");
      $(`.frm-ifre-${id}`).parent().removeClass("wrap-iframe");
      $(`.frm-ifre-${id}`).attr("data-ispop_up", "false");
      $(`.frm-ifre-${id}`).css({
        width: "20%",
        height: height,
        bottom: "0px",
      });
    } else {
      // popup small
      $(this).attr("data-ispopup", "true");
      $(this).parents('.frm-hdr').addClass('d-none').attr('data-frm_hdr', 'true');
      $(`.frm-ifre-${id} .maximum`).removeClass("d-none");
      $(`.frm-ifre-${id} .minimize`).attr("data-ispopup", "true");
      $(`.frm-ifre-${id}`).attr("data-ispop_up", "true");
      $(`.frm-ifre-${id}`).css({
        width: "",
        height: "",
        bottom: "",
      });
      if($(this).parents('.frm-hdr').attr("data-saveform") == 'true'){
        $(this).parents('.frm-hdr').removeClass('d-none')
      }
    }
    resetwidth();
  });
  $(`.frm-ifre-${number} .maximum`).on("click", function () {
    let id = $(this).attr("data-unid");
    $(this).addClass("d-none");
    $(this).siblings(".compress").removeClass("d-none");
    $(`.frm-ifre-${id}`).find(".ld-frm-src").attr("data-ispopup", "true");
    $(`.frm-ifre-${id}`).parent().addClass("wrap-iframe");
    $(`.frm-ifre-${id}`).css({width: "75%", position: "unset"});
    $(`.frm-ifre-${id} .ld-frm-src`).css({width: "100%"});
    $(`.frm-ifre-${id} .frm-bdy`).removeClass("d-none");
    $("#list-page").css({filter: "blur(2px)", opacity: "0.5"});
    $(`.frm-ifre-${id}`).find(".minimize").toggleClass("d-none");
  });
  $(`.frm-ifre-${number} .compress`).on("click", function () {
    let id = $(this).attr("data-unid");
    $(this).addClass("d-none");
    $(this).siblings(".maximum").removeClass("d-none");
    $(`.frm-ifre-${id}`).parent().removeClass("wrap-iframe");
    $(`.frm-ifre-${id}`).css({width: "", position: ""});
    $(`.frm-ifre-${id} .ld-frm-src`).css({width: ""});
    $("#list-page").css({filter: "", opacity: ""});
    $(`.frm-ifre-${id}`).find(".minimize").toggleClass("d-none");
  });
  $(`.frm-ifre-${number} .close`).on("click", function () {
    let id = $(this).attr("data-unid");
    $("#list-page").css({filter: "unset", opacity: "1"});
    $(`.frm-ifre-${id}`).parent().remove();
    resetwidth();
  });
}
function loadData(ApiPath, isSentBy) {
  $(".bdy-ul").empty().removeClass("d-none");
  $(".hdr-ul").removeClass("d-none");
  getData(ApiPath).then(function (result) {
    let response = JSON.parse(result.result),
      html = "";
    const cookie = getCookie("_idty");
    if (response.length != 0) {
      response.forEach(function (Item, index) {
        let isSent = false;
        if (Item.FromUserName == JSON.parse(cookie).name) {
          isSent = true;
        }
        if (Item.FromUserName == null) {
          Item.FromUserName = 'Please check it Notification Team';
        }
        //if(window.innerWidth >1024){    // Desktop Width
          html += `<li class="pdng lst-Notifi" data-ReminderTypeId="${Item.ReminderTypeId}" data-reminderurl="${Item.ReminderUrl}" data-reminderId="${Item.ReminderId}" data-isreaded="${Item.ReminderStatusId}" data-issentby=${isSent} data-refId="${Item.RedirectOptions.RefId}" data-instlledAppId="${Item.RedirectOptions.InstalledAppId}" data-formid="${Item.RedirectOptions.CreateFormId}" data-urlType="${Item.UrlType}">`;
          html += `<div class="flex-shrink-0 wi-chck"><div class="wi-item ml-0"><input class="form-check-input mr-2" type="checkbox" value="" id="flexCheckDefault"></div><div class="wi-item">`;
          if (Item.ReminderTypeId == 1) {
            html += `<i class="ri-star-fill" style="opacity:0.6"></i>`;
          } else {
            html += `<i class="ri-star-line"></i>`;
          }
          html += `</div></div>`; // check-box
          html += `<div class="wi-sbjt-msge mx-1">`;
          html += `<div class="wi-from wi-item text-truncate"><span  data-isreaded="${Item.ReminderStatusId}">${Item.FromUserName}</span></div>`;
          html += `<div class="wi-sbjt wi-item text-truncate flex-shrink-1"><span class="mx-2">${Item.Subject}</span></div><div>-</div>`; // Subject
          html += `<div class="wi-msge wi-item text-truncate"><span class="mx-2">${Item.Message}</span></div>`; // Message
          html += `</div>`;
          html += `<div class="wi-time time flex-shrink-0 ml-auto"><span>${dateTimeFormat(
            Item.ReminderDate
          )}</span></div>`;
          html += `<div class="hover">
                      <ul>`;
          if (Item.RedirectOptions.CreateFormId != 0) {
            html += `     <li class="mx-2 hover-item"><a class="formBtn" data-urltype="Form" href="javascript:;"><i class="ri-store-line"></i></a></li>`;
          } else {
            html += `     <li class="mx-2 hover-item"><a class="detailBtn" data-urltype=${Item.UrlType} href="javascript:;"><i class="ri-information-line"></i></a></li>`;
          }
          html += `    </ul>
                    </div>`;
          html += "</li>";    
       /* }else{          // Mobile Width card view
          html += `<li class="pdng lst-Notifi" data-ReminderTypeId="${Item.ReminderTypeId}" data-reminderurl="${Item.ReminderUrl}" data-reminderId="${Item.ReminderId}" data-isreaded="${Item.ReminderStatusId}" data-issentby=${isSent} data-refId="${Item.RedirectOptions.RefId}" data-instlledAppId="${Item.RedirectOptions.InstalledAppId}" data-formid="${Item.RedirectOptions.CreateFormId}" data-urlType="${Item.UrlType}">`
          html += ` <div><span class="align-items-center d-flex justify-content-center sdr-nme fs-4">S</span></div>
                    <div class="d-flex flex-column ms-2 w-100">
                      <div class="d-flex justify-content-between align-items-baseline">
                        <span class="me-2 text-truncate">${Item.FromUserName}</span>
                        <span class="w-60p text-truncate font-11">${dateTimeFormat(
            Item.ReminderDate
          )}</span>
                      </div>
                      <div><span class="fw-500">${Item.Subject}</span></div>
                      <div class="d-flex justify-content-between"><span>${Item.Message}</span><span>`;
                      if (Item.ReminderTypeId == 1) {
                        html += `<i class="ri-star-fill" style="opacity:0.6"></i>`;
                      } else {
                        html += `<i class="ri-star-line"></i>`;
                      }
            html +=  `</span></div>
                    </div>`
          html +=`</li>`
        }*/
        
      });
      $(".ctr-lst-pge .bdy-ul").html(html);
      if (isSentBy) {
        $(".pdng.lst-Notifi").addClass("d-none");
        $(".pdng.lst-Notifi[data-issentby='true']").removeClass("d-none");
      }
      detailClick();
      //stagesLoad();
    }
  });

  getData("apis/v4/unibase/reminders/platform/getunreadreminderscount").then(
    function (response) {
      let result = JSON.parse(response.result);
      let count = Number(result.NotificationCount) + Number(result.TasksCount);
      $('[data-buttontype="inbox"] .length.rounded-pill').remove();
      $('[data-buttontype="inbox"]').append(
        `<span class="length badge rounded-pill bg-light text-dark ml-auto" data-TasksCount="${result.TasksCount}" data-notifiCount="${result.NotificationCount}">${count}</span>`
      );
      $('[data-notification="count"]').text(count);
      if (count > 40) {
        $('[data-paggtn="true"]').text(`1-40`);
      } else {
        $(".li-pgn").empty();
      }
    }
  );
  if(window.innerWidth < 1024){
    $('.ctr-lst-pge').on('click', function(){
      $('.mnNvIcn').click()
    })
  }
}
function iFrmeWdth() {
  let width = 0,
    erwdth = 15;
  $(".frm-ifre").each(function (i, e) {
    if ($(this).length == 0) {
      erwdth = 0;
    }
    if (window.innerWidth > width) {
      width = width + $(this).width() + erwdth;
    }
  });
  return width;
}
function resetwidth() {
  let width = 0,
    erwdth = 15;
  $(".frm-ifre").each(function (i, e) {
    if (i == 0) {
      $(this).css("right", width + "px");
    }
    if (i != 0) {
      $(this).css("right", width + "px");
    }
    if (window.innerWidth > width) {
      width = width + $(this).width() + erwdth;
    }
  });
}
export function detailClick() {
  // Details Popup Abihram popup page
  $(".wi-sbjt-msge").on("click", function (e) {
    e.stopPropagation();
    detailsPage(this, true, "Details-page");
  });
  // Details Page Loading
  $(".detailBtn[data-urltype='Details']").click(function (e) {
    e.stopPropagation();
    detailsPage(this, false, "Details-page");
  });
  //Form Page Loading
  $(".formBtn[data-urltype='Form']").on("click", function (e) {
    e.stopPropagation();
    detailsPage(this, true, "Form-page");
  });
  //List Page Loading
  $("[data-urltype='List']").on("click", function (e) {
    e.stopPropagation();
    detailsPage(this, true, "List-page");
  });
  // get stages
}
export function detailsPage(e, ifrmPopup, isPage) {
  let serverUrl = _serverUrl();
  $(".bdy-ul").addClass("d-none");
  $(".hdr-ul").addClass("d-none");
  let installedAppId = $(e)
    .parents(".pdng.lst-Notifi")
    .attr("data-instlledappid");
  let recordId = $(e).parents(".pdng.lst-Notifi").attr("data-refid");
  let reminderid = $(e).parents(".pdng.lst-Notifi").attr("data-reminderid");
  let remindertype = $(e)
    .parents(".pdng.lst-Notifi")
    .attr("data-remindertypeid");
  // Unibase.Themes.Compact.Components.Notification.Instance().loadReminderDetails(105013010001972,105010260000090,'Details','null',6,0,null)
  const cookie = getCookie("_idty");
  if (cookie) {
    const {unibaseId, tenantId, userId} = JSON.parse(cookie);
    if (isPage == "Details-page") {
      $("#detailIframe").html(
        `<iframe width="100%" style="min-height:calc(100vh - ${$(
          ".tp-bar"
        ).height()}px)"  name="srcframe" id="srcframe" class="srcframe" src="${serverUrl}#/${unibaseId}/${tenantId}/${userId}/${recordId}/${installedAppId}/${remindertype}/${reminderid}/${ifrmPopup}/loadDetail"></iframe>`
      );
    } else if (isPage == "Form-page") {
      getData(
        `apis/v4/unibase/platform/apps/listappconfigurations/installedappid/${installedAppId}`
      ).then(function (result) {
        let _data = JSON.parse(result.result);
        let data = _data.filter((x) => x.SettingUrlType == 1);
        $("#detailIframe").html(
          `<iframe width="100%" style="min-height:calc(100vh - ${$(
            ".tp-bar"
          ).height()}px)"  name="srcframe" id="srcframe" class="srcframe" src="${serverUrl}#/${unibaseId}/${tenantId}/${userId}/${installedAppId}/${
            data[0].FormId
          }/0/${
            data[0].AppConfigurationId
          }/${reminderid}/${ifrmPopup}/loadform"></iframe>`
        );
      });
    } else if (isPage == "List-page") {
      $("#detailIframe").html(
        `<iframe width="100%" style="min-height:calc(100vh - ${$(
          ".tp-bar"
        ).height()}px)"  name="srcframe" id="srcframe" class="srcframe" src="${serverUrl}#/${unibaseId}/${tenantId}/${userId}/${installedAppId}/${reminderid}/${ifrmPopup}/loadList"></iframe>`
      );
    }
  }
}
export function signaRInit() {
  var huburl = _serverUrl() + "notificationhub";
  connection = new window["signalR"].HubConnectionBuilder()
    .withUrl(huburl)
    .build();
  register();
}
export async function register() {
  connection.on("sendnotification", (obj) => {
    $(".ctr-lst-pge .bdy-ul").empty();
    loadData(
      "apis/v4/unibase/reminders/platform/getuserreminders/PageSize/0",
      false
    );
  });
  const cookie = getCookie("_idty");
  const {unibaseId, tenantId, userId, sessionId, name} = JSON.parse(cookie);
  let packet = {
    UserId: Number(userId),
    UserName: name,
    UnibaseId: unibaseId,
    TenantId: Number(tenantId),
    SessionId: sessionId,
  };
  try {
    const stringConnection = await connection.start();
    await connection.invoke("Connect", packet);
  } catch (error) {
    console.log(error);
  }
}

export function resetClckEvnt() {
  $(".ChtAppIfrme").remove();
  $(".lft-nav-bar .lft-nav-bar-2").removeClass("d-none");
  $(".ctr-lst-pge, .rtr-nav-bar").removeClass("d-none");
  $(".lft-nav-bar").css("width", "");
}

export function initListIndex() {
  let userInfo = JSON.parse(getCookie("_idty"));
  let sessionId = userInfo.sessionId;

  signaRInit();
  let usrinfoHTML = `<li><a class="dropdown-item text-capitalize" href="javascript:void(0);">${userInfo.name}</a></li>
                    <li><a class="dropdown-item" href="javascript:void(0);">Help</a></li>
                    <li><a class="dropdown-item" href="javascript:void(0);" data-btn="logoff">Logoff</a></li>`;
  $(".icn-circle").text(userInfo?.name?.charAt(0)?.toUpperCase());
  $(".uindtls").html(usrinfoHTML);

  $('[data-btn="logoff"]').on("click", function () {
    document.cookie = "_idty=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
    window.location = "../login";
  });
  // List Page loading

  /*Data  loading  start here*/
  $(".nav-lft-item").on("click", function () {
    $(".nav-lft-item").removeClass("active");
    $(this).addClass("active");
    if ($(this).attr("data-application") != "Chat Application") {
      resetClckEvnt();
    }
  });
  $(".nav-lft-item[data-application='Chat Application']").on(
    "click",
    function () {
      const serverUrl = _serverUrl();
      const cookie = getCookie("_idty");
      const {unibaseId, tenantId, userId} = JSON.parse(cookie);
      $(".lft-nav-bar .lft-nav-bar-2").addClass("d-none");
      $(".ctr-lst-pge, .rtr-nav-bar").addClass("d-none");
      $(".lft-nav-bar").css("width", "var(--rtrWidth)");
      $(".btm-bar .ChtAppIfrme").remove();
      $(".btm-bar").append(`<div class="ChtAppIfrme w-100">
                  <iframe class="" style="height:100%; width:100%" data-ispopup="false" src="${serverUrl}#/${unibaseId}/${tenantId}/${userId}/loadChat"></iframe>
                </div>`);
    }
  );
  $(".mnNvIcn").click(function () {
      $(".lft-nav-bar").toggleClass("lft-nav-bar-Wrap");
      $(".ctr-lst-pge").toggleClass("lft-nav-bar-Wrap");
      if ($(".apps-loading:visible").length != 0) {
        $(".ctr-lst-pge").css("width", "");
        $(".ctr-lst-pge").toggleClass("apps-loaded");
        $(".ctr-lst-pge").toggleClass("apps-loaded-tr");
      }    
      if(window.innerWidth < 1025){
        $(".ctr-lst-pge").toggleClass('d-block');
        $(".lft-nav-bar").toggleClass("lft-nav-bar-Wrap d-flex w-100").css('background-color','rgb(0 0 0 / 50%)');
      }
  });
  $(".mre-drp a.sub-nav-item.more").on("click", function () {
    $(".sub-nav-item").removeClass("active");
    if ($(this)[0].className.includes("active")) {
      $(this).find("i").css("transform", "rotate(0deg)");
      $(this).removeClass("active");
    } else {
      $(this).find("i").css("transform", "rotate(180deg)");
      $(this).addClass("active");
    }
    $(this).siblings(".ul-drpdown").toggleClass("d-none");
  });
  $("a.sub-nav-item")
    .not(".more.active")
    .on("click", function () {
      $(".sub-nav-item").not(".more.active").removeClass("active");
      $(this).addClass("active");
    });

  $('[data-buttontype="inbox"], [data-application="Mail Application"]').on(
    "click",
    function () {
      $("#detailIframe").empty();
      loadData(
        "apis/v4/unibase/reminders/platform/getuserreminders/PageSize/0",
        false
      );
    }
  );
  window.addEventListener("message", function (e) {
    if (e.data != undefined) {
      if(e.data == "Edit-form"){
        $('.frm-hdr').addClass('d-none')
      }
      if (e.data == "closeForm") {
        $("#detailIframe").empty();
        $(".hdr-ul, .bdy-ul").removeClass("d-none");
        $('.frm-bdy [class="close"]')[0].click();
      }
      if (e.data == "clickToBack") {
        $("#detailIframe").empty();
        loadData(
          "apis/v4/unibase/reminders/platform/getuserreminders/PageSize/0",
          false
        );
      }
      if (e.data.includes("save-form")) {
        let spilt = e.data.split("/");
        $(`.frm-ifre[data-formid="${spilt[1]}"] .frm-hdr`).removeClass(
          "d-none"
        ).attr('data-frm_hdr','false');
      }
      if (e.data == "close apps") {
        $("body").removeClass("d-flex flex-row");
        $("#detailIframe").empty();
        $(".hdr-ul, .bdy-ul").removeClass("d-none");
        $(".apps-loading").remove();
        $("#list-page").css("width", "100%");
        $(".lft-nav-bar").removeClass(".lft-nav-bar-Wrap");
        $(".ctr-lst-pge").removeClass("apps-loaded");
        $(".ctr-lst-pge").removeClass("apps-loaded-tr");
      }
      if (e.data.includes("/")) {
        let spilt = e.data.split("/");
        $(
          `.frm-ifre[data-formid="${spilt[1]}"] .frm-hdr .ctrl .${spilt[0]}`
        ).click();
        if(spilt[0].includes('success')){
          $(`.frm-ifre[data-formid="${spilt[1]}"] .frm-hdr`).removeClass("d-none").attr({'data-frm_hdr': 'false', 'data-saveform':'true'});
        }
        if(!spilt[0].includes('maximum') && !spilt[0].includes('compress')){
          $(`.frm-ifre[data-formid="${spilt[1]}"] .frm-hdr`).removeClass("d-none").attr({'data-frm_hdr': 'false'});
        }
      }
      if (e.data == "closeForm_detailIframe") {
        $("#detailIframe").empty();
        $(".hdr-ul, .bdy-ul").removeClass("d-none");
      }
    }
  });
  $('[class="refrsh"]').on("click", function () {
    loadData(
      "apis/v4/unibase/reminders/platform/getuserreminders/PageSize/0",
      false
    );
  });

  getData("apis/v4/unibase/platform/apps/myapps").then(function (response) {
    if(response.message.includes("User Authentication Failed")){
          window.location = "../login";
    }else{
      let result = JSON.parse(response.result);
      let html = "<li class='m-0 p-0'><ul class='d-flex flex-wrap m-0 p-0'>";
      for (var i = 0; i < result.length; i++) {
        html += `<li class="appsBind" data-myappid="${result[i].MyAppId}">`;
        if (
          result[i].SvgIconUrl != undefined &&
          result[i].SvgIconUrl != null &&
          result[i].SvgIconUrl != ""
        ) {
          html += `<span class="svg-icons">${result[i].SvgIconUrl}</span>`;
        } else {
          html +=
            '<span class="svg-icons"><svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">   <path class="biz-svg-highlight-color" d="M16.01,31c-1.38,0-2.77-.09-4.14-.28-3.57-.49-6.58-1.42-9.21-2.86-.25-.14-.53-.42-.57-.71-.02-.19-.05-.37-.07-.56-.17-1.33-.34-2.7-.12-4.09,.31-1.92,1.27-3.07,2.95-3.5,1.88-.49,3.74-1.32,5.7-2.55,.07-.04,.14-.08,.24-.13,.04-.02,.09-.05,.15-.08l.28-.15,2.84,8.94c.03-.07,.05-.14,.08-.21,.05-.14,.1-.28,.15-.42,.19-.51,.38-1.04,.53-1.56,0,0,0-.01,0-.02-.03-.03-.05-.07-.06-.11l-1.46-3.77c-.06-.14-.04-.31,.05-.44,.09-.13,.23-.2,.39-.2h4.52c.16,0,.3,.08,.39,.2,.09,.13,.11,.29,.05,.44l-1.46,3.77s-.04,.09-.07,.13c.01,.05,.02,.09,.04,.14,.23,.6,.45,1.22,.66,1.82,.03,.07,.05,.15,.08,.22l2.83-8.89,.28,.14c.35,.18,.7,.37,1.04,.55,.79,.42,1.53,.81,2.3,1.16,.91,.41,1.82,.74,2.72,.98,1.71,.45,2.69,1.61,2.99,3.54h0c.22,1.38,.04,2.74-.13,4.06-.03,.2-.05,.39-.08,.59-.04,.33-.39,.6-.58,.7-2.61,1.43-5.61,2.36-9.16,2.85-1.38,.19-2.77,.28-4.16,.28Zm-5.11-14.14s-.05,.03-.07,.04c-2,1.26-3.91,2.11-5.85,2.61-1.48,.38-2.29,1.36-2.56,3.07-.21,1.31-.04,2.65,.12,3.94,.02,.19,.05,.37,.07,.56,0,.06,.14,.22,.29,.31,2.57,1.4,5.52,2.32,9.03,2.8,2.71,.37,5.45,.37,8.16,0,3.49-.48,6.43-1.39,8.98-2.79,.16-.09,.3-.24,.3-.3,.02-.2,.05-.39,.08-.59,.17-1.28,.34-2.6,.13-3.91h0c-.27-1.72-1.1-2.71-2.6-3.11-.93-.25-1.87-.59-2.8-1.01-.79-.36-1.54-.76-2.33-1.18-.25-.13-.5-.27-.75-.4l-3.11,9.79-.27-.74c-.12-.32-.23-.65-.34-.97-.21-.6-.42-1.21-.65-1.81-.06-.15-.09-.29-.1-.43v-.18s.14-.06,.14-.06l1.42-3.66h-4.34l1.42,3.66,.11,.07v.15c0,.1-.01,.19-.03,.27-.16,.54-.35,1.08-.54,1.6-.05,.14-.1,.28-.15,.42-.06,.18-.14,.35-.21,.51-.05,.13-.11,.26-.16,.39l-.27,.71-3.1-9.76Z"></path>   <path class="biz-svg-highlight-color" d="M16.09,16.2c-.81,0-1.63-.16-2.42-.48-2.36-.98-3.89-3.26-3.89-5.82,0-.62,.51-1.13,1.13-1.13s1.13,.51,1.13,1.13c0,1.64,.98,3.11,2.5,3.74,1.52,.63,3.25,.28,4.41-.88,1.16-1.16,1.51-2.89,.88-4.41-.63-1.52-2.1-2.5-3.74-2.5h-2.45l.66,.66c.44,.44,.44,1.16,0,1.6-.21,.21-.5,.33-.8,.33s-.59-.12-.8-.33l-2.59-2.59c-.21-.21-.33-.5-.33-.8s.12-.59,.33-.8l2.59-2.59c.21-.21,.5-.33,.8-.33s.59,.12,.8,.33c.21,.21,.33,.5,.33,.8s-.12,.59-.33,.8l-.66,.66h2.45c2.56,0,4.84,1.53,5.82,3.89,.98,2.36,.44,5.06-1.37,6.87-1.21,1.21-2.81,1.85-4.45,1.85Zm-5.18-6.9c-.33,0-.6,.27-.6,.6,0,2.34,1.4,4.44,3.56,5.33,2.16,.9,4.63,.41,6.29-1.25s2.15-4.13,1.25-6.29c-.9-2.16-2.99-3.56-5.33-3.56h-3.74l1.58-1.57c.23-.23,.23-.61,0-.85-.23-.23-.62-.23-.85,0l-2.59,2.59c-.11,.11-.18,.27-.18,.42s.06,.31,.18,.42l2.59,2.59c.23,.23,.62,.23,.85,0,.23-.23,.23-.61,0-.85l-1.58-1.57h3.74c1.86,0,3.52,1.11,4.23,2.83,.71,1.72,.32,3.68-.99,4.99-1.31,1.31-3.27,1.7-4.99,.99-1.72-.71-2.83-2.37-2.83-4.23,0-.33-.27-.6-.6-.6Z"></path> </svg></span>';
        }
        html += `<span class="appTitle">${result[i].AppTitle}</span></li>`;
      }
      html += "</ul></li>";
      $("#apps-list").html(html);
      $(".appsBind").on("click", function () {
        let width = "330px";
        if(window.innerWidth> 1024){
          $("#list-page").css("width", `calc(100% - ${width})`);     
        }
        if( $('.lft-nav-bar-2:visible').length !=0 ){
          $(".ctr-lst-pge").addClass("apps-loaded-tr");
        }else{
          $(".ctr-lst-pge").addClass("apps-loaded lft-nav-bar-Wrap")
        }
        let installedAppId = $(this).attr("data-myappid");
        const cookie = getCookie("_idty");
        if (cookie) {
          let serverUrl = _serverUrl();
          const {unibaseId, tenantId, userId} = JSON.parse(cookie);
          $("body").addClass("d-flex flex-row");
          $(".apps-loading").remove();
          $("#list-page").after(
            `<section id="" class="apps-loading"><iframe width="100%" style="height:inherit"  name="lstSrcFrame" id="lstSrcFrame" class="lstSrcFrame" src="${serverUrl}#/${unibaseId}/${tenantId}/${userId}/${installedAppId}/0/false/loadList"></iframe></section>`
          );
        }
      });
    }
  });
  $(".btn.dropdown-toggle.create").on("click", function () {
    let appName = [];
    getData("apis/v4/unibase/platform/apps/myapps").then(async function (res) {
      let response = await JSON.parse(res.result);
      jQuery.each(response, async function (index, item) {
        let installedAppId = Number(item.MyAppId);
        await getData(
          `apis/v4/unibase/platform/apps/listappconfigurations/installedappid/${installedAppId}`
        ).then(function (result) {
          if (
            result.result != null &&
            result.result != "" &&
            result.result != "[]"
          ) {
            let _data = JSON.parse(result.result);
            let data = _data.filter((x) => x.SettingUrlType == 1);
            if (data.length != 0) {
              appName.push({
                SettingUrlType: data[0].SettingUrlType,
                AppTitle: data[0].AppTitle,
                FormId: data[0].FormId,
                InstalledAppId: data[0].InstalledAppId,
                RoleSettingAppId: data[0].RoleSettingAppId,
                InstalledAppGuid: data[0].InstalledAppGuid,
                AppConfigurationId: data[0].AppConfigurationId,
                AppPermissionId: data[0].AppPermissionId,
                AppConfigType: data[0].AppConfigType,
              });
            }
          }
        });
        await appName.sort(function (a, b) {
            var a1 = a.AppTitle.toLowerCase().trim(), b1 = b.AppTitle.toLowerCase().trim();
            if (a1 == b1) return 0;
            return a1 > b1 ? 1 : -1;
        });
        await createLoad(appName);
      });
    });
  });
  $('[data-buttontype="Starred"]').on("click", function () {
    let count = 20;
    if (
      $('[data-buttontype="inbox"] .length').attr("data-taskscount") !=
      undefined
    ) {
      count = $('[data-buttontype="inbox"] .length').attr("data-taskscount");
    }
    loadData(
      `apis/v4/unibase/reminders/platform/getunreadreminders/ReminderType/1/PageSize/${count}`,
      false
    );
  });

  $('[data-buttontype="unstarred"]').on("click", function () {
    let count = 20;
    if (
      $('[data-buttontype="inbox"] .length').attr("data-notificount") !=
      undefined
    ) {
      count = $('[data-buttontype="inbox"] .length').attr("data-notificount");
    }
    loadData(
      `apis/v4/unibase/reminders/platform/getunreadreminders/ReminderType/6/PageSize/${count}`,
      false
    );
  });
  $('[data-buttontype="all"]').on("click", function () {
    loadData(
      "apis/v4/unibase/reminders/platform/getuserreminders/PageSize/0",
      false
    );
  });
  $('[data-buttontype="read"]').on("click", function () {
    $(".pdng.lst-Notifi").addClass("d-none");
    $(".pdng.lst-Notifi[data-isreaded='2']").removeClass("d-none");
  });
  $('[data-buttontype="unread"]').on("click", function () {
    $(".pdng.lst-Notifi").addClass("d-none");
    $(".pdng.lst-Notifi[data-isreaded='8']").removeClass("d-none");
  });
  $('[data-buttontype="sent"]').on("click", function () {
    loadData(
      "apis/v4/unibase/reminders/platform/getuserreminders/PageSize/0",
      true
    );
  });
  try {
    loadData(
      "apis/v4/unibase/reminders/platform/getuserreminders/PageSize/0",
      false
    );
  } catch (error) {
    console.log("LoadData Method is not loading, and getting error");
  }
}

export function stagesLoad() {
  $(".stgs-li").each(function () {
    let html = "";
    let InstalledAppId = $(this).attr("data-installedappid");
    getData(
      `apis/v4/unibase/platform/apps/getallchangestageroles/installedappid/${InstalledAppId}`
    ).then(function (stg_rslt) {
      let data = JSON.parse(stg_rslt.result);
      let _stage = data.filter(function (o) {
        return o.IsDefault == true;
      });
      html += `<button type="button" class="btn btn-sm btn-info dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false" data-isdefault="${_stage[0].IsDefault}" data-stageid="${_stage[0].StageId}" >
                ${_stage[0].StageName}
              </button>
              <ul class="dropdown-menu">`;
      for (var s = 0; s < data.length; s++) {
        let stage = data[s];
        if (!stage.IsDefault) {
          html += `<li><a class="dropdown-item" href="javascript:;" data-isdefault="${stage.IsDefault}" data-stageid="${stage.StageId}">${stage.StageName}</a></li>`;
        }
      }
      html += "</ul>";
      $(`.stgs-li[data-installedappid='${InstalledAppId}']`).html(html);
    });
  });
}
