import { CGridTableRec } from '@src/components/CGridTableRec'
import { CMyFriends } from '@src/components/CMyFriends'
import { CMyUser } from '@src/components/CMyUser'
import { CNotifAtTop } from '@src/components/CNotifAtTop'
import { CTitleBanner } from '@src/components/CTitleBanner'
import { CProfile } from '@src/components/CProfile'
import { CCheckIfIsLogged } from '@src/components/CCheckIfIsLogged'
import { CMyFieldRec } from '@src/components/CMyFieldRec'
import { CSkill } from '@src/components/CSkill'
import { CDateTime } from '@src/components/CDateTime'
import { CInfoAccount } from '@src/components/CInfoAccount'
import { CSendCoins } from '@src/components/CSendCoins'
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 { ICircuit, ICity, IFriends, IMyCircuit, IMyGroup, ISearchList } from 'model';
import { IUserFields } from 'model'
import { shared_consts } from '@src/common/shared_vuejs'
import { colmyUserPeople, colmyUserGroup, colmyMovementTable, colmyMovement } from '@store/Modules/fieldsTable'
import { useNotifStore } from '@store/NotifStore'
import { useCircuitStore } from '@src/store/CircuitStore'


export default defineComponent({
  name: 'mygroup',
  components: {
    CProfile, CTitleBanner, CMyFieldRec,
    CInfoAccount, CSkill, CDateTime, CMyFriends, CGridTableRec, CMyUser, CCheckIfIsLogged,
    CNotifAtTop, CSendCoins
  },
  props: {},
  setup() {
    const userStore = useUserStore()
    const notifStore = useNotifStore()
    const circuitStore = useCircuitStore()
    const $route = useRoute()
    const $q = useQuasar()
    const { t } = useI18n()

    const animation = ref(<any>'fade')
    const tabevents = ref('new')

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

    const groupname = computed(() => $route.params?.groupname ? $route.params?.groupname.toString() : '')
    const idnotif = computed(() => $route.query.idnotif ? $route.query.idnotif.toString() : '')

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

    const showsendCoinTo = ref(false)

    const tabcircuit = ref('info')
    const filtro_eventi = ref(<any[]>[])

    const mygrp = ref(<IMyGroup>{})
    const mystatus = ref(<number>0)
    const users_in_group = ref(<IFriends[]>[])

    const tabellare = ref(false)
    const circuitIndex = ref(0)

    const loading = ref(false)

    const tabgrp = ref('info')
    const tabmembers = ref('all')
    const tab = ref('membri')

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

    const cities = ref(<ICity[]>[])

    const circuitslist = ref(<ICircuit[]>[])
    const circuitslistOpt = ref(<any[]>[])

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

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

    async function loadGroup() {
      console.log('loadGroup')
      // Carica il profilo di quest'utente
      if (groupname.value) {
        await userStore.loadGroup(groupname.value, idnotif.value).then(({ data, status }: { data: any, status: number }) => {
          // console.log('data', data)
          circuitslist.value = []
          if (data) {
            mygrp.value = data.mygroup
            cities.value = data.cities
            notifStore.setAsRead(idnotif.value)
            users_in_group.value = data.users_in_group

            if (mygrp.value)
              circuitslist.value = circuitStore.getCircuitsListByGroup(mygrp.value)

            /*if (mygrp.value && tools.iAmAdminGroup(groupname.value)) {
          }*/
            if (circuitslist.value) {
              circuitslistOpt.value = []
              for (let i = 0; i < circuitslist.value.length; i++) {
                circuitslistOpt.value.push({ label: circuitslist.value[i].name, value: i })
                const myc = data.mygroup.mycircuits.find((circ: IMyCircuit) => circ.circuitname === circuitslist.value[i].name)
                if (myc) {
                  circuitslist.value[i].account = myc.account
                }
              }
            }
          } else {
            mygrp.value = null
            users_in_group.value = []
          }

          mystatus.value = status

          loading.value = false
          // filtroutente.value = [{ userId: userStore.my._id }]
        })

      }
    }

    watch(() => groupname.value, (to: any, from: any) => {
      loadGroup()
    })

    async function mounted() {
      loading.value = true
      await loadGroup()

      searchList.value = []
      filtercustom.value = [{ 'profile.mygroups': { $elemMatch: { groupname: { $eq: groupname.value } } } }]

      arrfilterand.value = []
      filtercustom_rich.value = []

      //++TODO: sistemare la filtercustom ... richieste...
    }

    function getImgGrp() {
      if (mygrp.value)
        return userStore.getImgByGroup(mygrp.value)
      else
        return ''
    }

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

    function getLinkGrpTelegram() {

      if (mygrp.value) {
        if (mygrp.value.link_telegram) {
          return (!mygrp.value.link_telegram.startsWith('http') ? 'https://' : '') + mygrp.value.link_telegram
        }
      } else {
        return ''
      }

    }

    function getLinkWebSite() {
      if (!mygrp.value) {
        return ''
      }

      let site = mygrp.value.website!
      if (site) {
        if (!site.startsWith('http')) {
          site = 'https://' + site
        }
      }
      return site
    }
    function extraparams_rich() {
      return {
        querytype: shared_consts.QUERYTYPE_MYGROUP,
        myid: mygrp.value ? mygrp.value._id : '',
      }
    }

    function extraparams_refused() {
      return {
        querytype: shared_consts.QUERYTYPE_REFUSED_USER_GRP,
        myid: mygrp.value ? mygrp.value._id : '',
      }
    }

    function numUsers() {
      return users_in_group.value ? users_in_group.value.length : 0
    }
    function numAdmins() {
      return (mygrp.value && mygrp.value.admins) ? mygrp.value.admins.length : 0
    }
    function listaAdmins() {
      return (mygrp.value && mygrp.value.admins) ? mygrp.value.admins.map((rec) => rec.username).join(', ') : ''
    }


    function getExtraparams_movs_grp(circuit: ICircuit): any {
      return {
        querytype: shared_consts.QUERYTYPE_LIST_MOVEMENTS_GROUPNAME,
        myid: circuit ? circuit._id : '',
        groupname: mygrp.value ? mygrp.value.groupname : '',
      }
    }

    function filtrotables(table: string, quale: string) {
      const out = []
      if (mygrp.value)
        out.push({ groupname: mygrp.value.groupname })

      if (table === shared_consts.TABLES_MYBACHECAS) {
        let mydate = tools.addDays(tools.getDateNow(), -1)
        let mydateend = tools.addDays(mydate, 180)
        mydate = tools.getstrYYMMDDDate(mydate)
        mydateend = tools.getstrYYMMDDDate(mydateend)

        if (quale === 'new') {
          filtro_eventi.value = [{ dateTimeStart: { $gte: mydate, $lte: mydateend } }]
        } else {
          mydate = tools.addDays(tools.getDateNow(), -365)
          mydateend = tools.addDays(tools.getDateNow(), 0)
          mydate = tools.getstrYYMMDDDate(mydate)
          mydateend = tools.getstrYYMMDDDate(mydateend)
          filtro_eventi.value = [{ dateTimeStart: { $gte: mydate, $lte: mydateend } }]
        }

        filtro_eventi.value.forEach((rec: any) => [
          out.push({ ...rec })
        ])

      }

      return out
    }

    function getlinkpage() {
      return tools.getFullCurrentUrl()
    }

    onMounted(mounted)

    return {
      groupname,
      profile,
      tools,
      costanti,
      mygrp,
      shared_consts,
      getImgGrp,
      checkifShow,
      getLinkGrpTelegram,
      getLinkWebSite,
      filtroutente,
      showPic,
      mygrpname,
      userStore,
      t,
      animation,
      arrfilterand,
      filtercustom,
      filtercustom_rich,
      searchList,
      colmyUserPeople,
      colmyUserGroup,
      extraparams_rich,
      extraparams_refused,
      tab,
      tabgrp,
      tabmembers,
      numUsers,
      numAdmins,
      listaAdmins,
      users_in_group,
      loading,
      mystatus,
      cities,
      circuitslist,
      circuitStore,
      getExtraparams_movs_grp,
      tabellare,
      colmyMovementTable,
      colmyMovement,
      tabcircuit,
      circuitIndex,
      circuitslistOpt,
      filtrotables,
      getlinkpage,
      showsendCoinTo,
      mycards,
      tabevents,
    }
  }
})
