import { defineComponent, ref, onMounted, computed, watch } from 'vue'

import { CImgText } from '../../../components/CImgText/index'
import { CCard } from '@src/components/CCard'
import { CMyPage } from '@src/components/CMyPage'
import { CTitleBanner } from '@src/components/CTitleBanner'
import { CGridTableRec } from '@src/components/CGridTableRec'

import { colmyelems } from '@src/store/Modules/fieldsTable'
import MixinMetaTags from '@src/mixins/mixin-metatags'
import { tools } from '@tools'
import { shared_consts } from '@src/common/shared_vuejs'
import { IMyPage } from 'model'
import { useGlobalStore } from '@store/globalStore'

import objectId from '@src/js/objectId'

export default defineComponent({
  name: 'editElems',
  setup() {

    const { setmeta } = MixinMetaTags()

    const globalStore = useGlobalStore()

    const arrPages = ref([] as any[])

    const pageSel = ref('')

    watch(() => pageSel.value, (newval: any, oldval) => {
      tools.setCookie('s_elems', newval)
    })

    const filtercustom = computed(() => [{ idPage: pageSel.value }])

    function mounted() {

      arrPages.value = []
      arrPages.value.push({ label: '[Vuoto]', path: '' })
      for (const page of globalStore.mypage) {

        const rec = {
          // @ts-ignore
          label: page.title,
          // @ts-ignore
          value: page._id
        }
        arrPages.value.push(rec)
      }

      // Aggiungi anche le pagine cancellate, in cui gli elementi non hanno più una pagina collegata

      for (const elem of globalStore.myelems) {
        const pagetofind = arrPages.value.find((page: any) => page.value === elem.idPage)
        if (!pagetofind) {
          // non c'è in lista:
          arrPages.value.push({ label: 'pag non trovata: ' + elem.idPage, value: elem.idPage })
        }
      }


      // filtercustom.value = [{ userId: userStore.my._id }]
    }

    onMounted(mounted)

    pageSel.value = tools.getCookie('s_elems', '')

    return {
      colmyelems,
      setmeta,
      arrPages,
      pageSel,
      filtercustom,
    }
  },
  components: { CImgText, CCard, CMyPage, CTitleBanner, CGridTableRec }
})
