import { CMyFieldDb } from '@src/components/CMyFieldDb'
import { CMyFieldRec } from '@src/components/CMyFieldRec'
import { CTitleBanner } from '@src/components/CTitleBanner'
import { CProfile } from '@src/components/CProfile'
import { CLabel } from '@src/components/CLabel'
import { CCopyBtn } from '@src/components/CCopyBtn'
import { CSkill } from '@src/components/CSkill'
import { CDateTime } from '@src/components/CDateTime'
import { CMyGroup } from '@src/components/CMyGroup'
import { CMyCircuit } from '@src/components/CMyCircuit'
import { CContactUser } from '@src/components/CContactUser'
import { CNotifAtTop } from '@src/components/CNotifAtTop'
import { CTimeAgo } from '@src/components/CTimeAgo'
import { CSendCoins } from '@src/components/CSendCoins'
import { CMyUser } from '@src/components/CMyUser'
import { CCheckIfIsLogged } from '@src/components/CCheckIfIsLogged'
import { CUserNonVerif } from '@src/components/CUserNonVerif'
import { tools } from '@tools'
import { computed, defineComponent, onMounted, ref, watch } from 'vue'
import { useUserStore } from '@store/UserStore'
import { useRoute, useRouter } from 'vue-router'
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, IMyCircuit, IMyGroup, IUserFields } from 'model';
import { IBookmark, ICircuit, IFavorite } from 'model'
import { shared_consts } from '@src/common/shared_vuejs'
import { static_data } from '@src/db/static_data'
import { fieldsTable } from '@store/Modules/fieldsTable'
import { useNotifStore } from '@store/NotifStore'
import MixinUsers from '@src/mixins/mixin-users'
import { useCircuitStore } from '@src/store/CircuitStore'


