import type { PropType } from 'vue';
import { computed, defineComponent, onMounted, ref, watch, nextTick } from 'vue'

import { CMyFieldDb } from '@src/components/CMyFieldDb'
import { CTitleBanner } from '@src/components/CTitleBanner'
import { CProfile } from '@src/components/CProfile'
import { CDateTime } from '@src/components/CDateTime'
import { CMyPage } from '@src/components/CMyPage'
import { CMyGroup } from '@src/components/CMyGroup'
import { CMyChipList } from '@src/components/CMyChipList'
import { CGridTableUser } from '@src/components/CGridTableUser'
import { CMyFieldRec } from '@src/components/CMyFieldRec'
import { CMyUser } from '@src/components/CMyUser'
import { CLabel } from '@src/components/CLabel'
import { CGalleryImages } from '@src/components/CGalleryImages'
import { CAccomodation } from '@src/components/CAccomodation'
import { tools } from '@tools'
import { useUserStore } from '@store/UserStore'
import { useCalendarStore } from '@store/CalendarStore'
import { useGlobalStore } from '@store/globalStore'
import { useI18n } from 'vue-i18n'
import { toolsext } from '@store/Modules/toolsext'
import { useQuasar } from 'quasar'
import { costanti } from '@costanti'
import type { IReaction, IBookedEventPage, IColGridTable, IBookedEvent, IEvents, IMessage, IMessagePage, IParamDialog, ISearchList } from '@model';
import { EState } from '@model'
import { shared_consts } from '@src/common/shared_vuejs'
import { colCitys, fieldsTable } from '@store/Modules/fieldsTable'
import { useRoute, useRouter } from 'vue-router'
import { useNotifStore } from '@store/NotifStore'
import { lists } from '@store/Modules/lists'
import translate from '@src/globalroutines/util'
import { useMessageStore } from '@src/store/MessageStore'
import mixinEvents from '@src/mixins/mixin-events'

