import { defineStore } from "pinia";
import { useAuthStore } from "./authStore";
import permitApis from "~/apis/permitApi";
import authApi from "~/apis/authApi";
import { useStorage } from "@vueuse/core";

import type {
  JahatSection,
  Book,
  TempData,
  AuthorizedPages,
  Schemas,
  ActiveSchema,
  ForwardItem,
  Selectedlists,
  Permission,
  System,
  User,
  lastRecord,
  Pagination,
} from "~/types/commonTypes";

import type { researchTerms } from "~/types/researchTypes";
import type { ActiveEntityViewSchema, ActiveTab } from "~/types/entityType";
import type {
  Domain,
  helpActiveSchema,
  helpSchema,
  searchActiveTab,
  searchSchema,
  searchSynonymTitle,
} from "~/types/searchTypes";

export const useCommonStore = defineStore("commonStore", {
  persist: {
    storage: piniaPluginPersistedstate.localStorage(),
  },
  state: () => ({
    vuexEntity: undefined, //پیدا نکردم

    // admin
    helpSchema: undefined as helpSchema | undefined,
    helpActiveSchema: undefined as helpActiveSchema | undefined,
    // from search
    domainActive: undefined as Domain | undefined,

    diffType: undefined,

    activeTab: undefined as ActiveTab | undefined,
    activeEntityViewSchema: undefined as ActiveEntityViewSchema | undefined,

    researchTerms: undefined as researchTerms | undefined,

    count: 0 as number,
    name: "" as string,
    jahatSection: [] as JahatSection,
    tokenIsValid: false,
    pwaInstallPromptEvent: null,
    axiosBaseUrl: null,
    componentName: "",
    show_base_modal: false,
    book: {} as Book,
    tempData: {} as TempData,
    collapsed: +import.meta.env.VITE_BUILD_STATE as
      | number
      | boolean
      | undefined,
    show_form: false,
    is_edit_mode: false,
    refresh_form: false,
    user_permissions: [] as string[],
    authorized_pages: [] as AuthorizedPages,
    isDesktop: false,
    isMobile: false,
    userLastState: null,
    schemas: {} as Schemas,
    activeSchema: {} as ActiveSchema,
    selectedlists: {} as Selectedlists,

    userHistory: {},
    lastRecord: {} as lastRecord | undefined,

    lang: "fa" as string,
    fontData: undefined,
    pagination: {
      pages: 0,
      total: 0,
      page: 1,
      offset: 0,
      limit: 10,
    } as Pagination,
    systems: [] as System[],
    activeSystem: {} as System,
    appVersion: "" as string,
    isShowHilight: true as boolean,
    sidebarMenu: {},

    // search
    searchSynonymTitle: undefined as searchSynonymTitle | undefined,
    searchActiveTab: undefined as searchActiveTab | undefined,
    searchSchema: undefined as searchSchema | undefined,
  }),
  getters: {
    vuexEntityGetter(state) {
      return state.vuexEntity;
    },
    // admin
    helpSchemaGetter(state) {
      return state.helpSchema;
    },
    helpActiveSchemaGetter(state) {
      return state.helpActiveSchema;
    },
    // from search
    searchSynonymTitleGetter(state) {
      return state.searchSynonymTitle;
    },
    searchActiveTabGetter(state) {
      return state.searchActiveTab;
    },
    searchSchemaGetter(state) {
      return state.searchSchema;
    },
    domainActiveGetter(state) {
      return state.domainActive;
    },
    diffTypeGetter(diffType) {
      return diffType;
    },
    activeTabGetter(state) {
      return state.activeTab;
    },
    activeEntityViewSchemaGetter(state) {
      return state.activeEntityViewSchema;
    },
    researchTermsGetter(state) {
      return state.researchTerms;
    },
    doubleCount: (state) => state.count * 2,
    loginMicroServiceName: () => import.meta.env.VITE_AUTH,
    messageMircroServiceName: () => import.meta.env.VITE_MESSAGE,
    keyValueMircroServiceName: () => import.meta.env.VITE_KEY_VALUE,
    permitMircroServiceName: () => import.meta.env.VITE_PERMIT,
    repoMircroServiceName: () => import.meta.env.VITE_REPO,
    logMircroServiceName: () => import.meta.env.VITE_LOG,
    listMircroServiceName: () => import.meta.env.VITE_LIST,
    activeSchemaGetter: (state) => state.activeSchema,
    schemasGetter: (state) => state.schemas,
    organNameGetter: () => import.meta.env.VITE_BUILD_NAME,
    sectionsGetter: (state) => state.jahatSection,
    getTokenIsValid: (state) => state.tokenIsValid,
    getPwaInstallPromptEvent: (state) => state.pwaInstallPromptEvent,
    getUserLastState: (state) => state.userLastState,
    getAxiosBaseUrl: (state) => state.axiosBaseUrl,
    authorizedPagesGetter: (state) => state.authorized_pages,
    userPermisionGetter: (state) => state.user_permissions,
    getBook: (state) => state.book,
    getComponentName: (state) => state.componentName,
    getShowBaseModal: (state) => state.show_base_modal,
    isSidebarCollapsed: (state) => state.collapsed,
    getPanelStatus: (state) => state.show_form,
    getRefreshForm: (state) => state.refresh_form,
    isDesktopGetter: (state) => state.isDesktop,
    isMobileGetter: (state) => state.isMobile,
    selectedlistsGetter: (state) => state.selectedlists,
    sidebarMenuGetter: (state) => state.sidebarMenu,
    userHistoryGetter: (state) => state.userHistory,
    lastRecordGetter: (state) => state.lastRecord,
    appVersionGetter: (state) => state.appVersion,
    systemsGetter: (state) => state.systems,
    activeSystemGetter: (state) => state.activeSystem,
    langGetter: (state) => state.lang,
    fontDataGetter: (state) => state.fontData,
    paginationGetter: (state) => state.pagination,
    isShowHilightGetter: (state) => state.isShowHilight,
  },
  actions: {
    vuexEntitySetter(vuexEntity = undefined) {
      this.vuexEntity = vuexEntity;
    },
    // admin
    helpSchemaSetter(helpSchema = undefined) {
      this.helpSchema = helpSchema;
    },
    helpActiveSchemaSetter(helpActiveSchema = undefined) {
      this.helpActiveSchema = helpActiveSchema;
    },
    // from search
    searchSynonymTitleSetter(searchSynonymTitle = undefined) {
      this.searchSynonymTitle = searchSynonymTitle;
    },

    searchActiveTabSetter(searchActiveTab: searchActiveTab) {
      this.searchActiveTab = searchActiveTab;
    },
    searchSchemaSetter(searchSchema = undefined) {
      this.searchSchema = searchSchema;
    },

    domainActiveSetter(domain = undefined) {
      this.domainActive = domain;
    },
    diffTypeSetter(diffType) {
      this.diffType = diffType;
    },
    activeTabSetter(activeTab = undefined) {
      this.activeTab = activeTab;
    },
    activeEntityViewSchemaSetter(activeEntityViewSchema = undefined) {
      this.activeEntityViewSchema = activeEntityViewSchema;
    },
    researchTermsSetter(researchTerms = undefined) {
      this.researchTerms = researchTerms;
    },

    activeSchemaSetter(activeSchema: {}) {
      if (this.activeSchema) this.activeSchema = activeSchema;
    },
    schemasSetter(schemas: any[]) {
      this.schemas = schemas;
    },
    sidebarCollapsedSetter(isCollapsed: boolean) {
      this.collapsed = isCollapsed;
    },

    SET_SECTIONS(jahatSection: JahatSection) {
      this.jahatSection = jahatSection;
    },
    // SET_TOKEN_IS_VALID_EVENT(tokenIsValid: boolean) {
    //   this.tokenIsValid = tokenIsValid;
    // },
    SET_PWA_INSTALL_PROMPT_EVENT(event = null) {
      this.pwaInstallPromptEvent = event;
    },
    // SET_USER_LAST_STATE(userLastState: null) {
    //   this.userLastState = userLastState;
    // },
    SET_IS_DESKTOP(isDesktop: boolean) {
      this.isDesktop = isDesktop;
    },
    SET_IS_MOBILE(isMobile: boolean) {
      this.isMobile = isMobile;
    },
    TOGGLE_SIDEBAR_MENU() {
      this.collapsed = !this.collapsed;
    },
    BOOK_DATA(payload: Book) {
      this.book = payload;
    },
    COMPONENT_NAME(payload: string) {
      this.componentName = payload;
    },
    SHOW_BASE_MODAL(payload: boolean) {
      this.show_base_modal = payload;
    },
    REFRESH_FORM() {
      this.refresh_form = !this.refresh_form;
    },
    TOGGLE_PANEL(status: boolean) {
      this.show_form = status;
    },
    SELECTED_LISTS(selectedlists: Selectedlists) {
      this.selectedlists = selectedlists;
    },

    SET_AUTHORIZED_PAGES(pages: Permission[] = []) {
      const AuthorizedPages: Set<string> = new Set();

      if (pages && pages.length) {
        pages.forEach((item: Permission) =>
          AuthorizedPages.add(item.section_tag)
        );
      }
      // this.authorized_pages = AuthorizedPages as Set<string>;
      this.authorized_pages = Array.from(AuthorizedPages);
    },
    SET_USER_PERMISSIONS(permissions: Permission[] = []) {
      const permissionArray: string[] = [];
      if (permissions && permissions.length) {
        permissions.forEach((item: Permission) =>
          permissionArray.push(item.action_tag)
        );
      }
      this.user_permissions = permissionArray;
      // localStorage.setItem('user_permissions', JSON.stringify(permissionArray))
    },
    increment() {
      this.count++;
    },
    // easily reset state using `$reset`
    clearUser() {
      this.$reset();
    },

    async getState() {
      const settingsApi = (await import("~/apis/adminApi")).default;
      const url = settingsApi.user.get;

      try {
        const response = await useAPI(url, {
          baseURL: import.meta.env.VITE_REPO_BASE_URL,
        });
        this.userLastState = JSON.parse(response?._source?.user_last_state);
        return this.getUserLastState;
      } catch (error) {
        return error;
      }
      // const httpService = new HttpService(import.meta.env.VITE_REPO_BASE_URL);

      // const url = settingsApi.user.get;
      // return await httpService.getRequest(url).then((res: any) => {
      //   this.userLastState = JSON.parse(res?._source?.user_last_state);
      //   return this.getUserLastState;
      // });
      // const url = adminApi.admin.get.replace(
      //   "{{system}}/",
      //   "user_log/user_last_state"
      // );

      // return await httpService.getRequest(url).then((res) => {
      //   this.SET_USER_LAST_STATE", JSON.parse(res.hits.hits[0]._source.value));
      //   return getters.getUserLastState;
      // });
    },
    // async storeState(userLastState: any) {
    // const httpService = new HttpService(import.meta.env.VITE_REPO_BASE_URL);
    // const settingsApi = require("~/apis/settingsApi");

    // const payload = {
    //   user_id: getters.currentUser.user_id,
    //   username: getters.currentUser.username ?? null,
    //   project: "user_log",
    //   key_option: "user_last_state",
    //   value: JSON.stringify(userLastState),
    // };
    // return await httpService.postRequest(adminApi.admin.save, payload);
    // const payload = {
    //   user_last_state: userLastState,
    // };

    // const url = settingsApi.user.setKey_object.replace(
    //   "{{key}}",
    //   "user_last_state"
    // );
    // return await httpService.postRequest(url, payload);
    // },

    setBodyClass(customClass: string | null = null) {
      if (customClass) {
        document.querySelector("body")?.classList.add(customClass);
      } else {
        const activeSystem = this.activeSystemGetter;
        if (
          activeSystem &&
          activeSystem.link &&
          location.pathname.includes(activeSystem.link)
        ) {
          document
            .querySelector("body")
            ?.classList.add(`${activeSystem.link}-system`);
        } else {
          if (this.systemsGetter) {
            this.setNewSystem(this.systemsGetter);
          } else {
            this.getSystems().then((systems: any) => {
              this.setNewSystem(systems);
            });
          }
        }
      }
    },

    // setNewSystem<Type>(systems: Type): void {
    setNewSystem(systems: System[]) {
      const extractedSystemName = location.pathname
        .match(/\/(.*)\/{0,1}/)
        ?.pop()
        ?.split("/");

      let result: System | null = null;

      if (extractedSystemName && extractedSystemName.length > 0) {
        result = systems.find(
          (item) => item.link === extractedSystemName[0]
        ) as System;
      }

      if (result) {
        this.activeSystem = result;
        const bodyElement = document.querySelector("body");
        if (bodyElement) {
          bodyElement.classList.add(result.link + "-system");
        }
      }
    },
    async getSystems() {
      const apiName = import.meta.env.VITE_API_NAME;
      const baseUrl = import.meta.env.VITE_BASE_URL;

      return await $fetch(permitApis.projects.list, {
        baseURL: baseUrl + apiName + import.meta.env.VITE_PERMIT_BASE_URL,
        headers: {
          Authorization: useStorage("id_token", "").value,
        },
        method: "post",
      })
        .then((res: any) => {
          const systems = this.systemsGetter;
          if (!systems) {
            // this.systemsSetter = res.data.data;
            this.systems = res.data;
          }
          return res;
        })
        .catch((error) => {
          throw createError({
            ...error,
            statusMessage: `Could not fetch posts`,
          });
        });

      // const httpService = axios.create({
      //   baseURL: import.meta.env.VITE_PERMIT_BASE_URL,
      //   headers: {
      //     Authorization: getToken(),
      //   },
      // });

      // return new Promise((resolve, reject) => {

      //   httpService
      //     .post(permitApis.projects.list)
      //     .then((res: resModelOne) => {
      //       const systems = this.systemsGetter;
      //       if (!systems) {
      //         // this.systemsSetter = res.data.data;
      //         this.systems = res.data;
      //       }
      //       // resolve(res.data.data);
      //       resolve(res.data);
      //     })
      //     .catch((err: any) => {
      //       reject(err);
      //     });
      // });
    },
    async getUserPermissions(projectId = undefined) {
      const authStore = useAuthStore();

      const data = {
        project_id: projectId ?? this.activeSystem.id,
        user_id: authStore.currentUser.user_id,
      };

      try {
        const res = await useAPI(permitApis.permissions.listUserPermission, {
          baseURL: import.meta.env.VITE_AUTH_BASE_URL,
          method: "POST",
          body: formDataParamMaker(data),
          // headers: {
          //   'Content-Type': 'application/x-www-form-urlencoded',
          // },
        });

        this.SET_USER_PERMISSIONS(res.data);
        this.SET_AUTHORIZED_PAGES(res.data);

        return res.data;
      } catch (error) {
        return error;
      }

      // const httpService = new HttpService(import.meta.env.VITE_PERMIT_BASE_URL);
      // return new Promise((resolve, reject) => {
      //   httpService
      //     .formDataRequest(permitApis.permissions.listUserPermission, data)
      //     .then((res) => {
      //       this.SET_USER_PERMISSIONS = res.data;
      //       this.SET_AUTHORIZED_PAGES = res.data;
      //       resolve(res.data);
      //     })
      //     .catch(({ response }) => {
      //       reject(response);
      //     });
      // });
    },

    async checkPermissions(permission = null) {
      const authStore = useAuthStore();

      return new Promise((resolve, reject) => {
        // اگر قبلا لیست دسترسی ها دریافت شده بود.
        if (this.userPermisionGetter && this.userPermisionGetter.length) {
          if (
            authStore.currentUser.user_level > 1 ||
            this.userPermisionGetter.includes(permission)
          ) {
            resolve(null);
          } else {
            reject();
          }
        } else {
          this.getUserPermissions().then((res) => {
            if (
              authStore.currentUser.user_level > 1 ||
              this.userPermisionGetter.includes(permission)
            ) {
              resolve(null);
            } else {
              // mySwalToast({
              //   title: "خطا",
              //   html: "عدم دسترسی",
              //   icon: "error",
              // });
              reject();
            }
          });
        }
      });
    },

    checkPagePermissions(pageUrl = null) {
      return new Promise((resolve, reject) => {
        // اگر قبلا لیست دسترسی صفحات دریافت شده بود.
        if (this.authorizedPagesGetter && this.authorizedPagesGetter.size > 0) {
          if (
            pageUrl == "" ||
            pageUrl == "view" ||
            this.authorizedPagesGetter.has(pageUrl)
          )
            resolve(null);
          else reject();
        } else {
          this.getUserPermissionTags().then(() => {
            if (
              pageUrl == "" ||
              pageUrl == "view" ||
              this.authorizedPagesGetter?.has(pageUrl)
            )
              resolve(null);
            else reject();
          });
        }
      });
    },
    async getUserPermissionTags() {
      try {
        const res = await useAPI(permitApis.permissions.userPermissionTags, {
          baseURL: import.meta.env.VITE_PERMIT_BASE_URL,
          method: "POST",
          body: {},
        });

        this.SET_USER_PERMISSIONS(res.data);
        this.SET_AUTHORIZED_PAGES(res.data);

        return res.data;
      } catch (error) {
        return error;
      }

      // const httpService = new HttpService(import.meta.env.VITE_PERMIT_BASE_URL);

      // return new Promise((resolve, reject) => {
      //   httpService
      //     .formDataRequest(permitApis.permissions.userPermissionTags, {})
      //     .then((res) => {
      //       this.SET_USER_PERMISSIONS = res.data;
      //       this.SET_AUTHORIZED_PAGES = res.data;
      //       resolve(res.data);
      //     })
      //     .catch(({ response }) => {
      //       reject(response);
      //     });
      // });
    },
    async checkTokenIsValid() {
      const authStore = useAuthStore();

      try {
        const res = await useAPI(authApi.validateUser, {
          baseURL: import.meta.env.VITE_AUTH_BASE_URL,
        });

        this.tokenIsValid = true;
        let userData = {
          ["user_data"]: res.data?.data,
        } as User;

        if (
          userData.user_data?.user_id == 3 ||
          userData.user_data?.username == "Guest"
        ) {
          authStore.setGuest(userData);
        }
        return res;
      } catch (error) {
        return error;
      }

      //   const httpService = new HttpService(import.meta.env.VITE_AUTH_BASE_URL);
      //   return new Promise((resolve, reject) => {
      //     httpService
      //       .getRequest(authApi.validateUser)
      //       .then((res) => {
      //         // this.SET_TOKEN_IS_VALID_EVENT = true;
      //         this.tokenIsValid = true;

      //         // if(typeof res.data == "boolean")
      //         // this.SET_TOKEN_IS_VALID_EVENT', res.data)
      //         // else{
      //         // this.SET_TOKEN_IS_VALID_EVENT', true)
      //         // }

      //         let userData = {
      //           ["user_data"]: res.data?.data,
      //         } as User;

      //         if (
      //           userData.user_data?.user_id == 3 ||
      //           userData.user_data?.username == "Guest"
      //         ) {
      //           authStore.setGuest(userData);
      //         }
      //         resolve(null);
      //       })
      //       .catch(({ response }) => {
      //         reject(response);
      //       });
      //   });
    },
    sidebarMenuSetter(sidebarMenu: {}) {
      this.sidebarMenu = sidebarMenu;
    },
    lastRecordSetter(lastRecord: lastRecord) {
      this.lastRecord = lastRecord;
    },

    appVersionSetter(appVersion = "") {
      this.appVersion = appVersion;
    },
    systemsSetter(systems: System[]) {
      this.systems = systems;
    },
    activeSystemSetter(activeSystem: System) {
      this.activeSystem = activeSystem;
    },
    langSetter(lang = "fa") {
      this.lang = lang;
    },
    fontDataSetter(fontData = undefined) {
      this.fontData = fontData;
    },
    paginationSetter(pagination: Pagination) {
      this.pagination = pagination;
    },
    isShowHilightSetter(isShowHilight = true) {
      this.isShowHilight = isShowHilight;
    },
  },
});
