import { defineStore } from 'pinia'
import type {
  ICfgServer, IProvince,
  IColGridTable,
  IConfig,
  IDataToSet,
  IGlobalState,
  IListRoutes, IMyElem,
  IMyPage, IParamsPickup,
  IParamsQuery,
  ISettings,
  IStatusSkill,
  StateConnection,
  ISchedaSingola,
  IOptQueryGM,
  IOptCatalogo,
  IProduct,
  IProductInfo,
  IVariazione,
  IDestNewsletter
} from '@model';
import {
  ICity, IMySkill,
  ISites,
  IMyScheda
} from '@model'
import { static_data } from '@src/db/static_data'
import * as Types from '@src/store/Api/ApiTypes'
import { useUserStore } from '@store/UserStore'
import { serv_constants } from '@store/Modules/serv_constants'
import * as ApiTables from '@src/store/Modules/ApiTables'
import type { Router } from 'vue-router';
import { useRouter } from 'vue-router'
import { cfgrouter } from '@src/router/route-config'
import { Api } from '@api'
import { toolsext } from '@store/Modules/toolsext'
import { costanti } from '@costanti'
import { fieldsTable } from '@store/Modules/fieldsTable'
import { tools } from '@tools'
import { shared_consts } from '@src/common/shared_vuejs'
import globalroutines from '../globalroutines/index'
import { useCalendarStore } from '@store/CalendarStore'
import urlBase64ToUint8Array from '@src/js/utility'
import translate from '@src/globalroutines/util'
import { useTodoStore } from '@store/Todos'
import { useMessageStore } from './MessageStore'
import { useNotifStore } from '@store/NotifStore'
import { useCircuitStore } from '@store/CircuitStore'
import { routesAdmin } from '@src/router/routesAdmin'
import { routesECommerce } from '@src/router/routesECommerce'
import { routesAI } from '@src/router/routesAI'
import LandingFooter from '@src/components/LandingFooter/LandingFooter'
import { useProducts } from '@store/Products'
import { useCatalogStore } from './CatalogStore'

const stateConnDefault = 'online'


async function getConfig(id: any) {
  return globalroutines('read', 'config', null, id)
}


