// // import Vue from "vue";
import { convertEnToPe } from "~/manuals/persianNumber";
// import { mapState } from "pinia";
// import Cookies from "js-cookie";
import { useCommonStore } from "~/stores/commonStore";
import { useAuthStore } from "~/stores/authStore";
// // ...mapState("common", ["activeSystemGetter"]),

export const appDescription = () => {
  return import.meta.env.VITVITE_DESCRIPTION_BUILD_NAME ?? "monir";
};
export const buildName = () => {
  return import.meta.env.VITE_BUILD_NAME ?? "monir";
};
export const logoPhoto = () => {
  if (buildName() == "majles")
    return import("assets/majles/img/logo_200x200_green.png");
  return import("assets/common/img/logo/logo.png");
};
export const appLongTitle = () => {
  return import.meta.env.VITE_TITLE ?? "زیست بوم تحریر";
};
export const appShortTitle = () => {
  return import.meta.env.VITE_SHORT_TITLE ?? "زیست بوم تحریر";
};
export const buildState = () => {
  return import.meta.env.VITE_BUILD_STATE ?? 0;
};
export const isMajlesBuild = () => {
  return buildName() == "majles" && buildState() == 1;
};
export const isAdmin = () => {
  const authStore = useAuthStore();
  return authStore.currentUser?.user_level > 1;
};
export const AddButtonText = () => {
  return import.meta.env.VITE_NEW_TEXT;
};
export const EditButtonText = () => {
  return import.meta.env.VITE_EDIT_TEXT;
};
// export const pageFormTitle = () => {
//   return this.$route.meta.pageFormTitle;
// };
// export const pageName = () => {
//   return this.$route.meta.breadcrumb;
// };

// export const getHtmlTooltip = (section, key, id) => {
//   let res = {};
//   let link = "";
//   if (id) link = location.origin + "/" + key + "/" + id;
//   if (section == "search") {
//     if (key == "search_type") {
//       res = {
//         html:
//           "<p>" +
//           "برای یافتن بهترین پاسخ، روش جستجو را تعیین می‌کند" +
//           "</p>" +
//           '<a href="' +
//           link +
//           '"> بیشتر ... </a>',
//       };
//     }
//   }
//   if (section == "entity") {
//   }

//   return res;
// };
export const tahrirUrl = () => {
  return import.meta.env.VITE_TAHRIR_BASE_URL + "/";
};
export const messageUrl = () => {
  return import.meta.env.VITE_MESSAGE + "/";
};
export const loginUrl = () => {
  return import.meta.env.VITE_AUTH + "/";
};
export const keyValueUrl = () => {
  return import.meta.env.VITE_KEY_VALUE + "/";
};
export const permitUrl = () => {
  return import.meta.env.VITE_PERMIT + "/";
};
export const repoUrl = () => {
  return import.meta.env.VITE_REPO + "/";
};
export const listUrl = () => {
  return import.meta.env.VITE_LIST + "/";
};
export const taskUrl = () => {
  return import.meta.env.VITE_TASK + "/";
};
export const logUrl = () => {
  return import.meta.env.VITE_LOG + "/";
};
export const fileUrl = () => {
  return import.meta.env.VITE_FILE + "/";
};
export const baseUrl = () => {
  return import.meta.env.BASE_URL;
};

// // ...mapActions(["SET_PWA_ISTALL_PROMPT_EVENT"]),
export const setDocumentTitle = (data, key1 = "title") => {
  let title = "";

  if (data) {
    let dataWithSource = data;

    if ("_source" in data) {
      dataWithSource = { ...dataWithSource, ...dataWithSource._source };
    }

    title = appShortTitle();
    if (key1 in dataWithSource) title = dataWithSource[key1];
    // else if (key2 in dataWithSource) title = dataWithSource[key2];
    // else title = dataWithSource[key3];

    // this.$nextTick(() => {
    document.title = title; //appShortTitle() + "-" +
    // });
  } else document.title = appShortTitle();
};
// export const canUpdateInShowPage = (elemnt_key = undefined) => {
//   const authStore = useAuthStore();
//   const CommonStore = useCommonStore();

//   if (authStore.currentUser.user_level > 1) return true;