export default defineComponent({
  name: 'CMyCardService',
  emits: ['showInMap'],
  components: {
    CProfile, CTitleBanner,
    CMyFieldDb, CDateTime, CMyPage, CMyFieldRec, CAccomodation,
    CMyUser, CGalleryImages, CMyChipList, CLabel, CMyGroup, CGridTableUser,
  },
  props: {
    table: {
      type: String,
      required: true,
    },
    prop_myrec: {
      type: Object as PropType<any>,
      required: false,
      default: null,
    },
    idRec: {
      type: String,
      required: false,
      default: ''
    },
    nopopup: {
      type: Boolean,
      required: false,
      default: false
    },
    showAnteprima: {
      type: Boolean,
      required: false,
      default: false,
    }
  },
  setup(props, { emit }) {

    const userStore = useUserStore()
    const calendarStore = useCalendarStore()
    const messageStore = useMessageStore()
    const notifStore = useNotifStore()
    const globalStore = useGlobalStore()
    const $q = useQuasar()
    const $route = useRoute()
    const { t } = useI18n()

    const arrfilterand: any = ref([])
    const searchList = ref(<ISearchList[]>[])

    const filter = ref(costanti.FIND_PEOPLE)

    const showPic = ref(false)
    const loading = ref(false)

    const $router = useRouter()

    const contextDay = ref(<any>null)
    const ismounted = ref(false)

    const usersList = ref(<any>{ show: false, title: '', list: [], loadfromDb: false, tipofavbook: 0 })
    const bookedList = ref(<any>{ show: false, title: '', list: [], loadfromDb: false, tipofavbook: 0 })

    const formbookEventDefault = ref(<IBookedEvent>{
      userId: '',
      username: '',
      msgbooking: '',
      infoevent: '',
      tableType: shared_consts.TABLETYPE.MyBachecas,
      numpeople: 1,
      numpeopleLunch: 0,
      numpeopleDinner: 0,
      numpeopleDinnerShared: 0,
      datebooked: tools.getDateNow(),
      booked: false,
      modified: false
    })

    const formAskForDefault = ref(<IMessage>{
      dest: '',
      origin: '',
      message: '',
    })

    const bookEventForm = ref({ ...formbookEventDefault.value })
    const askInfoForm = ref(<IMessage>{
      dest: '',
      origin: '',
      message: '',
    })

    const askInfopage = ref(<IMessagePage>{
      show: false,
      msg: {
        message: ''
      },
      state: EState.None
    })


    const bookEventpage = ref(<IBookedEventPage>{
      show: false,
      bookedevent: {
        userId: '',
        username: '',
        tableType: shared_consts.TABLETYPE.MyBachecas,
        numpeople: 0,
        infoevent: '',
        msgbooking: '',
        modified: false,
        booked: false
      },
      state: EState.Creating,
    })

    const myrec = ref(<any>null)
    const col = ref(<IColGridTable>{})

    const idnotif = computed(() => $route.query.idnotif ? $route.query.idnotif.toString() : '')
    const arrbookings = computed(() => calendarStore.findAllBookedByIdEvent(myrec.value._id))

    const isSmall = ref(props.showAnteprima);

    const cardRef = ref(<any>null)
    const smallHeight = ref('30vh')
    const largeHeight = ref('100vh')

    const cardStyle = computed(() => ({
      // height: isSmall.value ? smallHeight.value : largeHeight.value,
      transition: 'height 0.3s ease-in-out'
    }))

    const numpart = ref<number | null>(null);

    const updatePart = () => {
      numpart.value = calendarStore.getNumParticipants(
        myrec.value,
        true,
        tools.peopleWhere.participants
      );
    };

    const filtercustom: any = computed(() => {

      let queryreact = {}

      if (usersList.value.tipofavbook === costanti.TIPOFAVBOOK.SEEN) {
        queryreact = { seen: true }
      } else if (usersList.value.tipofavbook === costanti.TIPOFAVBOOK.FAVORITE) {
        queryreact = { fav: true }
      } else if (usersList.value.tipofavbook === costanti.TIPOFAVBOOK.BOOKMARK) {
        queryreact = { book: true }
      } else if (usersList.value.tipofavbook === costanti.TIPOFAVBOOK.ATTEND) {
        queryreact = { attend: true }
      }

      return [{
        idapp: tools.getEnv('VITE_APP_ID'),
        tab: tools.getNumTabByTable(props.table),
        idrec: myrec.value._id,
        ...queryreact,
      }]
    })

    function profile() {
      return userStore.my.profile
    }

    async function load() {
      // console.log('load')
      // Carica il record
      if (props.idRec) {
        await userStore.loadGeneric(props.table, props.idRec, idnotif.value).then((ris) => {
          // console.log('myrec', myrec)
          myrec.value = ris
          if (ris)
            notifStore.setAsRead(idnotif.value)
        }).catch((err) => {

        })

      } else {
        // myrec.value = props.prop_myrec
        await userStore.loadGeneric(props.table, props.prop_myrec._id, idnotif.value).then((ris) => {
          // console.log('myrec', myrec)
          myrec.value = ris
          if (ris)
            notifStore.setAsRead(idnotif.value)
        })

      }

      if (myrec.value)
        clicca(costanti.TIPOFAVBOOK.SEEN, true, myrec.value._id)

      col.value = fieldsTable.getArrColsByTable(props.table)

      updatePart()

      ismounted.value = true

    }

    watch(() => props.idRec, (to: any, from: any) => {
      if (ismounted.value)
        load()
    })

    async function mounted() {
      await load()
      await nextTick()
    }

    function updateCard() {
      if (cardRef.value) {
        largeHeight.value = !isSmall.value ? `${cardRef.value.clientHeight}px` : largeHeight.value
        if (isSmall.value)
          smallHeight.value = `${cardRef.value.clientHeight}px`
      }
    }

    function getlinkpage() {
      return self.location.host + tools.getPathByTable(props.table, myrec.value._id)
    }
    function condividipag() {
      const mystr = getlinkpage()
      tools.copyStringToClipboard($q, mystr, true)
      tools.sendMsgTelegramCmd($q, t, shared_consts.MsgTeleg.SHARE_TEXT, false, mystr)
      // Apri il BOT RISO
      tools.openUrl(tools.getLinkBotTelegram('', ''))
      return true
    }

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

      return false
    }

    function getRecGoodSkillByRec(rec: any) {
      if (props.table === 'myskills')
        return rec.recSkill
      else if (props.table === 'mygoods')
        return rec.recGood

      return null
    }

    function getSectorByRec(rec: any) {
      if (props.table === 'myskills')
        return rec.sector
      else if (props.table === 'mygoods')
        return rec.sectorGood

      return null
    }

    async function clicca(tipo: any, myset: any, title: string) {
      if (!userStore.my.username) {
        return
      }

      let mylist = null
      if (tipo === costanti.TIPOFAVBOOK.FAVORITE) {
        if (myset) {
          await userStore.setFavorite($q, t, myrec.value._id, props.table, myrec.value);
        }
        mylist = myrec.value.myreaction ? myrec.value.myreaction.filter((rec: IReaction) => rec.fav) : []
      } else if (tipo === costanti.TIPOFAVBOOK.BOOKMARK) {
        if (myset) {
          await userStore.setBookmark($q, t, myrec.value._id, props.table, myrec.value);
        }
        mylist = myrec.value.myreaction ? myrec.value.myreaction.filter((rec: IReaction) => rec.book) : []
      } else if (tipo === costanti.TIPOFAVBOOK.SEEN) {
        if (myset) {

          if (!userStore.isSeen(myrec.value._id, props.table)) {
            loading.value = true
            const risrecord = await userStore.setSeen($q, t, myrec.value._id, props.table, myrec.value)
            if (risrecord && risrecord.mybookings) {
              myrec.value = risrecord

              calendarStore.updatearrBookingEvent(myrec.value._id, risrecord.mybookings)

              bookEventpage.value.state = EState.None

              const findev = calendarStore.findEventBooked(myrec.value._id, false)
              EditBookEvent(false)
            }
            loading.value = false
          }
        }
        mylist = myrec.value.myreaction ? myrec.value.myreaction.filter((rec: IReaction) => rec.seen) : []
      } else if (tipo === costanti.TIPOFAVBOOK.ATTEND) {
        if (myset) {
          // userStore.setAttend($q, t, myrec.value._id, props.table, bookEventpage.value.bookedevent.numpeople, myrec.value);
        }
        mylist = arrbookings.value

        if (!myset && mylist && mylist.length > 0) {
          bookedList.value.show = true
          bookedList.value.title = title
          bookedList.value.list = mylist
        }
        return true;
      }

      if (!myset && mylist) {
        usersList.value.show = true
        usersList.value.title = title
        usersList.value.tipofavbook = tipo
        usersList.value.loadfromDb = true
        usersList.value.list = mylist
      }
    }

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

    function getTypeHosps() {
      let obj = null
      if (myrec.value.typeHosp) {
        obj = globalStore.getRecordByTableSingle(toolsext.TABTYPEHOSP, myrec.value.typeHosp)
        if (obj)
          return obj.label
      }

      return obj
    }

    function getTipodiAttivita() {
      let obj = null
      if (myrec.value.tipodiAttivita) {
        obj = globalStore.getRecordByTableSingle(toolsext.TABTIPODIATTIVITA, myrec.value.tipodiAttivita)
        if (obj)
          return obj.label
      }

      return obj
    }

    function hasModifiedBooking() {
      return (bookEventpage.value.bookedevent.numpeople !== bookEventForm.value.numpeople) ||
        (bookEventpage.value.bookedevent.numpeopleLunch !== bookEventForm.value.numpeopleLunch) ||
        (bookEventpage.value.bookedevent.numpeopleDinner !== bookEventForm.value.numpeopleDinner) ||
        (bookEventpage.value.bookedevent.numpeopleDinnerShared !== bookEventForm.value.numpeopleDinnerShared) ||
        (bookEventpage.value.bookedevent.msgbooking !== bookEventForm.value.msgbooking) ||
        (bookEventpage.value.bookedevent.booked !== bookEventForm.value.booked)
    }

    function checkseinviaMsg() {
      return (bookEventpage.value.state === EState.Creating) && (!bookEventForm.value.booked)
    }

    function getTitleBtnBooking() {
      if (bookEventpage.value.state === EState.Creating) {
        return t('dialog.book')
      } else {
        return t('dialog.update')
      }
    }

    function EditBookEvent(show: boolean) {

      // const bookedevent: any = calendarStore.findEventBooked(myrec.value._id, false)
      const bookedevent: any = arrbookings.value.find((recbook: IBookedEvent) => recbook.userId === userStore.my._id)


      console.log('bookedevent', bookedevent)

      if (bookedevent) {
        bookEventForm.value._id = bookedevent._id
        bookEventForm.value.numpeople = bookedevent.numpeople
        bookEventForm.value.numpeopleLunch = bookedevent.numpeopleLunch
        bookEventForm.value.numpeopleDinner = bookedevent.numpeopleDinner
        bookEventForm.value.numpeopleDinnerShared = bookedevent.numpeopleDinnerShared
        bookEventForm.value.infoevent = bookedevent.infoevent
        bookEventForm.value.msgbooking = bookedevent.msgbooking
        bookEventForm.value.booked = bookedevent.booked
        bookEventForm.value.datebooked = bookedevent.datebooked
        bookEventpage.value.state = EState.Modifying
      } else {
        bookEventpage.value.state = EState.Creating
      }

      bookEventpage.value.bookedevent = bookedevent
      bookEventpage.value.show = show
    }

    async function BookEvent(eventparam: IBookedEvent) {
      const ris = await calendarStore.BookEvent(eventparam)
      load()
      return ris
    }

    function saveBookEvent(myevent: IEvents) {

      if (true) {
        // close the dialog
        bookEventpage.value.show = false

        // bookEventForm.value.booked = bookEventForm.value.bookedcheck

        const data: IBookedEvent = {
          userId: userStore.my._id,
          username: userStore.my.username,
          id_bookedevent: myrec.value._id,
          tableType: shared_consts.TABLETYPE.MyBachecas,
          numpeople: bookEventForm.value.numpeople,
          numpeopleLunch: bookEventForm.value.numpeopleLunch,
          numpeopleDinner: bookEventForm.value.numpeopleDinner,
          numpeopleDinnerShared: bookEventForm.value.numpeopleDinnerShared,
          infoevent: tools.gettextevent(myrec.value),
          msgbooking: bookEventForm.value.msgbooking,
          booked: bookEventForm.value.booked,
          datebooked: tools.getDateNow(),
          modified: (bookEventpage.value.state !== EState.Creating)
        }

        BookEvent(data).then((ris) => {
          if (ris)
            tools.showPositiveNotif($q, t('cal.booked') + ' ' + t('cal.event') + ' "' + myrec.value.descr + '"')
          else
            tools.showNegativeNotif($q, t('cal.booked_error'))
        })

        contextDay.value = null
      }
    }

    function executefunc(mythisq: any, table: string, func: number, par: IParamDialog) {

      if (func === lists.MenuAction.DELETE) {
        // console.log('param1', par.param1)
        calendarStore.CancelBookingEvent({
          ideventbook: par.param1,
          notify: par.param2 === true ? '1' : '0',
        }).then((ris: any) => {
          if (ris) {
            tools.showPositiveNotif(mythisq, t('cal.canceledbooking') + ' "' + par.param3 + '"')
            if (bookEventpage.value)
              bookEventpage.value.show = false
          } else {
            tools.showNegativeNotif(mythisq, t('cal.cancelederrorbooking'))
          }
        })
      }
    }

    function CancelBookingEvent(mythisq: any, bookeventid: string, notify: boolean, mythis?: any) {

      const mytitle = translate('cal.titlebooking')
      const mytext = translate('cal.cancelbooking') + ' ' + tools.gettextevent(myrec.value) + '?'
      const ok = translate('dialog.yes')
      const funcok = lists.MenuAction.DELETE
      const table = ''
      const funccancel = 0
      const par = {
        param1: bookeventid,
        param2: notify,
        param3: myrec.value.descr,
      }

      // console.log('CancelBookingEvent ', myrec.value)
      return $q.dialog({
        message: mytext,
        html: true,
        ok: {
          label: ok,
          push: true,
        },
        title: mytitle,
        cancel: true,
        persistent: false,
      }).onOk(() => {
        // console.log('OK')
        executefunc($q, table, funcok, par)
        return true
      }).onCancel(() => {
        // console.log('CANCEL')
        executefunc($q, table, funccancel, par)
        return false
      })
    }

    function sendMsg(info: boolean) {
      askInfopage.value.show = false

      const data: IMessage = {
        source: {
          event_id: myrec.value._id,
          infoevent: tools.gettextevent(myrec.value)
        },
        origin: userStore.my.username,
        dest: myrec.value.username,
        message: info ? askInfoForm.value.message : bookEventForm.value.msgbooking
      }

      messageStore.SendMsgEvent(data).then((ris) => {
        contextDay.value = null
        if (ris)
          tools.showPositiveNotif($q, t('cal.sendmsg_sent'))
        else
          tools.showNegativeNotif($q, t('cal.sendmsg_error'))
      })

    }

    function isAlreadyBooked() {
      // const calendarStore = useCalendarStore()
      // return calendarStore.findEventBooked(myrec.value._id, true)
      arrbookings.value.find((recbook: IBookedEvent) => recbook.userId === userStore.my._id && recbook.booked)
    }

    function extraparams() {

      return {
        lookupPipeline1: {
          lk_tab: 'users',
          lk_LF: 'userId',
          lk_FF: '_id',
          lk_as: 'user',
          lk_proj: {
            name: 1,
            surname: 1,
            username: 1,
            verified_by_aportador: 1,
            'profile.handshake': 1,
            'profile.img': 1,
            'profile.mygroups': 1,
            'profile.qualifica': 1,
            'profile.resid_province': 1,
            'profile.resid_card': 1,
            'mycities.reg': 1,
          },
        },
        /*
              {
                $lookup: {
                  from: "users",
                  let: { searchId: { $toObjectId: "$userId" } },
                  pipeline: [
                    {
                      $match: {
                        $expr: {
                          $and: [
                            { $eq: ["$_id", "$$searchId"] },
                          ],
                        },
                      },
                    },
                    {
                      $project: {
                        name: 1,
                        surname: 1,
                        username: 1,
                        "profile.handshake": 1,
                        "profile.img": 1,
                        "profile.mygroups": 1,
                        "profile.qualifica": 1,
                        "profile.resid_province": 1,
                        "mycities.reg": 1,
                      },
                    }
                  ],
                  as: "user",
                },
              },
              {
                $replaceRoot: {
                  newRoot: {
                    $mergeObjects: [
                      {
                        $arrayElemAt: [
                          "$mycities",
                          0,
                        ],
                      },
                      {
                        $arrayElemAt: [
                          "$user",
                          0,
                        ],
                      },
                      "$$ROOT",
                    ],
                  },
                },
              },

                lookup1: {
                lk_tab: 'provinces',
                  lk_LF: 'profile.resid_province',
                    lk_FF: 'prov',
                      lk_as: 'mycities',
                        lk_proj: {
                  username: 1,
                    name: 1,
                      surname: 1,
                        'profile.handshake': 1,
                          'profile.img': 1,
                            'profile.mygroups': 1,
                              'profile.qualifica': 1,
                                'profile.resid_province': 1,
                                  'mycities.reg': 1,
                  }
              },
        */

      }
    }

    async function condividi() {
      const mystr = "❇️ Ecco l'annuncio da condividere !\nPuoi copiarlo oppure inoltrarlo a chi vuoi.\n\nE\' utile pubblicarlo anche nel gruppo Telegram RISO territoriale o in <a href=\'https://t.me/riso_gruppo/1911\'>RISO RIevoluzione SOlidale</a> (Topic \'Annunci RISO\') "
      await tools.sendMsgTelegramCmd($q, t, shared_consts.MsgTeleg.SHARE_TEXT, false, mystr)

      tools.copyToClip($q, getlinkpage(), true)
      await tools.sendMsgAnnuncioToTelegramCmd($q, t, props.table, myrec.value._id)

      // Apri telegram sulla chat BOT RISO
      tools.openUrl(tools.getLinkBotTelegram('', ''))
    }

    const expandDialog = () => {
      isSmall.value = false; // Cambia lo stato a 'non piccolo'
    };

    function toggleShowScheda() {
      // updateCard()
      isSmall.value = !isSmall.value

    }

    function showInMap(rec: any) {
      // close dialo
      emit('showInMap', rec)
    }


    onMounted(mounted)

    return {
      expandDialog,
      profile,
      tools,
      costanti,
      myrec,
      shared_consts,
      globalStore,
      site: globalStore.site,
      showPic,
      userStore,
      t,
      fieldsTable,
      colCitys,
      toolsext,
      col,
      condividipag,
      showBadge,
      getlinkpage,
      calendarStore,
      getSectorByRec,
      getRecGoodSkillByRec,
      usersList,
      bookedList,
      clicca,
      naviga,
      getTypeHosps,
      bookEventpage,
      hasModifiedBooking,
      checkseinviaMsg,
      getTitleBtnBooking,
      askInfoForm,
      EState,
      saveBookEvent,
      EditBookEvent,
      CancelBookingEvent,
      sendMsg,
      askInfopage,
      isAlreadyBooked,
      bookEventForm,
      loading,
      arrfilterand,
      filtercustom,
      searchList,
      filter,
      extraparams,
      condividi,
      getTipodiAttivita,
      isSmall,
      cardStyle,
      cardRef,
      smallHeight,
      toggleShowScheda,
      showInMap,
      ismounted,
      updatePart,
      numpart,
    }
  }
})