export default defineComponent({
  name: 'CMyActivities',
  components: {
    CProfile, CTitleBanner, CMyFieldDb, CSkill, CDateTime, CCopyBtn, CUserNonVerif, CMyFieldRec, CMyUser,
    CMyGroup, CLabel, CMyCircuit, CSendCoins, CNotifAtTop, CCheckIfIsLogged,
    CTimeAgo, CContactUser
  },
  props: {
    username_prop: {
      type: String,
      required: true,
      default: '',
    },
    introUser: {
      type: Boolean,
      required: false,
      default: true,
    },

  },
  setup(props) {
    const userStore = useUserStore()
    const globalStore = useGlobalStore()
    const circuitStore = useCircuitStore()
    const $route = useRoute()
    const $q = useQuasar()
    const { t } = useI18n()

    const site = ref(globalStore.site)

    const { getRefLink } = MixinUsers()

    const animation = ref('fade')
    const mytab = ref('my')

    // const username = computed(() => $route.params.username ? $route.params.username.toString() : userStore.my.username)
    const username = ref('')
    const idnotif = computed(() => $route.query.idnotif ? $route.query.idnotif.toString() : '')

    const filtroutente = ref(<any[]>[])
    const filtro_eventi = ref(<any[]>[])
    const showPic = ref(false)
    const caricato = ref(false)

    const myuser = ref(<IUserFields | null>null)

    const actualcard = ref('mygoods')
    const allcirc = ref(<any>[])

    const notifStore = useNotifStore()

    const mycards = computed(() => {
      return costanti.MAINCARDS.filter((rec: any) => rec.table && rec.showinprofile)
    })
    const optionsMainCards = ref({})

    const listgroupsfiltered = ref(<IMyGroup[]>[])
    const listcircuitsfiltered = ref(<IMyCircuit[]>[])


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

    function myusername() {
      return userStore.my.username
    }

    async function loadProfile() {
      console.log('loadUserActivities...', username.value)
      try {
        const today = new Date();
        today.setHours(0, 0, 0, 0);


        // Carica il profilo di quest'utente
        if (username.value) {
          await userStore.loadUserActivities({ username: username.value, idnotif: idnotif.value }).then((ris) => {
            // console.log('loadUserActivities = ', ris)
            myuser.value = ris
            if (myuser.value) {
              // filtro_eventi.value = [{ userId: myuser.value._id }, { dateTimeStart: { $gte: today } }]
              let mydate = tools.addDays(tools.getDateNow(), -1)
              const mydateend = tools.addDays(mydate, 180)
              mydate = tools.getstrYYMMDDDate(mydate)
              filtro_eventi.value = [{ userId: myuser.value._id }, { dateTimeStart: { $gte: mydate, $lte: mydateend } }]
              filtroutente.value = [{ userId: myuser.value._id }]
              notifStore.setAsRead(idnotif.value)

              try {
                listgroupsfiltered.value = globalStore.mygroups.filter((grp: IMyGroup) => myuser.value!.profile.mygroups.findIndex((rec: IMyGroup) => rec.groupname === grp.groupname) >= 0)
              } catch (e) {
                listgroupsfiltered.value = []
              }

              try {
                allcirc.value = myuser.value.profile.mycircuits
              } catch (e) {
                allcirc.value = []
              }

              const circnaz = circuitStore.getCircuitoNazionale(allcirc.value)

              if (allcirc.value.length > 0) {
                listcircuitsfiltered.value = allcirc.value.slice(0, 5)
                if (circnaz) {
                  if (listcircuitsfiltered.value.findIndex((circ: IMyCircuit) => circ._id === circnaz._id) < 0) {
                    // includi anche il circuito nazionale
                    listcircuitsfiltered.value.unshift(circnaz)
                  }
                }
              } else {
                listcircuitsfiltered.value = allcirc.value
              }

            }
          })

        }
        caricato.value = true

        optionsMainCards.value = tools.getoptionsMainCards(true)
      } catch (e) {
        console.error('ERR loadProfile', e)
      }
    }

    watch(() => username.value, (to: any, from: any) => {
      loadProfile()
    })

    watch(() => actualcard.value, (to: any, from: any) => {
      loadProfile()
    })

    function mounted() {
      username.value = props.username_prop || userStore.my.username
      loadProfile()
    }

    function getImgUser() {
      if (myuser.value)
        return userStore.getImgByProfile(myuser.value)
      else
        return ''
    }

    function checkifShow(col: string) {
      //++Todo: checkifShow Permessi !
      return true
    }

    function getLinkWebSite() {
      if (myuser.value) {
        let site = myuser.value.profile.website!
        if (site) {
          if (!site.startsWith('http')) {
            site = 'https://' + site
          }
        }
        return site
      } else {
        return ''
      }
    }

    function isMyRecord(username: string) {
      return username === userStore.my.username
    }

    function getlinkpage() {
      if (myuser.value)
        return self.location.host + '/attivita/' + myuser.value.username
      else
        return ''
    }

    function filtrofavorite(table: string) {
      const tab = tools.getNumTabByTable(table)
      if (myuser.value && myuser.value.profile.reaction) {
        const arrfav = myuser.value.profile.reaction.filter((rec: IReaction) => rec.tab === tab && (rec.fav! === true))
        if (arrfav)
          return myuser.value.profile.reaction ? [{ _id: { $in: arrfav.map((rec: any) => rec.idrec) } }] : []
      }
      return []
    }
    function filtrobookmark(table: string) {
      const tab = tools.getNumTabByTable(table)
      if (myuser.value && myuser.value.profile.reaction) {
        const arrfav = myuser.value.profile.reaction.filter((rec: IReaction) => rec.tab === tab && rec.book === true);
        if (arrfav)
          return myuser.value.profile.reaction ? [{ _id: { $in: arrfav.map((rec: any) => rec.idrec) } }] : []
      }
      return []
    }

    onMounted(mounted)

    return {
      username,
      profile,
      tools,
      costanti,
      myuser,
      shared_consts,
      getImgUser,
      checkifShow,
      getLinkWebSite,
      filtroutente,
      filtro_eventi,
      filtrofavorite,
      filtrobookmark,
      showPic,
      myusername,
      userStore,
      t,
      static_data,
      animation,
      isMyRecord,
      getRefLink,
      fieldsTable,
      mycards,
      actualcard,
      caricato,
      listgroupsfiltered,
      idnotif,
      site,
      listcircuitsfiltered,
      optionsMainCards,
      getlinkpage,
      mytab,
    }
  }
})