//   if (elemnt_key) {
//     // کلید واحد کامل با توجه به صفحه
//     const res = CommonStore.userPermisionGetter?.includes(elemnt_key + "_update");
//     return res;
//   }

//   const routeName = this.$route.name;
//   const routekey = this.$route.params.key;

//   if (routeName == "answersShow") {
//     const res = CommonStore.userPermisionGetter?.includes(
//       "answers-properties_update"
//     );
//     return res;
//   }
//   if (routeName == "issuesShow") {
//     const res = CommonStore.userPermisionGetter?.includes(
//       "issues-properties_update"
//     );
//     return res;
//   }
//   if (routeName == "critionsShow") {
//     const res = CommonStore.userPermisionGetter?.includes(
//       "critions-properties_update"
//     );
//     return res;
//   }

//   if (routekey == "mqsection" || routekey == "qsection") {
//     const res = CommonStore.userPermisionGetter?.includes(routekey + "_update");
//     return res;
//   } else {
//     return CommonStore.userPermisionGetter?.includes(routeName + "_update");
//   }
// };
export const copyToClipboard = async (
  id = undefined,
  domainUrl = undefined
) => {
  try {
    const _id = id ? "/" + id : "";
    let url = location.href;
    if (domainUrl) {
      url = location.origin + domainUrl;
    }
    await navigator.clipboard.writeText(url + _id);

    mySwalToast({
      html: "نشانی پیوند کپی شد.",
    });
  } catch (err) {
    console.log(err.message);
    mySwalToast({
      html: "خطایی رخ داد.لطفا دوباره امتحان کنید.",
    });
  }
};
export const copyTextToClipboard = async (text) => {
  try {
    await navigator.clipboard.writeText(text);

    mySwalToast({
      html: "متن کپی شد.",
    });
  } catch (err) {
    console.log(err.message);
    mySwalToast({
      html: "خطایی رخ داد.لطفا دوباره امتحان کنید.",
    });
  }
};

