import type { PropType } from 'vue';
import { defineComponent, onMounted, ref, watch, computed, onBeforeUnmount, nextTick } from 'vue'
import { tools } from '@tools'
import { useUserStore } from '@store/UserStore'
import { useRouter } from 'vue-router'
import { useGlobalStore } from '@store/globalStore'
import { useProducts } from '@store/Products'
import { useI18n } from 'vue-i18n'
import { toolsext } from '@store/Modules/toolsext'
import { useQuasar } from 'quasar'
import { costanti } from '@costanti'

import { shared_consts } from '@src/common/shared_vuejs'
import { CProductCard } from '@src/components/CProductCard'

import { CMySelect } from '@src/components/CMySelect'
import { CContainerCatalogoCard } from '@src/components/CContainerCatalogoCard'
import { CSelectUserActive } from '@src/components/CSelectUserActive'
import type {
  IOptCatalogo, IDimensioni, IFilterCatalogo,
  IMyScheda, IProdView, IProduct, ISchedaSingola, ISearchList, ICatalog, IImg
} from 'model';


import { fieldsTable } from '@store/Modules/fieldsTable'
import { useCatalogStore } from '@src/store/CatalogStore'

export default defineComponent({
  name: 'CSearchProduct',
  components: { CContainerCatalogoCard, CProductCard, CSelectUserActive, CMySelect },
  emits: [],
  props: {
    modelValue: {
      type: Object as PropType<IOptCatalogo>,
      required: true,
    },
  },
  setup(props, { emit }) {
    const userStore = useUserStore()
    const globalStore = useGlobalStore()
    const productStore = useProducts()
    const router = useRouter()
    const $q = useQuasar()
    const { t } = useI18n()

    const search = ref('')

    const loadpage = ref(false)
    const refreshpage = ref(false)
    const show_hide = ref(false)

    const mycolumns = ref([])

    const idPage = ref('')
    const selauthor = ref('')

    const searchList = ref(<any[]>[])

    const optcatalogo = ref<IOptCatalogo | null>(null);

    const myproduct = ref(<IProduct>{})

    const labelcombo = computed(() => (item: any) => {
      let lab = item.label
      if (item.showcount)
        lab += ' (' + valoriopt.value(item, false, false).length + ')'
      return lab
    })

    const listaRicerca = computed(() => {
      const mylist = searchList.value.find((rec: any) => rec.table === 'products' && rec.key === 'titolo')

      return mylist
    })


    const searchText = computed(() => {
      const lista = listaRicerca.value
      return lista && lista.value && tools.existProp(lista.value, 'name') ? lista.value.name : ''
    })

    const valoriopt = computed(() => (item: any, addall: boolean, addnone: boolean = false) => {
      // console.log('valoriopt', item.table)
      return globalStore.getTableJoinByName(item.table, addall, addnone, item.filter)
    })

    watch(() => searchText.value, (newval, oldval) => {
      console.log('searchText=', searchText.value)
      const id = getSearchId()
      loadProduct(id)
    })

    async function loadProduct(id: string) {
      // Carica il prodotto

      if (id) {
        myproduct.value = await productStore.loadProductById(id)
      } else {
        myproduct.value = null
      }

      if (myproduct.value) {
        tools.setCookie(tools.COOK_LAST_PROD_SEARCH, myproduct.value._id.toString())
      } else {
        tools.setCookie(tools.COOK_LAST_PROD_SEARCH, '')
      }

    }

    function resetSearch() {
      const mialista = listaRicerca.value
      if (mialista && mialista.value && tools.existProp(mialista.value, 'name')) {
        mialista.value = null
      }
      search.value = ''
    }


    function getSearchId(): string {
      const lista = listaRicerca.value
      return lista && lista.value && lista.value._id ? lista.value._id : ''
    }

    async function mounted() {
      // console.log('mounted Catalogo')

      optcatalogo.value = props.modelValue
      loadpage.value = false

      const id = tools.getCookie(tools.COOK_LAST_PROD_SEARCH, '')

      if (id) {
        await loadProduct(id)
      }

      mycolumns.value = fieldsTable.getArrColsByTable('products')

      searchList.value = [
        {
          visible: true,
          label: 'Ricerca',
          table: 'products',
          key: 'titolo',
          type: costanti.FieldType.select_by_server,
          value: myproduct.value?.productInfo?.name,
          // addall: true,
          arrvalue: [],
          useinput: true,
          filter: null,
          tablesel: 'products',
        },
      ]

      // Inizializza
      loadpage.value = true

    }


    function naviga(path: string) {
      router.push(path)
    }

    onMounted(mounted)

    return {
      userStore,
      costanti,
      tools,
      toolsext,
      search,
      shared_consts,
      productStore,
      t,
      loadpage,
      refreshpage,
      show_hide,
      searchList,
      fieldsTable,
      mycolumns,
      naviga,
      myproduct,
      optcatalogo,
      idPage,
      selauthor,
      valoriopt,
      labelcombo,
      searchText,
    }
  }
})