export const useGlobalStore = defineStore('GlobalStore', {
  state: (): IGlobalState => ({
    finishLoading: false,
    conta: 0,
    wasAlreadySubscribed: false,
    wasAlreadySubOnDb: false,
    isLoginPage: false,
    layoutNeeded: true,
    mobileMode: false,
    menuCollapse: true,
    leftDrawerOpen: false,
    rightDrawerOpen: false,
    rightNotifOpen: false,
    rightCoinsOpen: false,
    rightCartOpen: false,
    stateConnection: stateConnDefault,
    serverError: false,
    serverMsgError: {},
    networkDataReceived: false,
    clickcmd: '',
    cfgServer: [],
    testp1: { contatore: 0, mioarray: [] },
    category: 'personal',
    posts: [],
    menulinks: {},
    listatodo: [
      { nametranslate: 'personal', description: 'personal' },
      { nametranslate: 'work', description: 'work' },
      { nametranslate: 'shopping', description: 'shopping' },
    ],
    connData: {
      uploading_server: 0,
      uploading_indexeddb: 0,
      downloading_server: 0,
      downloading_indexeddb: 0,
    },
    arrConfig: [],
    lastaction: {
      table: '',
      type: 0,
      _id: 0,
    },
    serv_settings: [],
    templemail: [],
    opzemail: [],
    settings: [],
    disciplines: [],
    paymenttypes: [],
    autoplaydisc: 8000,
    newstosent: [],
    gallery: [],
    mailinglist: [],
    mypage: [],
    myelems: [],
    myschedas: [],
    calzoom: [],
    producers: [],
    groups: [],
    resps: [],
    workers: [],
    storehouses: [],
    scontisticas: [],
    providers: [],
    catprods: [],
    subcatprods: [],
    gasordines: [],
    departments: [],
    categories: [],
    sharewithus: [],
    TIMER: null,
    TIMEOUT: null,
    CUT: null,
    TIMER_STATE: 0,
    URL_RITORNA: '',
    URL_RESTORE: '',
    levels: [],
    adtypes: [],
    adtypegoods: [],
    skills: [],
    goods: [],
    // subSkills: [],
    statusSkills: [],
    sectors: [],
    sectorgoods: [],
    catgrps: [],
    catAI: [],
    queryAIList: [],
    site: {
      confsite: {
        options: 0
      },
      confpages: {
        font: '',
        col_toolbar: '',
        col_bgfooter: '',
        show_darkopt: true,
        showProfile: false,
        showUserMenu: true,
        showiscrittiMenu: false,
        showRegButton: false,
        enableReg: false,
        showNL: false,
        sendNewsletter: false,
        showMsgs: false,
        showNotif: false,
        showCoins: false,
        showRIS: false,
        showMenuCoins: false,
        showNameSurname: false,
        showCompetenze: false,
        showConnected: false,
        bookingEvents: false,
        enableEcommerce: false,
        enableAI: false,
        enableGroups: false,
        enableCircuits: false,
        enableProj: false,
        enableTodos: false,
        enableRegByBot: false,
        enableRegMultiChoice: false,
        enableTokenExpired: false,
        enabledRegNeedTelegram: false,
        enableGoods: false,
        enableServices: false,
        enableActivities: false,
        enableHosps: false,
        enableEvents: false,
        enableDebugOn: false,
        showButtHome: false,
        showViewGroups: false,
        showViewEventi: false,
        showViewCircuits: false,
        showViewUsers: false,
        showViewBooking: false,
        showViewProfile: false,
        showViewCart: false,
        showViewOrders: false,
        enablePwa: false,
        lang: costanti.Lang.IT,
        videoPromo: '',
        PDFPromo: '',
      },
    },
    provinces: [],
    mygroups: [],
    selElem: {},
    editOn: false,
    myselector: { data: {}, table: '' },
    addNewRecord: '',
    isAppRunning: false,
    deferredPrompt: null,
    homescreen: '',
  }),

  getters: {

    sovrascriviSchedaFromTemplate: (state: IGlobalState) => (idTemplate: string, origScheda: ISchedaSingola, optcatalogo: IOptCatalogo) => {

      const arrschede: ISchedaSingola[] = state.myschedas
      const myfindscheda = arrschede.find((recscheda: ISchedaSingola) => recscheda.scheda?._id === idTemplate)

      const linkIdTemplate = origScheda.scheda?.linkIdTemplate
      const precname = origScheda.scheda?.name

      if (myfindscheda) {
        const myschedatocopy = tools.jsonCopy(myfindscheda)

        if (myschedatocopy) {
          myschedatocopy.scheda._id = origScheda.scheda?._id
          myschedatocopy.scheda.isTemplate = false
          myschedatocopy.scheda.name = precname
          myschedatocopy.scheda.linkIdTemplate = linkIdTemplate

          return myschedatocopy.scheda
        }
      }

      return null
    },

    // conta: (state: IGlobalState) => { state.conta },
    // listatodo: (state: IGlobalState) => { state.listatodo },
    // category: (state: IGlobalState) => { state.category },

    testpao1_getter_contatore: (state: IGlobalState) => (param1: number) => state.testp1.contatore + 100 + param1,
    testpao1_getter_array: (state: IGlobalState) => (param1: number) => state.testp1.mioarray.filter((item) => item).map((item) => item.valore),


    getConfigbyId: (state: IGlobalState) => (id: string) => state.arrConfig.find((item) => item._id === id),
    getConfigStringbyId: (state: IGlobalState) => (params: any) => {
      const config = state.arrConfig.find((item) => item._id === params.id)
      if (config) {
        return config.value
      } else {
        return params.default
      }
    },

    getColByStatusSkills: (state: IGlobalState) => (id: number) => {
      const ctrec = state.statusSkills.find((mystatus: IStatusSkill) => mystatus._id === id)
      return (ctrec && ctrec.color) ? ctrec.color : 'green'

    },

    getStatusSkillById: (state: IGlobalState) => (id: number) => {
      const ctrec = state.statusSkills.find((mystatus: IStatusSkill) => mystatus._id === id)
      return (ctrec) ? ctrec.descr : ''

    },

    getStatusSkillIconById: (state: IGlobalState) => (id: number) => {
      const ctrec = state.statusSkills.find((mystatus: IStatusSkill) => mystatus._id === id)
      return (ctrec) ? ctrec.icon : ''

    },

    isNewVersionAvailable: (state: IGlobalState) => {
      // console.log('cfgServer', cfgServer)
      const serversrec = state.cfgServer.find((x) => (x.chiave === toolsext.SERVKEY_VERS) && (x.idapp === tools.getEnv('VITE_APP_ID')))
      // console.log('Record ', serversrec)
      if (serversrec) {
        console.log('Vers Server ', serversrec.valore, 'Vers locale:', import.meta.env.VITE_APP_VERSION)
        return serversrec.valore !== import.meta.env.VITE_APP_VERSION
      }
      return false
    },

    getSchedeOpt: (state: IGlobalState) => (tag?: string) => {
      const Products = useProducts()

      return Products.getSchedeOpt(state.myschedas, tag)
    },

    getLinkIdTemplateByName: (state: IGlobalState) => (name: string) => {

      try {
        const myrecscheda = state.myschedas.find((recscheda: ISchedaSingola) => recscheda.scheda.name === name)

        return myrecscheda.scheda._id
      } catch (error) {
        return ''
      }

    },

    isMyLang: (state: IGlobalState) => (rec: any) => {
      if (!rec.lang) return true

      return (rec.lang === toolsext.getLocale(false) || toolsext.getLocale() === '')
    },

    getPage: (state: IGlobalState) => (path: string): IMyPage | undefined => state.mypage.find((page) => (`/${page.path}`) === path),
    getPageById: (state: IGlobalState) => (idpage: string): IMyPage | undefined => {
      const mypage = state.mypage.find((page) => (`${page._id}`) === idpage)
      return mypage
    },
    getPathByIdPage: (state: IGlobalState) => (idpage: string): string => {
      const mypage = state.mypage.find((page) => (`${page._id}`) === idpage)
      if (mypage) {
        return mypage.path!
      }
      return ''
    },

    getMyElemsByIdPage: (state: IGlobalState) => (idPage?: string): IMyElem[] | [] => {
      return state.myelems.filter((page: IMyElem) => (page._id === idPage)).sort((a: any, b: any) => a.order - b.order)
    },

    getMySchede: (state: IGlobalState) => (): ISchedaSingola[] | [] => {
      return state.myschedas
    },

    getMyElemPrecThisElemId: (state: IGlobalState) => (idPage: string, idelem: string): IMyElem => {
      // Ottieni tutti gli myelem con lo stesso path e ordinali per order
      const sortedElems = state.myelems
        .filter((elem: IMyElem) => elem.idPage === idPage)
        .sort((a: any, b: any) => a.order - b.order);

      // Trova l'indice dell'elemento con _id = idelem
      const index = sortedElems.findIndex((elem: IMyElem) => elem._id === idelem);

      // ritorna l'elemento precedente
      if (index > 0) {
        return sortedElems[index - 1];
      } else {
        return sortedElems[0];
      }
    },

    getMyElemNextThisElemId: (state: IGlobalState) => (idPage: string, idelem: string): IMyElem => {
      // Ottieni tutti gli myelem con lo stesso idpage e ordinali per order
      const sortedElems = state.myelems
        .filter((elem: IMyElem) => elem.idPage === idPage)
        .sort((a: any, b: any) => a.order - b.order);

      // Trova l'indice dell'elemento con _id = idelem
      const index = sortedElems.findIndex((elem: IMyElem) => elem._id === idelem);

      // ritorna l'elemento successivo
      if (index < sortedElems.length - 1) {
        return sortedElems[index + 1];
      } else {
        return sortedElems[sortedElems.length - 1];
      }
    },

    getmenu: (state: IGlobalState): any => {
      // console.log('getmenu', cfgrouter.getmenu())

      const mystate = state

      mystate.menulinks = {
        Dashboard: {
          routes: cfgrouter.getmenu(),
          show: true,
        },
      }

      return mystate.menulinks

    },

    isPresenteCardsByProv: (state: IGlobalState) => (myprov: string) => {
      const arrprov: any[] = state.provinces.filter((prov: IProvince) => prov.prov === myprov && (!!prov.card))
      return arrprov && arrprov.length > 0
    },

    getRespByUsername: (state: IGlobalState) => (username: string) => {
      const rec = state.resps.find((recin: any) => recin.username === username)
      return !!rec ? rec.name + ' ' + rec.surname : ''
    },

    getListByTable: (state: IGlobalState) => (table: string, value2?: any): any => {
      let ris: any = []

      const calendarStore = useCalendarStore()
      const Products = useProducts()
      const circuitStore = useCircuitStore()
      const userStore = useUserStore()
      const catalogStore = useCatalogStore()
      const messageStore = useMessageStore()
      const notifStore = useNotifStore()


      if (table === costanti.TABEVENTS)
        return calendarStore.eventlist
      else if (table === 'operators')
        return calendarStore.operators
      else if (table === 'internalpages')
        return calendarStore.internalpages
      else if (table === 'wheres')
        return calendarStore.wheres
      else if (table === 'contribtypes')
        return calendarStore.contribtype
      else if (table === shared_consts.TABFILTRI_UTENTE)
        return [...shared_consts.RECFILTRI_UTENTE, ...((userStore.isFacilitatore || userStore.isAdmin) ? shared_consts.RECFILTRI_UTENTE_FACIL : [])]
      else if (table === 'disciplines') ris = state.disciplines
      else if (table === toolsext.TABNEWSLETTER) ris = state.newstosent
      else if (table === toolsext.TABGALLERY) ris = state.gallery
      else if (table === toolsext.TABTEMPLEMAIL) ris = state.templemail
      else if (table === toolsext.TABDESTNEWSLETTER) ris = state.destnewsletter
      else if (table === toolsext.TABOPZEMAIL) ris = state.opzemail
      else if (table === toolsext.TABMAILINGLIST) ris = state.mailinglist
      else if (table === toolsext.TABMYPAGE) ris = state.mypage
      else if (table === 'mypages_id') ris = state.mypage
      else if (table === toolsext.TABMYELEMS) ris = state.myelems
      else if (table === toolsext.TABCATALOGS) ris = catalogStore.catalogs!
      else if (table === toolsext.TABCALZOOM) ris = state.calzoom
      else if (table === 'producers') ris = state.producers
      else if (table === 'storehouses') ris = state.storehouses
      else if (table === 'providers') ris = state.providers
      else if (table === 'productinfos') ris = Products.productInfos
      // else if (table === 'products') ris = Products.products
      else if (table === 'gasordines') ris = state.gasordines
      else if (table === 'scontisticas') ris = state.scontisticas
      else if (table === 'groups') ris = state.groups
      else if (table === 'resps') ris = state.resps
      else if (table === 'workers') ris = state.workers
      else if (table === 'departments') ris = state.departments
      else if (table === 'categorys') ris = state.categories
      else if (table === 'catprods') ris = Products.catprods
      else if (table === 'catprtotali') ris = Products.catprtotali
      else if (table === 'collanas') ris = Products.collane
      else if (table === 'collanastotali') ris = Products.collane
      else if (table === 'subcatprods') ris = Products.subcatprods
      else if (table === 'catprods_gas') ris = Products.catprods_gas
      else if (table === 'authors') ris = Products.authors
      else if (table === 'publishers') ris = Products.publishers
      else if (table === 'publishers_totali') ris = Products.publishers
      else if (table === 't_web_statiprodottos') ris = Products.stati_prodotto
      else if (table === 't_web_tipologies') ris = Products.tipologie
      else if (table === 't_web_tipiformatos') ris = Products.tipoformato
      else if (table === 'catais') ris = state.catAI
      else if (table === 'queryais') ris = state.queryAIList
      else if (table === 'sharewithus') ris = state.sharewithus
      else if (table === 'paymenttypes') ris = state.paymenttypes
      else if (table === 'circuits') ris = circuitStore.listcircuits
      else if (table === 'listcircuits') ris = circuitStore.getCircuitsLabelValue()
      else if (table === 'listaccounts') ris = circuitStore.getAccountsListNameValue()
      else if (table === 'bookings')
        return calendarStore.bookedevent
      else if (table === 'users')
        return userStore.usersList
      else if (table === 'friends')
        return userStore.my.profile.friends
      else if (table === 'lista_editori') {
        ris = userStore.listaEditori
      } else if (table === 'friendsandme')
        return [{ username: userStore.my.username }, ...userStore.my.profile.friends]
      // else if (table === 'mygroups')
      //   return userStore.groups
      else if (table === 'mygroups')
        return state.mygroups
      else if (table === 'sendmsgs')
        return messageStore.last_msgs
      else if (table === 'sendnotifs')
        return notifStore.last_notifs
      else if (table === 'settings')
        return state.settings
      else if (table === 'levels')
        return state.levels
      else if (table === 'adtypes')
        return state.adtypes
      else if (table === 'adtypegoods')
        return state.adtypegoods
      else if (table === 'skills')
        return state.skills
      else if (table === 'goods')
        return state.goods
      // else if (table === 'subskills')
      //   return state.subSkills
      else if (table === 'statusSkills')
        return state.statusSkills
      else if (table === toolsext.TABSECTORS)
        return state.sectors
      else if (table === 'sectorgoods')
        return state.sectorgoods
      else if (table === 'catgrps')
        return state.catgrps
      else if (table === 'schedeopt')
        return Products.getSchedeOpt(state.myschedas)
      else if (table === 'provinces')
        return state.provinces.filter((rec: IProvince) => (!rec.card) && (rec.prov !== 'ITA') && (rec.prov !== 'EST'))
      else if (table === 'cards') {
        const arrprov: any[] = state.provinces.filter((prov: IProvince) => prov.prov === value2 && (!!prov.card))
        if (arrprov) {
          // const idCardArray: { _id: number, card: string }[] = arrprov.map(({ _id, card }) => ({ _id, card }));
          const idCardArray: { card: string, label: string }[] = arrprov.map(({ card }) => ({ card, label: card }));
          return idCardArray
        }
        return []
      }

      else {
        return ris
      }

      return ris
    },

    getrecSettingsByKey: (state: IGlobalState) => (key: any, serv: any): ISettings | undefined => {
      if (serv) return state.serv_settings.find((rec) => rec.key === key)
      const ris = state.settings.find((rec) => rec.key === key)
      // console.log('getrecSettingsByKey=', ris)
      return ris
    },

    getCmdClick: (state: IGlobalState): string => (state.clickcmd ? state.clickcmd : ''),

    gettemplemailbyId: (mystate: IGlobalState) => (templid: string): string => {
      const myrec = mystate.templemail.find((rec) => rec._id === templid)
      return (!!myrec) ? myrec.subject! : ''
    },
    getdestnewsletterbyId: (mystate: IGlobalState) => (id: string): string => {
      const myrec = mystate.destnewsletter.find((rec: IDestNewsletter) => rec._id === id)
      return (!!myrec) ? myrec.descr! : ''
    },

  },

  actions: {
    getMyElems(path: string): IMyElem[] | [] {
      const mypage = this.getPage(`/${path}`)
      if (mypage) {
        const idPage = mypage._id
        let arrelems = this.myelems.filter((myelem: IMyElem) => (myelem.idPage === idPage)).sort((a: any, b: any) => a.order - b.order)
        if (arrelems.length > 0)
          return arrelems
        // Se non lo trovo per ID allora lo cerco per path
        const arrelempath = this.myelems.filter((myelem: IMyElem) => (myelem.path === path)).sort((a: any, b: any) => a.order - b.order)
        return arrelempath
      }
      return [];
    },

    setValueSettingsByKey({ key, value, serv }: { key: string, value: any, serv: boolean }): any {
      // Update the Server

      // Update in Memory
      let myrec = null
      if (serv) myrec = this.serv_settings.find((rec: any) => rec.key === key)
      else myrec = this.settings.find((rec: any) => rec.key === key)

      if (myrec) {
        if ((myrec.type === costanti.FieldType.date) || (myrec.type === costanti.FieldType.onlydate)) myrec.value_date = value
        else if ((myrec.type === costanti.FieldType.number) || (myrec.type === costanti.FieldType.hours)) myrec.value_num = value
        else if (myrec.type === costanti.FieldType.boolean) myrec.value_bool = value
        else myrec.value_str = value

        // console.log('setValueSettingsByKey value', value, 'myrec', myrec)
      }
    },

    getValueSettingsByKey(key: any, serv: any): any {
      const myrec = this.getrecSettingsByKey(key, serv)
      // console.log('getValueSettingsByKey', myrec, 'key=', key, 'srv=', serv)
      if (myrec) {
        if ((myrec.type === costanti.FieldType.date) || (myrec.type === costanti.FieldType.onlydate)) return myrec.value_date
        if ((myrec.type === costanti.FieldType.number) || (myrec.type === costanti.FieldType.hours)) return myrec.value_num
        if (myrec.type === costanti.FieldType.boolean) return myrec.value_bool
        else if (myrec.type === costanti.FieldType.crypted)
          return '***********'
        else if (myrec.value_str === undefined) {
          return ''
        } else {
          return myrec.value_str
        }
      }
      return ''
    },

    changeCmdClick(value: string) {
      console.log('changeCmdClick', value)
      this.clickcmd = value
    },

    isOnline(): boolean {
      return this.stateConnection === 'online'
    },

    getLangAvailable() {
      let myarrLang = []
      // console.log('lang Server: ', this.site.confpages.lang)
      if (tools.isLangEnabled(costanti.Lang.IT)) {
        myarrLang.push({
          label: 'Italiano', icon: 'fa-flag-it', value: 'it', image: '../images/it.png', short: 'IT',
        })
      }
      if (tools.isLangEnabled(costanti.Lang.EN)) {
        // console.log('ENG')
        myarrLang.push(
          {
            label: 'English', icon: 'fa-flag-us', value: 'enUs', image: '../images/gb.png', short: 'EN',
          },
        )
      }
      if (tools.isLangEnabled(costanti.Lang.ES)) {
        myarrLang.push(
          {
            label: 'Español', icon: 'fa-flag-es', value: 'es', image: '../images/es.png', short: 'ES',
          },
        )
      }

      if (tools.isLangEnabled(costanti.Lang.FR)) {
        myarrLang.push(
          { label: 'Français', icon: 'fa-facebook', value: 'fr', image: '../public/images/fr.png', short: 'FR' })
      }
      if (tools.isLangEnabled(costanti.Lang.DE)) {
        myarrLang.push(
          { label: 'German', icon: 'fa-flag-de', value: 'de', image: '../public/images/de.png', short: 'DE' }
        )
      }

      return myarrLang
    },

    addDynamicPages($router: Router | null) {
      // console.log('this.mypage', this.mypage)
      /// console.log('addDynamicPages.........')
      const arrpagesroute: IListRoutes[] = []

      for (const page of this.mypage) {
        if (page.active) {
          if (this.isMyLang(page)) {
            // console.log('page.active', page.title)
            // console.log('page', page.title, 'OK')
            arrpagesroute.push({
              active: true,
              order: page.order ? page.order : 1000,
              lang: page.lang,
              path: `/${page.path}`,
              name: '',
              text: page.title,
              subtitle: page.subtitle,
              materialIcon: page.icon,
              iconsize: page.iconsize,
              component: () => import('@src/root/mypage/mypage.vue'),
              inmenu: page.inmenu,
              onlySocioResidente: page.only_residenti,
              onlyConsiglio: page.only_consiglio,
              color: page.color,
              infooter: page.infooter,
              onlyif_logged: page.onlyif_logged,
              level_child: page.l_child,
              level_parent: page.l_par,
              submenu: page.submenu,
              extraclass: page.extraclass,
              mainMenu: page.mainMenu,
              sottoMenu: page.sottoMenu,
            })
          }
        }
      }

      const baseroutes = static_data.getDynamicPages(this.site);

      const adminRoutes = routesAdmin.routesAd(this.site);
      const ecommRoutes = routesECommerce.routesEcomm(this.site);
      const AIRoutes = routesAI.routesAI(this.site);

      const last = {
        active: true,
        order: 10000,
        path: '/:catchAll(.*)*',
        materialIcon: 'fas fa-calendar-plus',
        name: 'otherpages.error404def',
        component: () => import('@src/root/My404page/My404page.vue'),
        inmenu: false,
        infooter: false,
      }

      const sito_offline = {
        active: true,
        order: 20,
        path: '/sito_offline',
        materialIcon: 'home',
        name: 'otherpages.sito_offline',
        component: () => import('@src/rootgen/sito_offline/sito_offline.vue'),
        inmenu: false,
        infooter: false,
      }

      // console.log('Sito Online? ', toolsext.sito_online(false))

      if (!toolsext.sito_online(false)) {
        static_data.routes = [sito_offline, last]
      } else {
        static_data.routes = [sito_offline, ...baseroutes, ...ecommRoutes, ...adminRoutes, ...arrpagesroute, ...AIRoutes, last]
      }

      /*for (const menu of static_data.routes) {
        if (menu.active && menu.routes2) {
          for (const menu2 of menu.routes2) {
            if (menu2.active && !menu2.noroute) {
              arrpagesroute.push(menu2)
            }
          }
        }
      }*/

      // Sort array
      static_data.routes = static_data.routes.sort((a, myb) => a.order - myb.order)

      // console.log('static_data.routes', static_data.routes)

      // console.log('$router', $router)

      if ($router) {
        static_data.routes.forEach((route: any) => {
          if (!$router.hasRoute(route.name) && !route.noroute) {
            $router.addRoute(route)
          }

          if (route.routes2) {
            for (const route2 of route.routes2) {
              if (!$router.hasRoute(route2.name) && !route2.noroute) {
                $router.addRoute(route2)
              }

              if (route2.routes2) {
                for (const route3 of route2.routes2) {
                  if (!$router.hasRoute(route3.name) && !route3.noroute) {
                    $router.addRoute(route3)
                  }
                }
              }

            }
          }
        })


        if (!tools.sito_online(false)) {
          $router.replace('/sito_offline')
        }

        // console.log('getRoutes', $router.getRoutes())

        const mypathsel = $router.currentRoute.value.fullPath
        if (mypathsel !== '/') {
          // console.log('mypathsel', mypathsel)

          const trovato = this.mypage.filter((rec: IMyPage) => (rec.path === mypathsel) && (rec.active))

          // if ($router.currentRoute.value.fullPath in ) {
          if (trovato) {
            $router.replace(mypathsel)
          }
        }

      }
    },

    setPaoArray_Delete(state: IGlobalState) {
      state.testp1.mioarray.pop()
    },

    setConta(num: number) {
      this.conta = num
    },

    setleftDrawerOpen(bool: boolean) {
      this.leftDrawerOpen = bool
      tools.localStSetItem(toolsext.localStorage.leftDrawerOpen, bool.toString())
    },

    setCategorySel(cat: string | null) {
      this.category = cat || ''
    },

    setStateConnection(stateconn: StateConnection) {
      if (this.stateConnection !== stateconn) {
        console.log('INTERNET ', stateconn)
        this.stateConnection = stateconn
      }
    },

    saveConfig(data: IConfig) {
      // this.$set(dataout, data.value, {'value': 'default value'})
      return globalroutines('write', 'config', { _id: data._id, value: data.value })
    },

    SetwasAlreadySubOnDb(subscrib: boolean) {
      this.wasAlreadySubOnDb = subscrib
    },

    setShowType(showtype: number) {
      const todos = useTodoStore()
      console.log('setShowType', showtype)
      const config = this.getConfigbyId(costanti.CONFIG_ID_SHOW_TYPE_TODOS)
      console.log('config', config)
      if (config) {
        config.value = String(showtype)
        todos.showtype = parseInt(config.value, 10)
      } else {
        todos.showtype = showtype
      }
      console.log('Todos.state.showtype', todos.showtype)
      this.saveConfig({ _id: costanti.CONFIG_ID_SHOW_TYPE_TODOS, value: String(showtype) })

    },

    UpdateValuesInMemory(mydata: IDataToSet): void {
      const { id } = mydata
      const { table } = mydata

      try {
        const mylist = this.getListByTable(table!)
        const mykey = fieldsTable.getKeyByTable(table!)

        if (mylist) {
          const myrec = mylist.find((event: any) => event[mykey] === id)
          // console.log('myrec', myrec)
          if (myrec) {
            // console.log('key', value, myrec[key])
            for (const [key, value] of Object.entries(mydata.fieldsvalue)) {
              myrec[key] = value
            }
          }
        }
      } catch (e) {
        console.error(e)
      }
    },

    UpdateValuesInMemoryByTable(mydata: any, table: string): void {

      try {
        const mylist = this.getListByTable(table)
        const mykey = fieldsTable.getKeyByTable(table)
        const id = mydata[mykey]

        console.log('mylist', mylist)
        console.log('mykey', mykey)
        console.log('id', id)

        if (mylist) {
          const myrec = mylist.find((event: any) => event[mykey] === id)
          // console.log('myrec', myrec)
          if (myrec) {
            // console.log('key', value, myrec[key])
            for (const [key, value] of Object.entries(mydata)) {
              myrec[key] = value
            }
          }

          console.log('update: ', myrec)
        }
      } catch (e) {
        console.error(e)
      }
    },

    newValueInMemoryByTable(mydata: any, table: string): void {

      try {
        const mylist = this.getListByTable(table)

        if (mylist) {
          mylist.push(mydata)

        }
      } catch (e) {
        console.error(e)
      }
    },

    async createPushSubscription() {

      // console.log('ENTER TO createPushSubscription')
      // If Already subscribed, don't send to the Server DB
      // if (state.wasAlreadySubOnDb) {
      //   // console.log('wasAlreadySubOnDb!')
      //   return
      // }


      if (!this.site.confpages || !this.site.confpages.enablePwa)
        return

      if (!('serviceWorker' in navigator)) {
        console.log('serviceWorker not present !')
        return
      }

      if (!('PushManager' in window)) {
        console.log('PushManager not present !')
        return
      }

      console.log('createPushSubscription')

      let reg: any
      const mykey = import.meta.env.VITE_PUBLICKEY_PUSH
      if (navigator.serviceWorker) {
        return navigator.serviceWorker.ready
          .then((swreg) => {
            reg = swreg
            return swreg.pushManager.getSubscription()
          })
          .then((subscription) => {
            console.log('!!!!!!!!  subscription = ', subscription)

            this.wasAlreadySubscribed = !(subscription === null)

            if (this.wasAlreadySubscribed) {
              // console.log('User is already SAVED Subscribe on DB!')
              // return null
              return subscription
            } else {
              // Create a new subscription
              console.log('####  Create a new subscription !!!')
              const convertedVapidPublicKey = urlBase64ToUint8Array(mykey)
              return reg.pushManager.subscribe({
                userVisibleOnly: true,
                applicationServerKey: convertedVapidPublicKey,
              })
            }
          })
          .then((newSub) => {
            this.saveNewSubscriptionToServer(newSub)
          })
          .catch((err) => {
            console.log('ERR createPushSubscription:', err)
          })
      }
    },

    // Calling the Server to Save in the MongoDB the Subscriber
    saveNewSubscriptionToServer(newSub: any) {
      // console.log('saveNewSubscriptionToServer')

      const userStore = useUserStore()


      if (!newSub) {
        return
      }

      if (userStore.isUserInvalid) {
        return
      }

      // console.log('saveSubscriptionToServer: ', newSub)
      // console.log('context', context)

      const options = null
      let notreg = false

      if (userStore.isTokenInvalid) {
        notreg = true
      }

      // If is not already stored in DB, then show the message to the user.
      if (!this.wasAlreadySubscribed || notreg) {
        /*
        options = {
          title: tools.translate('notification.title_subscribed', [{
            strin: 'sitename',
            strout: translate('ws.sitename'),
          }]),
          content: translate('notification.subscribed'),
          openUrl: '/',
        }

         */
      }

      const myres = {
        options,
        subs: newSub,
        others: {
          userId: userStore.my._id,
          access: userStore.my.tokens![0].access,
        },
      }

      return Api.SendReq('/subscribe', 'POST', myres)
        .then((res) => {
          this.wasAlreadySubscribed = true
          this.wasAlreadySubOnDb = true

          // if (res)
          //   console.log('saveNewSubscriptionToServer: OK')

          tools.localStSetItem(toolsext.localStorage.wasAlreadySubOnDb, String(this.wasAlreadySubOnDb))
        })
        .catch((e) => {
          console.log('Error during Subscription!', e)
        })
    },

    async deleteSubscriptionToServer() {
      console.log('DeleteSubscriptionToServer: ')

      try {
        return Api.SendReq('/subscribe/del', 'DELETE', null)
      } catch (e) {
        console.error('deleteSubscriptionToServer')
      }
    },

    async clearDataAfterLogout() {
      // console.log('clearDataAfterLogout')

      try {
        for (const table of ApiTables.allTables()) {
          await globalroutines('clearalldata', table, null)
        }
      } catch (e) {
        //
      }

      if (this.site.confpages.enablePwa) {
        if ('serviceWorker' in navigator) {
          // REMOVE ALL SUBSCRIPTION
          console.log('REMOVE ALL SUBSCRIPTION...')
          if (navigator.serviceWorker) {
            navigator.serviceWorker.ready
              .then((reg) => {
                console.log('... Ready')
                reg.pushManager.getSubscription().then((subscription) => {
                  console.log('    Found Subscription...')
                  if (subscription) {
                    subscription.unsubscribe().then((successful) => {
                      // You've successfully unsubscribed
                      console.log('You\'ve successfully unsubscribed')
                    }).catch((e) => {
                      // Unsubscription failed
                    })
                  }
                })
              }).catch((err) => {
                console.error('err ready service worker', err)
              })
          }
        }
      }

      await this.deleteSubscriptionToServer()
    },

    clearDataAfterLoginOnlyIfActiveConnection() {
      const prova = 1
      return prova
    },

    async loadLoginSite(router: Router) {
      let isok = false
      let code = 200

      let stop = false

      const { ris, status } = await this.loadSite()

      if (status === toolsext.ERR_RETRY_LOGIN) {
        stop = true
        code = status
      } else {
        isok = true
      }

      return { isok, stop, code }
    },

    async loadAfterLogin() {
      const userStore = useUserStore()

      // console.log('loadAfterLogin')
      this.clearDataAfterLoginOnlyIfActiveConnection()

      await userStore.loadListaEditori()

      await globalroutines('readall', 'config', null)

      if (tools.isLogged()) {
        const pageKey = window.location.pathname
        this.editOn = tools.getCookie('edn_' + pageKey, '0') === '1'
      }
    },

    async saveCfgServerKey(dataval: ICfgServer) {
      //console.log('saveCfgServerKey dataval', dataval)

      const ris = await Api.SendReq('/admin/updateval', 'POST', { pairval: dataval })
    },

    async checkUpdates() {
      console.log('checkUpdates')

      const userStore = useUserStore()

      // if (userStore.my._id === '')
      //   return false // Login not made

      this.networkDataReceived = false

      const ris = await Api.SendReq('/checkupdates', 'GET', null)
        .then((res) => {
          this.networkDataReceived = true

          // console.log('******* checkUpdates RES :', res.data.cfgServer)
          if (res.data.CfgServer) {
            this.cfgServer = [...res.data.CfgServer]
            // console.log('res.data.cfgServer', res.data.cfgServer)
          }

          // console.log('res.data.userslist', res.data.usersList)
          if (res.data.usersList) {
            userStore.setusersList(res.data.usersList)
          }

          if (res.data.last_msgs) {
            // ++Todo conv: MessageStore.last_msgs = [...res.data.last_msgs]
          }

          // console.log('MessageStore.last_msgs', MessageStore.last_msgs)

          // console.log('**********  res', 'todos', todos, 'checkPending', checkPending)
          // After Login will store into the indexedDb...

          return res
        })
        .catch((error) => {
          console.log('error checkUpdates', error)
          userStore.setErrorCatch(error)
          return error
        })
    },

    async sendPushNotif({ params }: { params: any }) {

      return Api.SendReq('/push/send', 'POST', { params })
        .then((res) => {
          // console.table(res)
          return res.data
        })
        .catch((error) => {
          console.log('error sendPushNotif', error)
          return null
        })
    },

    async loadTable(params: IParamsQuery) {
      const userStore = useUserStore()

      return Api.SendReq('/gettable', 'POST', params)
        .then((res) => {
          this.serverError = false
          // if (tools.isDebug())
          // console.table(res)
          return res.data
        })
        .catch((error) => {
          this.serverError = true
          this.serverMsgError = error
          console.log('error loadTable', error)
          userStore.setErrorCatch(error)
          return null
        })
    },

    async getObjOnServer(cmd: string) {
      const userStore = useUserStore()

      return Api.SendReq('/getobj', 'POST', { cmd })
        .then((res) => {
          this.serverError = false
          return res.data.data
        })
        .catch((error) => {
          this.serverError = true
          this.serverMsgError = error
          console.log('error getObjOnServer', error)
          userStore.setErrorCatch(error)
          return null
        })
    },

    async loadExp(params: any) {
      // console.log('loadTable', params)
      params.filtersearch2 = 'fdsgas1'

      return Api.SendReq('/getexp', 'POST', params)
        .then((res) => {
          return res.data ? res.data : []
        })
        .catch((error) => {
          return []
        })
    },

    loadPickup(params: IParamsPickup) {
      console.log('loadPickup', params)
      const userStore = useUserStore()

      return Api.SendReq('/pickup', 'POST', params)
        .then((res) => {
          // console.table(res)
          return res.data
        })
        .catch((error) => {
          console.log('error loadPickup', error)
          userStore.setErrorCatch(error)
          return null
        })
    },

    async caricaTabella(table: string, extrapar: string) {

      const myarr = []
      const sortBy = 'descr'
      const descending = 1
      const myobj: any = {}
      if (descending)
        myobj[sortBy] = -1
      else
        myobj[sortBy] = 1

      const params: IParamsQuery = {
        newvers: true,
        table: '',
        startRow: 0,
        endRow: 10000,
        filter: '',
        filterand: '',
        filtersearch: '',
        filtersearch2: '',
        filtercustom: '',
        filter_gte: '',
        sortBy: myobj,
        descending,
        userId: '',
        extrapar,
        noaut: false,
      }

      params.table = table
      return this.loadTable(params).then((data) => {
        return data
      }).catch((e) => {
        return []
      })
    },

    async loadPage(path: string, dove?: string) {
      const userStore = useUserStore()

      path = path.substring(1)
      const mypage = this.getPage(`/${path}`)

      // console.log('mypage', mypage)

      // Controlla se l'ho già caricato
      if (!!mypage && (!!mypage.content || mypage.loadFirst || mypage.loaded)) {
        return mypage
      }

      // console.log(dove, '*** loadPage', path)

      return Api.SendReq('/getpage', 'POST', { path })
        .then((res) => {
          // console.table(res)
          if (res) {
            const index = this.mypage.findIndex((rec) => rec.path === path)
            if (index >= 0) {
              // console.log('load page', path, '...')
              this.mypage[index] = res.data.mypage
              this.mypage[index].loaded = true
            }
            return res.data.mypage
          }
          return null
        })
        .catch((error) => {
          console.log('error loadTable', error)
          userStore.setErrorCatch(error)
          return null
        })
    },

    async duplicatePage(path: string, $q: any, t: any) {
      const userStore = useUserStore()

      let newpath = prompt(t('mypages.duplica_newname'))

      if (!newpath)
        return false

      $q.dialog({
        message: t('mypages.duplica_conferma', { path, newpath }),
        ok: { label: t('dialog.yes'), push: true },
        cancel: { label: t('dialog.cancel') },
        title: t('db.domanda')
      }).onOk(() => {


        return Api.SendReq('/duppage', 'POST', { path, newpath })
          .then((res) => {
            if (res) {
              tools.showPositiveNotif($q, t('mypages.duplicateok'))
              return true
            } else {
              tools.showNegativeNotif($q, t('mypages.duplicateerr'))
              return false
            }
          })
          .catch((error) => {
            console.log('error loadTable', error)
            userStore.setErrorCatch(error)
            return null
          })
      })

    },

    async exportPage(path: string, $q: any, t: any) {
      const userStore = useUserStore()

      return Api.SendReq('/exppage', 'POST', { path })
        .then((res) => {
          if (res && res.data && res.data.json) {
            tools.showPositiveNotif($q, t('mypages.expok'))
            return res.data.json
          } else {
            tools.showNegativeNotif($q, t('mypages.experr'))
            return null
          }
        })
        .catch((error) => {
          console.log('error loadTable', error)
          userStore.setErrorCatch(error)
          return null
        })
    },

    importPage(jsonString: string, $q: any, t: any) {
      const userStore = useUserStore()

      return Api.SendReq('/imppage', 'POST', { jsonString })
        .then((res) => {
          if (res && res.data && res.data.ris) {
            tools.showPositiveNotif($q, t('mypages.impok'))
            return res.data.ris
          } else {
            tools.showNegativeNotif($q, t('mypages.imperr'))
            return null
          }
        })
        .catch((error) => {
          console.log('error importPage', error)
          userStore.setErrorCatch(error)
          return null
        })
    },

    async loadPageTest() {

      console.log('loadPageTest')

      const obj = { test: 'OK! Versione Client: ' + tools.getvers() }

      return Api.SendReq('/testServer', 'POST', obj)
        .then((res) => {
          return res
        })
        .catch((error) => {
          return error
        })
    },

    async saveTable(mydata: any) {
      // console.log('saveTable', mydata)
      const userStore = useUserStore()

      return Api.SendReq('/settable', 'POST', mydata)
        .then((res) => {
          this.serverError = false
          // console.log('res', res)
          if (res && res.data) {
            tools.updateMyData(res.data.ris)

            this.aggiornaRecordInLocaleDopoUpdateSulServer(mydata, res.data)
            if (res.data.rec) {
              return res.data.rec
            } else {
              return res.data
            }
          }
        })
        .catch((error) => {
          this.serverError = true
          this.serverMsgError = error
          console.log('error saveTable', error)
          userStore.setErrorCatch(error)
          return null
        })
    },

    isErroreDispositivoServer() {
      if (this.serverMsgError) {
        if (this.serverMsgError.code)
          return this.serverMsgError.code === -2
      } else {
        return false
      }

      return false
    },

    async saveSubRec(mydata: any) {
      // console.log('saveTable', mydata)
      const userStore = useUserStore()

      return Api.SendReq('/setsubrec', 'POST', mydata)
        .then((res) => res.data)
        .catch((error) => {
          console.log('error saveSubRec', error)
          userStore.setErrorCatch(error)
          return null
        })
    },

    async saveNewRecord(mytable: string, myrec: any) {
      const userStore = useUserStore()
      console.log('saveNewRecord', mytable, myrec)

      const mydata: any = {
        table: mytable,
        data: myrec
      }

      mydata.data.userId = userStore.my._id

      const ris = await this.saveTable(mydata)

      if (ris) {
        this.newValueInMemoryByTable(ris, mytable)
      }

      console.log('saveNewRecord', ris)
      return ris
    },

    async saveFieldValue(mydata: IDataToSet) {
      // const userStore = useUserStore()
      return Api.SendReq('/chval', 'PATCH', { data: mydata })
        .then((res) => {
          if (res) {
            if (mydata.aggiornainmem)
              this.UpdateValuesInMemory(mydata)
            return (res.data.code === serv_constants.RIS_CODE_OK)
          }
          return false
        })
        .catch((error) => false)
    },

    async callFunz({ mydata }: { mydata: any }) {
      // console.log('saveFieldValue', mydata)

      return Api.SendReq('/callfunz', 'PATCH', { data: mydata })
        .then((res) => {
          if (res) {
            return (res.data.code === serv_constants.RIS_CODE_OK)
          } else
            return false
        })
        .catch((error) => {
          return false
        })
    },

    async askFunz({ mydata }: { mydata: any }) {
      // console.log('saveFieldValue', mydata)

      return Api.SendReq('/askfunz', 'PATCH', { data: mydata })
        .then((ris) => {
          return ris.data.out
        })
        .catch((error) => {
          return null
        })
    },

    async DeleteRec({ table, id }: { table: string, id: string }) {
      console.log('DeleteRec', table, id)

      return Api.SendReq('/delrec/' + table + '/' + id, 'DELETE', null)
        .then((res) => {
          if (res.status === 200) {
            if (res.data.code === serv_constants.RIS_CODE_OK) {
              return true
            }
          }
          return false
        })
        .catch((error) => {
          console.error(error)
          return false
        })
    },

    async DeleteFile({ filename }: { filename: string }) {
      console.log('DeleteFile', filename)

      return Api.SendReq(`/delfile/${tools.getvers()}/`, 'DELETE', { filename })
        .then((res) => {
          if (res.status === 200) {
            if (res.data.code === serv_constants.RIS_CODE_OK) {
              return true
            }
          }
          return false
        })
        .catch((error) => {
          console.error(error)
          return false
        })
    },

    async DuplicateRec({ table, id }: { table: string, id: string }) {
      console.log('DuplicateRec', id)

      return Api.SendReq('/duprec/' + table + '/' + id, 'POST', null)
        .then((res) => {
          if (res.status === 200) {
            if (res.data.code === serv_constants.RIS_CODE_OK) {
              return res.data.record
            }
          }
          return null
        })
        .catch((error) => {
          console.error(error)
          return null
        })
    },

    async InviaMsgADonatori({ msgobj, navemediatore, tipomsg }: { msgobj: any, navemediatore: any, tipomsg: any }) {
      console.log('InviaMsgADonatori', msgobj)

      const mydata = {
        idapp: tools.getEnv('VITE_APP_ID'),
        msgextra: msgobj.msgextra,
        msgpar1: msgobj.msgpar1,
        username: msgobj.username,
        username_mitt: msgobj.username_mitt,
        tipomsg,
        inviareale: msgobj.inviareale,
        navemediatore,
      }

      return Api.SendReq('/dashboard/msgnave', 'POST', mydata)
        .then((res) => {
          if (res.status === 200) {
            if (res.data.code === serv_constants.RIS_CODE_OK) {
              return res.data.ris
            }
          }
          return null
        })
        .catch((error) => {
          console.error(error)
          return null
        })
    },

    async InviaMsgAFlotta({ flotta, inviareale, inviaemail, tipomsg }: { flotta: any, inviareale: boolean, inviaemail: boolean, tipomsg: any }) {
      console.log('InviaMsgAFlotta')

      const mydata = {
        idapp: tools.getEnv('VITE_APP_ID'),
        tipomsg,
        flotta,
        inviareale,
        inviaemail,
      }

      return Api.SendReq('/dashboard/msgflotta', 'POST', mydata)
        .then((res) => {
          if (res.status === 200) {
            if (res.data.code === serv_constants.RIS_CODE_OK) {
              return res.data.ris
            }
          }
          return null
        })
        .catch((error) => {
          console.error(error)
          return null
        })
    },

    async GetArrNavi() {
      console.log('GetArrNavi')

      const mydata = {
        idapp: tools.getEnv('VITE_APP_ID'),
      }

      return Api.SendReq('/dashboard/getnavi', 'POST', mydata)
        .then((res) => {
          if (res.status === 200) {
            if (res.data.code === serv_constants.RIS_CODE_OK) {
              return res.data.ris
            }
          }
          return null
        })
        .catch((error) => {
          console.error(error)
          return null
        })
    },

    async GetMsgTemplates() {
      console.log('GetMsgTemplates')

      const mydata = {
        idapp: tools.getEnv('VITE_APP_ID'),
      }

      return Api.SendReq('/dashboard/getmsg_templates', 'POST', mydata)
        .then((res) => {
          if (res.status === 200) {
            if (res.data.code === serv_constants.RIS_CODE_OK) {
              return res.data.ris
            }
          }
          return null
        })
        .catch((error) => {
          console.error(error)
          return null
        })
    },

    async GetNave({ riga, col, riga1don, col1don, ind_order }: { riga: any, col: any, riga1don: any, col1don: any, ind_order: number }) {
      // console.log('GetNave')

      const mydata = {
        idapp: tools.getEnv('VITE_APP_ID'),
        riga,
        col,
        riga1don,
        col1don,
        ind_order,
      }

      return Api.SendReq('/dashboard/getnave', 'POST', mydata)
        .then((res) => {
          if (res.status === 200) {
            if (res.data.code === serv_constants.RIS_CODE_OK) {
              return res.data.ris
            }
          }
          return null
        })
        .catch((error) => {
          console.error(error)
          return null
        })
    },

    async GetData({ data }: { data: any }) {
      console.log('GetData')

      const mydata = {
        idapp: tools.getEnv('VITE_APP_ID'),
        data,
      }

      return Api.SendReq('/dashboard/getdata', 'POST', mydata)
        .then((res) => {
          if (res.status === 200) {
            if (res.data.code === serv_constants.RIS_CODE_OK) {
              return res.data.ris
            }
          }
          return null
        })
        .catch((error) => {
          console.error(error)
          return null
        })
    },

    async GetArrDoniNavi({ ricalcola, showall }: { ricalcola: boolean, showall: boolean }) {
      console.log('GetArrDoniNavi')

      const mydata = {
        idapp: tools.getEnv('VITE_APP_ID'),
        ricalcola,
        showall,
      }

      return Api.SendReq('/dashboard/getdoninavi', 'POST', mydata)
        .then((res) => {
          if (res.status === 200) {
            if (res.data.code === serv_constants.RIS_CODE_OK) {
              return res.data.ris
            }
          }
          return null
        })
        .catch((error) => {
          console.error(error)
          return null
        })
    },

    async GetFlotte({ ricalcola, showall }: { ricalcola: boolean, showall: boolean }) {
      console.log('GetFlotte')

      const mydata = {
        idapp: tools.getEnv('VITE_APP_ID'),
        ricalcola,
        showall,
      }

      return Api.SendReq('/dashboard/getflotte', 'POST', mydata)
        .then((res) => {
          if (res.status === 200) {
            if (res.data.code === serv_constants.RIS_CODE_OK) {
              return res.data.arrflotte
            }
          }
          return null
        })
        .catch((error) => {
          console.error(error)
          return null
        })
    },

    async GetFlotta({ riga, col_prima, col_ultima }: { riga: any, col_prima: any, col_ultima: any }) {
      console.log('GetFlotta')

      const mydata = {
        idapp: tools.getEnv('VITE_APP_ID'),
        riga,
        col_prima,
        col_ultima,
      }

      return Api.SendReq('/dashboard/getflotta', 'POST', mydata)
        .then((res) => {
          if (res.status === 200) {
            if (res.data.code === serv_constants.RIS_CODE_OK) {
              return res.data
            }
          }
          return null
        })
        .catch((error) => {
          console.error(error)
          return null
        })
    },

    async loadTest(ind: number, numval: number) {
      const restest = await Api.SendReq(`/testpao/?numval=${numval}&ind=${ind}`, 'GET', null)
      return restest
    },

    async loadSite() {
      const userStore = useUserStore()
      const calendarStore = useCalendarStore()
      const circuitStore = useCircuitStore()
      const Products = useProducts()
      const catalogStore = useCatalogStore()

      let status = 0

      // console.log('calendarStore: loadAfterLogin')
      // Load local data
      const showall = userStore.isAdmin || userStore.isManager ? '1' : '0'

      const myuserid = (userStore.my._id) ? userStore.my._id : '0'

      // calendarStore.editable = false

      try {
        const res = await Api.SendReq(`/loadsite/${myuserid}/${tools.getEnv('VITE_APP_ID')}/${import.meta.env.VITE_APP_VERSION}`, 'GET', null)
        status = res.status
        if (res.status === 200) {

          console.log('____________________________  res', res)
          this.serverError = false
          if (res.status === 200) {

            calendarStore.bookedevent = (res.data.bookedevent) ? res.data.bookedevent : []
            calendarStore.eventlist = (res.data.eventlist) ? res.data.eventlist : []
            calendarStore.operators = (res.data.operators) ? res.data.operators : []
            calendarStore.internalpages = (res.data.internalpages) ? res.data.internalpages : []
            calendarStore.wheres = (res.data.wheres) ? res.data.wheres : []
            calendarStore.contribtype = (res.data.contribtype) ? res.data.contribtype : []

            circuitStore.listcircuits = (res.data.listcircuits) ? res.data.listcircuits : []
            circuitStore.listaccounts = (res.data.listaccounts) ? res.data.listaccounts : []

            catalogStore.catalogs = res.data.catalogs

            this.settings = (res.data.settings) ? [...res.data.settings] : []
            this.disciplines = (res.data.disciplines) ? [...res.data.disciplines] : []
            this.paymenttypes = (res.data.paymenttypes) ? [...res.data.paymenttypes] : []
            this.gallery = (res.data.gallery) ? [...res.data.gallery] : []
            this.calzoom = (res.data.calzoom) ? [...res.data.calzoom] : []
            Products.products = (res.data.products) ? [...res.data.products] : []
            Products.productInfos = (res.data.productInfos) ? [...res.data.productInfos] : []
            this.producers = (res.data.producers) ? [...res.data.producers] : []
            this.storehouses = (res.data.storehouses) ? [...res.data.storehouses] : []
            this.providers = (res.data.providers) ? [...res.data.providers] : []

            Products.catprods = (res.data.catprods) ? [...res.data.catprods] : []
            Products.catprtotali = (res.data.catprtotali) ? [...res.data.catprtotali] : []
            Products.collane = (res.data.collane) ? [...res.data.collane] : []
            Products.subcatprods = (res.data.subcatprods) ? [...res.data.subcatprods] : []
            Products.stati_prodotto = (res.data.stati_prodotto) ? [...res.data.stati_prodotto] : []
            Products.tipologie = (res.data.tipologie) ? [...res.data.tipologie] : []
            Products.tipoformato = (res.data.tipoformato) ? [...res.data.tipoformato] : []
            Products.catprods_gas = (res.data.catprods_gas) ? [...res.data.catprods_gas] : []
            Products.authors = (res.data.authors) ? [...res.data.authors] : []
            Products.publishers = (res.data.publishers) ? [...res.data.publishers] : []

            this.gasordines = (res.data.gasordines) ? [...res.data.gasordines] : []
            this.scontisticas = (res.data.scontisticas) ? [...res.data.scontisticas] : []
            this.groups = (res.data.groups) ? [...res.data.groups] : []
            this.resps = (res.data.resps) ? [...res.data.resps] : []
            this.workers = (res.data.workers) ? [...res.data.workers] : []
            this.departments = (res.data.departments) ? [...res.data.departments] : []
            this.categories = (res.data.categories) ? [...res.data.categories] : []
            this.levels = (res.data.levels) ? [...res.data.levels] : []
            this.skills = (res.data.skills) ? [...res.data.skills] : []
            this.goods = (res.data.goods) ? [...res.data.goods] : []
            // this.subSkills = (res.data.subSkills) ? [...res.data.subSkills] : []
            this.statusSkills = (res.data.statusSkills) ? [...res.data.statusSkills] : []
            this.sectors = (res.data.sectors) ? [...res.data.sectors] : []
            this.sectorgoods = (res.data.sectorgoods) ? [...res.data.sectorgoods] : []
            this.provinces = (res.data.provinces) ? [...res.data.provinces] : []
            this.catgrps = (res.data.catgrps) ? [...res.data.catgrps] : []
            this.catAI = (res.data.catAI) ? [...res.data.catAI] : []
            if (res.data.queryAIList)
              this.queryAIList = res.data.queryAIList
            this.site = (res.data.site) ? res.data.site : {}
            this.mygroups = (res.data.mygroups) ? [...res.data.mygroups] : []
            this.adtypes = (res.data.adtypes) ? [...res.data.adtypes] : []
            this.adtypegoods = (res.data.adtypegoods) ? [...res.data.adtypegoods] : []

            // console.log('res.data.cart', res.data.cart)

            if (res.data.cart)
              Products.cart = (res.data.cart) ? { ...res.data.cart } : {}
            else
              Products.cart = { items: [], totalPrice: 0, totalQty: 0, userId: '' }

            Products.orders = (res.data.orders) ? [...res.data.orders] : []


            if (showall) {
              this.newstosent = (res.data.newstosent) ? [...res.data.newstosent] : []
              this.mailinglist = (res.data.mailinglist) ? [...res.data.mailinglist] : []
            }
            this.mypage = (res.data.mypage) ? [...res.data.mypage] : []
            for (const page of this.mypage) {
              if (page.loadFirst)
                page.loaded = true
            }
            this.myelems = (res.data.myelems) ? [...res.data.myelems] : []
            this.crons = (res.data.crons) ? [...res.data.crons] : []
            this.myschedas = []
            this.myschedas = (res.data.myschedas) ? [...res.data.myschedas] : []
            // console.log('this.mypage', this.mypage)

            let isLogged = false

            // console.log('res.data.myuser', res.data.myuser)
            if (res.data.myuser) {
              userStore.authUser(res.data.myuser)

              userStore.updateLocalStorage(res.data.myuser)

              isLogged = !!res.data.myuser.username
            } else {
              // User not exist !!

            }

            // const isLogged = localStorage.getItem(toolsext.localStorage.username)
            // console.log('isLogged', isLogged)

            let myidapp = ''
            try {
              if (res.data?.myuser) {
                myidapp = res.data?.myuser?.idapp
              }
            } catch (e) {

            }

            // calendarStore.editable = userStore.isAdmin || userStore.isManager || userStore.isFacilitatore
            if (!myidapp || (myidapp !== tools.getEnv('VITE_APP_ID'))) {
              if (isLogged) {
                // Fai Logout
                // console.log('Fai Logout', 'isLogged', isLogged)
                userStore.logout()
                this.rightDrawerOpen = true
                return false
              } else {
                console.log('NON SONO LOGGATO... MYUSER NON TORNATO dal SRV',)
                const token = localStorage.getItem(toolsext.localStorage.token)
                if (token) {
                  console.log('Sbianca cmq i dati')
                  // Sbianca cmq i dati
                  userStore.logout()
                  this.rightDrawerOpen = true
                  return false
                }
              }
            }
          }

          return { ris: true, status }
        } else {
        }
      } catch (error) {
        status = error.status
        if (error.status === toolsext.ERR_RETRY_LOGIN) {

        } else {

          if (error.status === serv_constants.RIS_CODE__HTTP_FORBIDDEN_TOKEN_EXPIRED ||
            error.status === serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN
          ) {

          } else {
            this.serverError = true
          }
        }

        console.log('error dbLoad', error)
        // userStore.setErrorCatch(error)

        this.serverMsgError = error
        //return new Types.AxiosError(serv_constants.RIS_CODE_ERR, null, toolsext.ERR_GENERICO, error)
        return { ris: false, status }
      }

      return { ris: false, status }
    },

    getProvinceByProv(provstr: string) {

      const recprov = this.provinces.find((rec: any) => rec.prov === provstr)

      return recprov ? recprov.descr : ''


    },

    getArrCardByProv(provstr: string): string[] {

      const recprov = this.provinces.filter((rec: any) => rec.prov === provstr)

      const cardArray: string[] = recprov.map((prov: IProvince) => prov.card);

      return cardArray


    },

    async sendEmailTest({ previewonly }: { previewonly: any }) {
      const usertosend = {
        locale: tools.getLocale(),
        previewonly
      }
      console.log(usertosend)

      return Api.SendReq('/news/testemail', 'POST', usertosend)
        .then((res) => {
          return res
        })
    },


    getArrStrByValueBinary(col: IColGridTable, val: any) {
      const arr = this.getArrByValueBinary(null, col, val)
      if (arr.length > 0) return arr.join(' - ')
      return '[---]'
    },

    getArrByValueBinary(mythis: any, col: IColGridTable, val: any) {
      if (col.jointable) {
        const mylist = this.getTableJoinByName(col.jointable)
        const key = fieldsTable.getKeyByTable(col.jointable)
        const myres: any = []
        mylist.forEach((myrec: any) => {
          if (tools.isBitActive(val, myrec[key])) myres.push(mythis.t(myrec.label))
        })

        return myres
      }
      return []
    },

    getRecordByTableSingle(table: string, val: any) {
      if (table) {
        const mylist = this.getTableJoinByName(table)
        const key = fieldsTable.getKeyByTable(table)

        return mylist.find((myrec: any) => myrec[key] === val)
      }
    },

    getValueByTableSingle(table: string, val: any, lab?: any) {
      if (table) {
        const mylist = this.getTableJoinByName(table)
        const key = fieldsTable.getKeyByTable(table)
        let collab = lab
        if (!lab)
          collab = fieldsTable.getLabelByTable(table)

        // console.table(mylist)
        let risultato = ''

        if (tools.isObject(collab)) {
          risultato = mylist.filter((myrec: any) => myrec.username === val).map(collab)
        } else {
          const myris = mylist.find((myrec: any) => myrec[key] === val)
          if (myris)
            risultato = myris[collab]
        }

        if (key === 'username') {
          // console.log('key=', key, 'collab', collab, 'val', val)
          // console.log('myris', risultato)
        }

        return risultato
      }
      return ''
    },


    getValueByTable(col: IColGridTable, val: any) {
      return this.getValueByTableSingle(col.jointable!, val)
    },

    getMultiValueByTable(col: IColGridTable, arrval: any) {
      // console.log('getMultiValueByTable')
      if (col.jointable) {
        const mylist = this.getTableJoinByName(col.jointable)
        const key = fieldsTable.getKeyByTable(col.jointable)
        const collab = fieldsTable.getLabelByTable(col.jointable)

        // console.table(mylist)
        // console.log('key=', key, 'collab', collab, 'val', collab)

        const myris = mylist.filter((myrec: any) => arrval.includes(myrec[key]))
        // console.log('myris', myris)
        if (myris) {
          console.log('collab', collab)
          if (tools.isObject(collab)) return myris.map(collab)
          return myris.map((rec: any) => rec[collab])
        }
        return ''
      }
      return ''
    },

    async getStatSite() {

      const userStore = useUserStore()

      const paramquery = {
        locale: tools.getLocale(),
        username: userStore.my.username
      }

      return Api.SendReq('/site/load', 'POST', paramquery)
        .then((res) => {
          // console.log('datastat', res)
          this.datastat = res.data.datastat
          return this.datastat
        }).catch((error) => {
          return {}
        })

    },

    async getQueryAI() {

      const userStore = useUserStore()

      const paramquery = {
        locale: tools.getLocale(),
        username: userStore.my.username
      }

      return Api.SendReq('/aitools/getlist', 'POST', paramquery)
        .then((res) => {
          // console.log('queryAIList', res)
          this.queryAIList = res.data.queryAIList
          return this.queryAIList
        }).catch((error) => {
          return {}
        })

    },

    async getQueryDS(prompt: string, options: any) {

      const userStore = useUserStore()

      const paramquery = {
        locale: tools.getLocale(),
        username: userStore.my.username,
        prompt,
        options,
      }

      return Api.SendReq('/aitools/ds', 'POST', paramquery, false, true, 1, 5000, null, null, options)
        .then((res) => {
          return res.data
        }).catch((error) => {
          return {}
        })

    },

    getItemDate(num: number, day: number, numdays: number, mystr: string) {
      let mydate = tools.addDays(tools.getDateNow(), day)
      let mydateend = tools.addDays(mydate, numdays)
      mydate = tools.getstrYYMMDDDate(mydate)
      mydateend = tools.getstrYYMMDDDate(mydateend)
      const filter = { dateTimeStart: { $gte: mydate, $lte: mydateend } }
      const obj = { _id: num, datestr: mystr, filter }

      return obj
    },

    getArrDateEvent() {
      const arr = []

      const obj = {}

      arr.push(this.getItemDate(1, -30, 30, 'Eventi Passati'))
      arr.push(this.getItemDate(2, 0, 365, 'Prossimi Eventi'))
      // arr.push(this.getItemDate(2, 0, 14, 'Da Oggi a 2 sett.'))
      /// arr.push(this.getItemDate(3, 14, 60, 'Eventi Futuri'))

      // console.log('Days', arr)

      return arr
    },

    getArrAllDateEvent() {
      const arr = []

      let obj = {}

      for (let i = 0; i < 120; i++) {
        const mydate = tools.addDays(tools.getDateNow(), i - 30)
        obj = { _id: mydate, datestr: tools.getstrVeryShortDate(mydate) }
        arr.push(obj)
      }

      // console.log('Days', arr)

      return arr
    },

    getTableJoinByName(table: string, addall?: boolean, addnone?: boolean, filter?: any, value2?: any) {

      let myarr: any = []
      if (table === 'permissions') myarr = [shared_consts.Permissions.Admin, shared_consts.Permissions.Manager, shared_consts.Permissions.Teacher, shared_consts.Permissions.Facilitatore, shared_consts.Permissions.Editor, shared_consts.Permissions.Zoomeri, shared_consts.Permissions.Department, shared_consts.Permissions.Grafico]
      else if (table === 'accepted') myarr = [shared_consts.Accepted.CHECK_READ_GUIDELINES, shared_consts.Accepted.CHECK_SEE_VIDEO_PRINCIPI]
      else if (table === 'fieldstype') myarr = costanti.FieldTypeArr
      else if (table === 'metodo_pagamento') myarr = tools.SelectMetodiPagamento
      else if (table === 'confsite_opt') myarr = tools.ConfSiteOpt
      else if (table === 'confpages_lang') myarr = costanti.ArrLang
      else if (table === 'bottype') myarr = shared_consts.BotType
      else if (table === 'visibility') myarr = shared_consts.Visibility
      else if (table === 'cat_interesse_arcadei') myarr = shared_consts.Cat_Interesse_Arcadei
      else if (table === 'pub_to_share') myarr = shared_consts.Pub_to_Share
      else if (table === 'visibilGroup') myarr = shared_consts.VisibilGroup
      else if (table === 'statuscircuit') myarr = shared_consts.StatusCircuit
      else if (table === 'elemtypes') myarr = shared_consts.TypesElem
      else if (table === 'fonts_installed') myarr = shared_consts.FontsInstalled
      else if (table === 'lang') myarr = shared_consts.Lang
      else if (table === 'regions') myarr = shared_consts.Regions
      else if (table === 'shippings') myarr = shared_consts.Shippings
      else if (table === 'otherfilters') myarr = shared_consts.OtherFilters
      else if (table === toolsext.TABCALDATE) myarr = this.getArrDateEvent()
      else if (table === toolsext.TABCALALLDATE) myarr = this.getArrAllDateEvent()
      else if (table === toolsext.TABTYPEHOSP) myarr = shared_consts.TypeHosps
      else if (table === 'tipodest') myarr = shared_consts.DESTNEWSLETTER_ARRAY
      else if (table === 'versions') myarr = shared_consts.VERSIONI_PRODOTTO
      else if (table === toolsext.TABPEOPLE) myarr = shared_consts.People
      else if (table === toolsext.TABTYPEACCOM) myarr = shared_consts.TypeAccom
      else if (table === toolsext.TABLOCACCOM) myarr = shared_consts.LocationAccom
      else if (table === toolsext.TABPREF) myarr = shared_consts.Preferences
      else if (table === toolsext.TABUNITS) myarr = shared_consts.Units_Of_Measure_ListBox
      else if (table === toolsext.TABTYPECASH) myarr = shared_consts.TypeCashStr
      else if (table === 'usernotifs') myarr = shared_consts.UsersNotif_Adv_List
      else if (table === 'typenotifs') myarr = shared_consts.TypeNotifs_Arr
      else if (table === toolsext.TABTIPODIATTIVITA) myarr = shared_consts.TipoDiAttivita
      else myarr = this.getListByTable(table, value2)

      if (costanti.TABLES_ARRAY.includes(table)) {
        const newarr = []
        for (const value of myarr) {
          let label = value
          let valout = value
          // if (table === 'mygroups') {
          //  label = value.descr
          //  valout = value.groupname
          if (table === 'circuits') {
            label = value.name
          }

          // console.log('value', value, 'label', label)
          newarr.push({ value: valout, label, name: label })
        }

        myarr = newarr
      }

      /* if (addall) {
        //myarr = [costanti.FILTER_TUTTI, ...myarr]
        const mykey = fieldsTable.getKeyByTable(table)
        const collab = fieldsTable.getLabelByTable(table)
        let obj: any = {}
        obj[mykey] = costanti.FILTER_TUTTI
        obj[collab] = costanti.FILTER_TUTTI_STR

        myarr = [obj, ...myarr]
      }*/

      if (addnone) {
        const mykey = fieldsTable.getKeyByTable(table)
        const collab = fieldsTable.getLabelByTable(table)
        let obj: any = {}
        obj[mykey] = costanti.FILTER_NESSUNO
        obj[collab] = '[Nessuno]'

        if (table === shared_consts.TABLES_MYGOODS) {
          obj.idSectorGood = []
        } else if ((table === shared_consts.TABLES_MYSKILLS)) {
          obj.idSector = []
        }

        if (table === 'cards') {
          obj = { card: '', label: '[Nessuna]' }
        }
        myarr = [obj, ...myarr]

      }

      if (filter) {
        // console.log('table', table, 'filter', filter, 'arrprima', myarr)
        myarr = myarr.filter(filter)
        // console.log('myarr', myarr)
      }

      return myarr
    },

    getMsgServerError() {
      if (this.serverError) {
        if (this.serverMsgError) {
          if (this.serverMsgError.status === 500) {
            return 'Errore Interno del Server'
          } else if (this.serverMsgError.msgerr === '') {
            return 'Codice Errore ' + this.serverMsgError.status
          }
          try {
            return this.serverMsgError.msgerr.message
          } catch (e) {
            return this.serverMsgError.msgerr
          }
        }
      }

      return ''
    },

    getTableJoinLabelValueByName(col: IColGridTable) {
      let myarrrec: any = []
      if (col.jointable) {
        let myarrtab = this.getTableJoinByName(col.jointable, col.addall, col.addnone, col.filter)

        const key = fieldsTable.getKeyByTable(col.jointable)
        const collab = fieldsTable.getLabelByTable(col.jointable)

        for (let index = 0; index < myarrtab.length; index++) {
          let obj = { label: '', value: 0 }
          obj.label = myarrtab[index][collab]
          obj.value = myarrtab[index][key]
          myarrrec.push(obj)
        }

      }

      return myarrrec
    },

    getServerHost() {

      try {
        let myserv = import.meta.env.VITE_MONGODB_HOST!

        if (!import.meta.env.VITE_DEBUG) {
          if (tools.isTest()) {
            if (this.site && this.site.host_testapi) {
              myserv = this.site.host_testapi
              // console.log('getServerHost TEST API', myserv)
            }
          } else {
            if (this.site && this.site.host_api) {
              myserv = this.site.host_api
              // console.log('getServerHost API', myserv)
            }
          }

        }

        console.log('getServerHost', myserv)

        return myserv
      } catch (e) {
        return import.meta.env.VITE_MONGODB_HOST
      }

    },

    async delMyElem($q: any, t: any, myelem: IMyElem) {

      if (!myelem._id)
        return false

      return await this.DeleteRec({ table: 'myelems', id: myelem._id })
        .then(async (ris) => {
          if (ris) {
            this.myelems = this.myelems.filter((rec) => rec._id !== myelem._id)

            // Aggiorna anche tutto il sito...
            // await this.loadSite()

            tools.showPositiveNotif($q, t('db.deletedrecord'))
            return true
          } else {
            tools.showNegativeNotif($q, t('db.recdelfailed'))
            return false
          }
        })
    },

    async saveMyElem($q: any, t: any, myelem: IMyElem) {
      const mydata = {
        table: 'myelems',
        data: {}
      }
      console.log('   DA SALVARE', myelem)

      mydata.data = myelem

      return await this.saveTable(mydata)
        .then(async (newelem) => {
          if (newelem) {
            console.log('*** newelem', newelem)

            // Save in Memory
            for (let i = 0; i < this.myelems.length; i++) {
              if (this.myelems[i]._id === newelem._id) {
                this.myelems[i] = newelem;

                console.log('SALVATO', this.myelems[i])
                break;
              }
            }

            // Aggiorna anche tutto il sito...
            // await this.loadSite()

            tools.showPositiveNotif($q, t('db.recupdated'))
          } else {
            tools.showNegativeNotif($q, t('db.recfailed'))
          }
          return newelem
        }).catch((e) => {
          tools.showNegativeNotif($q, t('db.recfailed'))
          return false
        })


    },

    async addNewElem($q: any, t: any, myelem: IMyElem) {
      const newelem = await this.saveMyElem($q, t, myelem)
      if (newelem) {
        this.myelems.push(newelem)
      }

      return newelem
    },

    changeVisuDrawer(path: string, edit: boolean) {
      const userStore = useUserStore()

      if (userStore.isManager)
        tools.setCookie('EDITPAGES', edit ? '-1' : '0')
    },

    getGeoJsonByProvince(prov: string) {
      const usertosend = {
        prov,
      }
      // console.log(usertosend)

      return Api.SendReq('/city/geojson', 'POST', usertosend)
        .then((res) => {
          return res.data ? res.data.ris : []
        })
    },

    createCatalogoVuoto(): IOptCatalogo {
      return {
        productTypes: [0],
        excludeproductTypes: [],
        idTipologie: [],
        formato: [],
        Categoria: [],
        editore: [],
        pdf: false,
        dimensioni_def: {
          pagina: tools.resetRecIDimensioni(null)
        },
        areadistampa: tools.resetRecIAreaDiStampa(null),
      }
    },

    async prepareAddNewElem(order: any, $q: any, t: any, myelem: any, newtype: any) {

      const newrec: IMyElem = {
        _id: undefined,
        type: newtype,
        path: myelem.path,
        idPage: myelem.idPage,
        order: order ? order : 1000,
        active: true,
        container: ''
      }

      if (newrec.type === shared_consts.ELEMTYPE.CAROUSEL_IMGS) {
        newrec.container2 = '8'
        newrec.height = 600
      } else if (newrec.type === shared_consts.ELEMTYPE.CARD) {
        newrec.class2 = 'row justify-center'
      } else if (newrec.type === shared_consts.ELEMTYPE.SEARCHPRODUCT) {

        newrec.catalogo = this.createCatalogoVuoto()

      } else if (newrec.type === shared_consts.ELEMTYPE.CATALOGO) {
        newrec.catalogo = this.createCatalogoVuoto()
      }

      const mynewrec = await this.addNewElem($q, t, newrec)

      return mynewrec

    },

    getIconBySector(sectorId: string) {
      const myrec = this.sectors.find((rec: any) => rec._id === sectorId)

      if (myrec && myrec.icon) {
        return myrec.icon
      } else {
        return 'fas fa-home'
      }
    },

    async execScript(paramquery: any) {
      return Api.SendReq('/admin/exec', 'POST', paramquery)
        .then((res) => {
          return res.data
        }).catch((error) => {
          return false
        })
    },

    async execConvertPDF(paramquery: any) {
      // console.log('paramquery', paramquery)
      return Api.SendReq('/admin/convert-pdf', 'postFormData', {}, false, false, 1, 5000, paramquery, { responseType: 'blob' })
        .then((res) => {
          return res.data
        }).catch((error) => {
          return false
        })
    },

    async convertPdf(pdfFile: any, width: string, height: string, compressione: string, dir_out: string, file_out: string) {
      try {

        if (!pdfFile) {
          console.error('No PDF file selected');
          return;
        }

        const filenameToDownload = tools.removeFileExtension(pdfFile.name) + '-compresso.pdf'

        const formData = new FormData();
        if (pdfFile instanceof File) {
          formData.append('pdf', pdfFile);
        }
        formData.append('width', width); // Dimensione del PDF in cm
        formData.append('height', height); // Dimensione del PDF in cm
        formData.append('compressione', compressione);
        formData.append('dir_out', dir_out);
        formData.append('file_out', file_out);
        formData.append('idapp', tools.getEnv('VITE_APP_ID'));

        const response = await this.execConvertPDF(formData)

        if (response) {
          const blob = new Blob([response], { type: 'application/pdf' });
          const downloadUrl = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = downloadUrl;
          link.setAttribute('download', filenameToDownload);
          document.body.appendChild(link);
          link.click();
          link.remove();

          window.URL.revokeObjectURL(downloadUrl);
        } else {
          console.error('No data returned from the server.');
        }

      } catch (error) {
        console.error('Error converting PDF:', error);
      }
    },

    async saveServerMysql(paramquery: any) {
      return Api.SendReq('/admin/mysql', 'POST', paramquery)
        .then((res) => {
          return res.data
        }).catch((error) => {
          return false
        })
    },

    async getCloudFlareTok(cmd: string, tok: string, zoneId: string, dnsRecordId: any = null, record: any = undefined) {

      const mydata = {
        cmd,
        tokcheck: "php8.1_version_762321HSD121nJDokq@?!aFS.tar.gz",
        tok,
        zoneId,
        dnsRecordId,
        record,
      }

      return Api.SendReq('/admin/cloudflare', 'POST', mydata)
        .then((res) => {
          return res.data
        }).catch((error) => {
          return false
        })
    },

    async getGM_Tabella(options: IOptQueryGM) {
      const arrrec = await this.fetchTableContent(options);

      return arrrec
    },
    async getGM_Lista_Argomenti(outhtml: boolean) {
      const arrrec = await this.fetchTableContent({ nameTable: 'T_Web_Argomenti', numrec: 200, outhtml });

      return arrrec
    },

    async getGM_FieldOf_T_Web_Articoli(sku: string, field: string, cmd: number) {

      const options: IOptQueryGM = {
        nameTable: 'T_Web_Articoli',
        campispeciali: !field,
        numrec: 1,
        query: '',
        where: 'T.IdArticolo =' + sku + ' AND T.DataPubblicazione IS NOT NULL ORDER BY T.DataOra DESC;',
        fieldGM: field,
        showQtaDisponibile: false,
        outhtml: false,
        cmd,
      }

      const valueris = await this.fetchTableContent(options);
      if (valueris && valueris[field]) {
        console.log('valueris', valueris)
        return valueris[field]
      }

      return null
    },
    async updateLocalDbFromGM_T_Web_Articoli(sku: string, isbn: string) {

      const options: IOptQueryGM = {
        nameTable: 'T_Web_Articoli',
        query: '',
        where: 'T.IdArticolo =' + sku + ' AND T.Ean13 = \'' + isbn + '\'',
        showQtaDisponibile: false,
        outhtml: false,
        cmd: shared_consts.CmdQueryMs.UPDATE,
        updatelocaldb: true,
      }

      const valueris = await this.fetchTableContent(options);

      return !!valueris
    },
    async updateAllBookFromGM_T_Web_Articoli(options: any) {

      const valueris = await this.updateAllBookTableContent(options);

      return valueris
    },

    async setGM_FieldOf_T_Web_Articoli(sku: string, data: Record<string, any>, cmd: number) {
      try {
        // Verifica se i campi specificati sono validi
        if (!data || Object.keys(data).length === 0) {
          throw new Error("I campi specificati non sono validi.");
        }

        // Costruisce le opzioni per l'aggiornamento
        const options: IOptQueryGM = {
          nameTable: 'T_Web_Articoli',
          insertMode: false, // Impostiamo su false per eseguire un UPDATE (modifica)
          data, // Dati da aggiornare
          where: `IdArticolo = ${sku}`, // Condizione WHERE basata sullo SKU
          cmd,
        };

        // Eseguiamo l'operazione di salvataggio
        const result = await this.saveTableContent(options);

        // Restituiamo il risultato dell'operazione
        return result;
      } catch (error) {
        console.error("Errore durante l'aggiornamento dei campi:", error.message);
        throw new Error(`Errore durante l'aggiornamento dei campi per lo SKU ${sku}: ${error.message}`);
      }
    },


    async fetchTableContent(options: IOptQueryGM) {
      try {
        // aggiungi idapp ad options
        options.idapp = tools.getEnv('VITE_APP_ID')
        console.log('CHIAMATA fetchTableContent...', options)
        return Api.SendReq('/apisqlsrv/view-table', 'POST', { options })
          .then((res) => {
            return res.data.data
          }).catch((error: any) => {
            console.error('Error fetchTableContent: ', error)
          })
      } catch (error) {
        console.error("Errore nel recupero della tabella:", error);
      }
    },

    async updateTablesInMemory(data: any) {

      const table = data.table
      const id = data.idRecUpdated

      if (!id)
        return

      const productStore = useProducts()

      try {
        if (table === 'products') {
          await productStore.loadProductById(id)
        } else if (table === 'productinfos') {

        }
      } catch (error) {
        console.error("Errore durante l'aggiornamento della tabella in memoria:", error);
      }
    },

    async updateAllBookTableContent(options: any) {
      try {
        // aggiungi idapp ad options
        options.idapp = tools.getEnv('VITE_APP_ID')
        return await Api.SendReq('/apisqlsrv/updateAllBook', 'POST', { options })
          .then(async (res) => {
            if (res?.data?.data?.logerror) {
              return { error: 'Errore ' + res?.data?.data?.logerror }
            }
            await this.updateTablesInMemory(res.data.data)
            return res.data.data
          }).catch((error: any) => {
            console.error('Error fetchTableContent: ', error)
            return { error: 'Errore ' + error }
          })
      } catch (error) {
        console.error("Errore nel recupero della tabella:", error);
        throw error;
      }
    },

    async saveTableContent(options: IOptQueryGM) {
      try {
        return Api.SendReq('/apisqlsrv/save-table', 'POST', { options })
          .then((res) => {
            return res.data.data
          }).catch((error: any) => {
            console.error('Error saveTableContent: ', error)
          })
      } catch (error) {
        console.error("Errore nel salvataggio della tabella:", error);
        throw error;
      }
    },

    async getMailInABox(cmd: string, record: any = undefined) {

      const mydata = {
        cmd,
        tokcheck: "php8.1_version_762321HSD121nJDokq@?!aFS.tar.gz",
        record,
      }

      return Api.SendReq('/admin/miab', 'POST', mydata)
        .then((res) => {
          return res.data
        }).catch((error) => {
          return false
        })
    },

    async loadLastMovements(nummov: number) {
      return Api.SendReq('/users/lastmovs', 'POST', { nummov })
        .then((res) => {
          if (res.data && res.data.last_transactions && this.datastat) {
            this.datastat.last_transactions = res.data.last_transactions
          }
        }).catch((error) => {
          return {}
        })

    },

    aggiornaRecordInLocaleDopoUpdateSulServer(datain: any, resdata: any) {

      try {

        if (datain.table) {
          const mytablerec = this.getListByTable(datain.table)

          if (mytablerec && resdata && resdata.rec) {
            // Trova l'indice del record da aggiornare
            const index = mytablerec.findIndex((item: any) => item._id === resdata.rec._id)

            if (index !== -1 && index !== undefined) {
              // Aggiorna il record mantenendo reattività
              if (datain.table === 'catalogs') {
                // salva lista_prodotti
                const prec_lista_prodotti = mytablerec![index].lista_prodotti
                mytablerec![index] = { ...mytablerec[index], ...resdata.rec }
                mytablerec![index].lista_prodotti = prec_lista_prodotti
              } else {

                mytablerec![index] = { ...mytablerec[index], ...resdata.rec }
                console.log('Aggiorna il record mantenendo reattività')
              }
            }
          }
        }
      } catch (e) {

      }
    },
  },
})