// // for firefox browser that does nt support pwa installation.
export const alertPwaNotSupported = () => {
  if (isMajlesBuild()) return;

  const vm = this;

  mySwalConfirm({
    title: "توجه!",
    html: `مرورگر شما امکان نصب سامانه در صفحه گوشی یا رایانه شما را نمی دهد.
      درصورت تمایل به نصب سامانه،
       از مرورگر گوگل کروم
       <img src="${require("assets/common/img/chrome.svg")}" width="20" height="20" alt="Google Chrome">
         یا مایکروسافت اج
         <img src="${require("assets/common/img/edge.svg")}" width="20" height="20" alt="Microsoft Edge">
          استفاده نمایید.
      `,
    showCancelButton: true,
    confirmButtonText: "باشه",
    cancelButtonText: "فعلا نمی خوام",
  });
  // .then((result) => {
  //   if (result.isConfirmed) {
  //     vm.dismissPwaInstallationBox(365);
  //   }
  // });
};
export const identifyBrowser = () => {
  var ua = navigator.userAgent;
  var tem;
  var M =
    ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) ||
    [];
  if (/trident/i.test(M[1])) {
    tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
    return "IE " + (tem[1] || "");
  }
  if (M[1] === "Chrome") {
    tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
    if (tem != null) return tem.slice(1).join(" ").replace("OPR", "Opera");
  }
  M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, "-?"];
  if ((tem = ua.match(/version\/(\d+)/i)) != null) M.splice(1, 1, tem[1]);
  return M.join(" ");
};
export const dismissPwaInstallationBox = async (time) => {
  const CommonStore = useCommonStore();
  // Cookies.set("add-to-home-screen", null, { expires: +time });
  CommonStore.SET_PWA_INSTALL_PROMPT_EVENT(null);
};
export const installPwa = async () => {
  const vm = this;
  const CommonStore = useCommonStore();

  CommonStore.getPwaInstallPromptEvent.prompt(); // Wait for the user to respond to the prompt
  CommonStore.getPwaInstallPromptEvent.userChoice.then((choice) => {
    if (choice.outcome === "accepted") {
      console.log("User accepted");
    } else {
      console.log("User dismissed");
    }
  });
};
export const userFullname = (user) => {
  if (user?.first_name || user?.last_name)
    return user?.first_name + " " + user?.last_name;
  else return user?.username;
};
export const userAvatar = (user = undefined) => {
  if (user) {
    try {
      if (user?.avatar && user?.avatar?.length) {
        return (
          import.meta.env.VITE_BASE_URL +
          import.meta.env.VITE_API_NAME +
          fileUrl() +
          user.avatar
        );
      } else {
        let initials = "";
        if (user.first_name) initials += user?.first_name.charAt(0);
        if (user.last_name) initials += user?.last_name.charAt(0);

        if (initials == "")
          initials = user?.username?.charAt(0) + user?.username?.charAt(1);

        return generateAvatarFromChars(initials);
      }
    } catch (err) {
      return import("~/assets/common/img/user.svg");
    }
  }
  return import("~/assets/common/img/user.svg");
};
export const generateAvatarFromChars = (
  text,
  foregroundColor = "white",
  backgroundColor = "#00b6e3"
) => {
  const canvas = document.createElement("canvas");
  const context = canvas.getContext("2d");

  canvas.width = 100;
  canvas.height = 100;

  // Draw background
  context.fillStyle = backgroundColor;
  context.fillRect(0, 0, canvas.width, canvas.height);

  // Draw text
  context.font = "normal 2.5rem sahel-bold";
  context.fillStyle = foregroundColor;
  context.textAlign = "center";
  context.textBaseline = "middle";
  context.direction = "rtl";
  context.fillText(text.trim(), canvas.width / 2, canvas.height / 2);

  return canvas.toDataURL("image/png");
};
export const logout = (route = undefined) => {
  const authStore = useAuthStore();
  // const route = useRoute();
  const router = useRouter();
  authStore.logout();

  if (route) {
    router.push({
      name: "login",
      params: route.params,
      query: {
        redirectBack: true,
        path: route.fullPath,
      },
    });
  } else {
    router.push({
      name: "login",
    });
  }
};
export const redirectToRouteName = (routeName = "dashboard") => {
  const router = useRouter();
  router.push({ name: routeName }).then(() => {
    // if (routeName === 'dashboard')
    //   clearBodyClass();
  });
};
export const getGroupAvatar = (user = undefined) => {
  try {
    if (user) {
      if (isValidHttpUrl(user.avatar)) return user.avatar;
      else {
        if ("title" in user) {
          const nameArray = user.title?.split(" ");
          if (nameArray?.length > 1) {
            const initials = nameArray[0].charAt(0) + nameArray[1].charAt(0);
            return generateAvatarFromChars(initials);
          } else {
            const initials = nameArray[0].charAt(0);
            return generateAvatarFromChars(initials);
          }
        }
      }
    }
  } catch (err) {
    return import("~/assets/common/img/default.svg").default;
  }
};
export const convertUnixToPersianDateTime = (created_at) => {
  if (created_at) {
    const currentDate = new Date();
    const currentYear = currentDate.getFullYear();
    const currentMonth = currentDate.getMonth();
    const currentDay = currentDate.getDate();
    const currentHours = currentDate.getHours();
    const currentMinutes = currentDate.getMinutes();
    const currentSeconds = currentDate.getSeconds();

    const updatedAtDate = new Date(created_at * 1000);
    const updatedAtYear = updatedAtDate.getFullYear();
    const updatedAtMonth = updatedAtDate.getMonth();
    const updatedAtDay = updatedAtDate.getDate();
    const updatedAtHours = updatedAtDate.getHours();
    const updatedAtMinutes = updatedAtDate.getMinutes();
    const updatedAtSeconds = updatedAtDate.getSeconds();

    let yr =
      updatedAtYear - currentYear !== 0
        ? Math.abs(updatedAtYear - currentYear)
        : 0;
    if (yr) return convertEnToPe(yr) + " سال پیش";

    let mon =
      updatedAtMonth - currentMonth !== 0
        ? Math.abs(updatedAtMonth - currentMonth)
        : 0;

    if (mon) return convertEnToPe(mon) + " ماه پیش";

    let dy =
      updatedAtDay - currentDay !== 0 ? Math.abs(updatedAtDay - currentDay) : 0;
    if (dy) {
      if (dy % 7 === 0) return convertEnToPe(dy) + " هفته پیش";
      else return convertEnToPe(dy) + " روز پیش";
    }

    let sec =
      updatedAtSeconds - currentSeconds !== 0
        ? Math.abs(updatedAtSeconds - currentSeconds)
        : 0;
    let _seconds = "";
    if (sec) _seconds = " چند لحظه پیش";

    let min =
      updatedAtMinutes - currentMinutes !== 0
        ? Math.abs(updatedAtMinutes - currentMinutes)
        : 0;
    let _minutes = "";
    if (min) _minutes = convertEnToPe(min) + " دقیقه پیش";

    let hr =
      updatedAtHours - currentHours !== 0
        ? Math.abs(updatedAtHours - currentHours)
        : 0;
    if (hr) {
      // if (min) {
      //   return convertEnToPe(hr) + " ساعت و " + _minutes
      // };
      return convertEnToPe(hr) + " ساعت پیش ";
    }
    if (!min && sec) return _seconds;

    return _minutes;
  } else {
    return "تاریخ نامعتبر";
  }
};

