import type { PropType } from 'vue';
import { defineComponent, onMounted, ref, watch, computed } 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,
  IProduct, ISearchList
} from 'model';


import { fieldsTable } from '@store/Modules/fieldsTable'
import Products from 'app/src/rootgen/admin/products/products.vue';

export default defineComponent({
  name: 'CSearchProduct',
  components: { CContainerCatalogoCard, CProductCard, CSelectUserActive, CMySelect },
  emits: ['insert', 'close', 'updateproductmodif'],
  props: {
    modelValue: {
      type: Object as PropType<IOptCatalogo>,
      required: false,
      default: null,
    },
    idprodtoshow: {
      type: String,
      required: false,
      default: '',
    },
    empty: {
      type: Boolean,
      required: false,
      default: false,
    },
    nameLinkTemplate: {
      type: String,
      required: false,
      default: '',
    },
    visu: {
      type: Number,
      required: false,
      default: shared_consts.VISU_SEARCHPROD_MODE.VISU,
    },
  },
  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 focus = ref(false)

    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(<ISearchList[]>[])

    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)

    })
    watch(() => myproduct.value, (newval, oldval) => {
      console.log('myproduct', myproduct.value)
      // loadProduct(myproduct.value._id)
      updateproductmodif(myproduct.value)
    })

    async function loadProduct(id: string) {
      // Carica il prodotto
      console.log('loadProduct', id)

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

      saveSearch()

      console.log('myproduct.value', myproduct.value)

    }

    function saveSearch() {
      if (!props.idprodtoshow && !props.empty) {
        if (myproduct.value) {
          tools.setCookie(tools.COOK_LAST_PROD_SEARCH, myproduct.value._id.toString())
        } else {
          tools.setCookie(tools.COOK_LAST_PROD_SEARCH, '')
        }
      }

      if (!myproduct.value) {
        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 : ''
    }

    function populateDataWithlinkIdTemplate() {
      // console.log('populateDataWithlinkIdTemplate')

      if (optcatalogo.value) {

        for (const recscheda of optcatalogo.value.arrSchede!) {
          if (recscheda.scheda?.linkIdTemplate) {
            // ricopia da Template:
            const myscheda = globalStore.sovrascriviSchedaFromTemplate(recscheda.scheda?.linkIdTemplate, recscheda)
            if (myscheda) {
              recscheda.scheda = { ...myscheda }
            }

          }
        }
      }

      // console.log('   FINE - populateDataWithlinkIdTemplate')
    }


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

      if (props.modelValue) {
        optcatalogo.value = props.modelValue
      } else {
        optcatalogo.value = globalStore.createCatalogoVuoto()
        productStore.addNewScheda(optcatalogo.value)

        if (props.nameLinkTemplate) {
          const linkIdTemplate = globalStore.getLinkIdTemplateByName(props.nameLinkTemplate)
          if (linkIdTemplate)
            optcatalogo.value.arrSchede[0].scheda.linkIdTemplate = linkIdTemplate
        } else {
          optcatalogo.value.arrSchede[0].scheda.name = 'SEARCH_NEW'
        }
      }

      const id = props.idprodtoshow || (!props.empty ? tools.getCookie(tools.COOK_LAST_PROD_SEARCH, '') : '')

      if (props.nameLinkTemplate) {
        populateDataWithlinkIdTemplate()
      }

      if (props.visu === shared_consts.VISU_SEARCHPROD_MODE.INSERT) {
        focus.value = true
      }

      loadpage.value = false

      if (id) {
        await loadProduct(id)
      }


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

      searchList.value = [
        {
          visible: true,
          label: 'Cerca un Titolo o un Autore',
          table: 'products',
          key: 'titolo',
          type: costanti.FieldType.select_by_server,
          value: myproduct.value,
          collabel: collabel,
          arrvalue: [],
          useinput: true,
          filter: null,
          tablesel: 'products',
          dense: false,
        },
      ]

      // Inizializza
      loadpage.value = true

    }



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

    function collabel(rec: any) {

      let label = ''
      if (rec && rec.productInfo) {
        if (productStore.isNovitaById(rec.productInfo.date_pub))
          label += `🌟 `

        label += `${rec.productInfo.name}`;
        if (Array.isArray(rec.productInfo.authors)) {
          const authors = rec.productInfo.authors.map((a: any) => `${a.name} ${a.surname}`).join(', ');
          label += ` - (${authors})`;
        } else {
          label += rec.productInfo.authors ? ` - (${rec.productInfo.authors.name} ${rec.productInfo.authors.surname}) ` : '';
        }
        if (rec.productInfo.idStatoProdotto) {
          if (!productStore.isPubblicatoById(rec.productInfo.idStatoProdotto))
            label += ' (' + productStore.getDescrStatiProdottoByIdStatoProdotto(rec.productInfo.idStatoProdotto || '') + ')'
        }
        if (productStore.isEsaurito(rec)) {
          label += ' (Attualmente non disponibile)'
        }
        // console.log('Computed label:', label)
      }
      return label
    }

    function insertProd() {
      // console.log('insertProd')
      emit('insert', myproduct.value)
    }

    function clickClose() {
      searchList.value[0].value = ''
      myproduct.value = null
      emit('close')
    }

    function updateproductmodif(element: IProduct) {
      console.log('CSEARCHPRODUCT: updateproductmodif')
      emit('updateproductmodif', element)
    }

    async function searchOnGM(mystr: string) {
      // refreshSingleBookFromGM({usaDBGMLocale: false})
      const options = {

      }
      const ris = await globalStore.updateAllBookFromGM_T_Web_Articoli({ sku: '', isbn: mystr, ...options })
      if (ris) {

        const id = getSearchId()
        loadProduct(id)
        updateproductmodif(myproduct.value)

        // await updateproduct(false)
        if (ris.error) {
          tools.showNegativeNotif($q, ris.error)
        } else {
          tools.showPositiveNotif($q, t('dbgm.updateLocalDb_OK'))
        }

        // updatefromgm.value = false
      }

    }

    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,
      insertProd,
      focus,
      clickClose,
      saveSearch,
      updateproductmodif,
      searchOnGM,
    }
  }
})

