import type { PropType } from 'vue';
import { defineComponent, onMounted, ref, watch, computed } from 'vue'
import { useUserStore } from '@store/UserStore'
import type { ICatalog, IOptGrid, IUserFields } from 'model';
import { IImgGallery, IUserProfile } from 'model'
import { costanti } from '@costanti'
import { shared_consts } from '@src/common/shared_vuejs'
import { fieldsTable } from '@store/Modules/fieldsTable'
import { tools } from '@tools'
import { toolsext } from '@store/Modules/toolsext'
import { useQuasar } from 'quasar'
import { useI18n } from 'vue-i18n'
import { CLabel } from '@src/components/CLabel'
import { CMyCardPopup } from '@src/components/CMyCardPopup'
import { useRouter } from 'vue-router'
import { useCalendarStore } from '@src/store/CalendarStore'
import { useGlobalStore } from '@src/store/globalStore'

import type { ICatProd, ICollana, IPublisher } from "@src/model/Products"
import { useProducts } from '@src/store/Products'

export default defineComponent({
  name: 'CMyRecCatalog',
  components: { CMyCardPopup, CLabel },
  emits: ['setCmd', 'cmdext'],
  props: {
    table: {
      type: String,
      required: true,
    },
    prop_myrec: {
      type: Object as PropType<any>,
      required: false,
      default: null,
    },
    editOn: {
      type: Boolean,
      required: false,
      default: false,
    },
    dettagli: {
      type: Boolean,
      required: false,
      default: false,
    },
    margin_right: {
      type: Number,
      required: false,
      default: 0,
    },
    opt: {
      type: Object as PropType<IOptGrid>,
      required: false,
      default: () => {
        return {}
      },
    },
  },

  setup(props, { emit }) {

    const userStore = useUserStore()
    const calendarStore = useCalendarStore()
    const globalStore = useGlobalStore()
    const $q = useQuasar()
    const { t } = useI18n()
    const $router = useRouter()

    const myrec = ref(<ICatalog>{})

    const statecolor = ref('negative')
    const apriInfo = ref(false)
    const collanestr = ref('')
    const argomentistr = ref('')
    const numprodtot = ref(0)
    const editorestr = ref('')

    const products = useProducts()

    const visupage = ref(false)
    const disabilita = computed(() => {
      return props.table === shared_consts.TABLES_MYBACHECAS
    })
    const esiste_descrintro = computed(() => {
      return myrec.value.descr_introduttiva && myrec.value.descr_introduttiva.length > 100
    })
    const numprodottistr = computed(() => {
      return myrec.value.lista_prodotti?.length || 0
    })
    const pagina_collegata = computed(() => {

      let linkpage = ''

      const idpag = myrec.value.idPageAssigned
      if (idpag) {
        const mypage = globalStore.getPageById(idpag)
        if (mypage)
          linkpage = mypage.path!
      }

      return linkpage

    })

    watch(() => props.prop_myrec, (newval, oldval) => {

      mounted()
    })


    function mounted() {
      if (props.prop_myrec) {
        myrec.value = props.prop_myrec
      }

      collanestr.value = ''
      if (myrec.value.idCollane) {
        for (const idcollana of myrec.value.idCollane) {
          const reccoll: ICollana = products.collane!.find((coll: ICollana) => coll._id === idcollana)
          if (reccoll)
            collanestr.value += reccoll.title + ' '
        }
      }
      argomentistr.value = ''
      if (myrec.value.argomenti) {
        numprodtot.value = 0
        for (const arg of myrec.value.argomenti) {
          const recargomento: ICatProd = products.catprods.find((catprod: ICatProd) => catprod._id === arg)
          if (recargomento)
            argomentistr.value += recargomento.name + ' '
          numprodtot.value += products.getTotaliProdottiByIdCatProd(arg)
        }
      }



      editorestr.value = ''
      if (myrec.value.editore) {
        for (const receditore of myrec.value.editore) {
          const rectrovato: IPublisher = products.publishers.find((editore: IPublisher) => editore._id === receditore)
          editorestr.value += rectrovato?.name + ' '
        }
      }

      statecolor.value = 'negative'

      if (myrec.value.descr_introduttiva && myrec.value.img_bordata?.imagefile && myrec.value.img_intro?.imagefile) {
        statecolor.value = 'orange-8'
        if (myrec.value.pdf_generato) {
          statecolor.value = 'positive'
        }
      }
    }

    function showBadge() {
      if (shared_consts.TABLES_SHOW_ADTYPE.includes(props.table)) {
        return true
      }

      return false
    }

    function getImgUser(profile: IUserFields) {
      return userStore.getImgByProfile(profile)
    }

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



    function setCmd($q: any, cmd: number, myusername: string, value: any, groupname: string) {
      emit('setCmd', $q, cmd, myusername, value, groupname)
    }

    function cmdExt(cmd: any, val1: any, val2: any) {
      emit('cmdext', cmd, val1, val2)
    }

    function navigaExt(obj: any) {
      cmdExt(costanti.CMD_SHOW_PAGE, null, obj)
      //let link = shared_consts.getDirectoryByTable(props.table) + '/' + obj._id
      //console.log('link', link)
      //$router.push(link)
    }

    function getNameToShow(user: IUserFields, col = null) {
      if (myrec.value.groupname)
        return myrec.value.groupname
      else
        return userStore.getNameToShow(user, col)
    }

    function computedWidth() {
      const width = tools.getwidth($q) - 20;
      return `${Math.min(width, 600)}px`; // Limita la larghezza massima a 600px
    }

    onMounted(mounted)

    return {
      t,
      myrec,
      costanti,
      getImgUser,
      naviga,
      navigaExt,
      setCmd,
      shared_consts,
      userStore,
      tools,
      toolsext,
      fieldsTable,
      cmdExt,
      visupage,
      showBadge,
      getNameToShow,
      calendarStore,
      disabilita,
      globalStore,
      computedWidth,
      statecolor,
      apriInfo,
      collanestr,
      editorestr,
      pagina_collegata,
      esiste_descrintro,
      argomentistr,
      numprodtot,
      numprodottistr,
    }
  },
})