// export const deletePaper = (url, { isowner, title, guid }) => {
//   let html = `
//         <div class="custom-sw-content">
//       <div class="custom-sw-header-container">
//         <div class="icon">
//           <i class="tavasi tavasi-Component-360--58"><span class="path1"></span><span class="path2"></span></i>
//         </div>
//         <p class="custom-content-title">${title}</p>
//       </div>

//       <span class="text__gray text__small">سند <strong>اشتراکی</strong> شما حذف و در بخش بازیافت به مدت ۶۰ روز بایگانی می‌شود. بعد ازاین مدت خود به خود حذف می‌شود و بازگرداندن آن غیر ممکن است</span>
//     </div>
// `;

//   if (isowner === 1) {
//     html = `
//         <div class="custom-sw-content">
//       <div class="custom-sw-header-container">
//         <div class="icon">
//           <i class="tavasi tavasi-Component-360--58"><span class="path1"></span><span class="path2"></span></i>
//         </div>
//         <p class="custom-content-title">${title}</p>
//       </div>

//       <span class="text__gray text__small">سند شما حذف و در بخش بازیافت به مدت ۶۰ روز بایگانی می‌شود. بعد ازاین مدت خود به خود حذف می‌شود و بازگرداندن آن غیر ممکن است</span>
//     </div>
// `;
//   }

//   return new Promise((resolve, reject) => {
//     this.mySwalConfirm({
//       title: "از حذف این پرونده مطمئن هستید؟",
//       html,
//     }).then((result) => {
//       if (result.isConfirmed) {
//         ApiService.formData(url, { guid })
//           .then((response) => {
//             resolve(response);
//           })
//           .catch((err) => {
//             //todo: define what operation should to be done on error(401,403,500)
//             reject(err);
//           });
//       }
//     });
//   });
// };

// export const myEncodeQuery = (text) => {
//   // console.log(text);

//   if (!text || text == "") return "";
//   //text = JSON.stringify(text);
//   let ch1 = encodeURIComponent("#");
//   let ch3 = encodeURIComponent("\\");
//   let ch4 = encodeURIComponent("&");
//   text = text.replaceAll("#", ch1);
//   text = text.replaceAll("&", ch4);
//   text = text.replaceAll("/", "\\");
//   text = text.replaceAll("\\", ch3);
//   // text = text.replaceAll(".", '%2E');
//   return text;
// };
export const myEncodeQuery = (text) => {
  //text = JSON.stringify(text);
  if (!text || text == "") return "";

  let ch1 = encodeURIComponent("#");
  let ch3 = encodeURIComponent("\\");
  let ch4 = encodeURIComponent("&");

  text = text.replaceAll(ch1, "#");
  text = text.replaceAll(ch4, "&");
  text = text.replaceAll(ch3, "\\");
  return text;
};

// // Vue.mixin(globalMixin);

export const formDataParamMaker = (data) => {
  const formData = new FormData();

  for (const [key, value] of Object.entries(data)) {
    if (
      key != null &&
      key != undefined &&
      value !== undefined &&
      value !== null
    )
      formData.append(key, value);
  }
  return formData;
};