import { CGridTableRec } from '@/components/CGridTableRec'
import { CMyFriends } from '@/components/CMyFriends'
import { CMyUser } from '@/components/CMyUser'
import { CTitleBanner } from '@/components/CTitleBanner'
import { CProfile } from '@/components/CProfile'
import { CCheckIfIsLogged } from '@/components/CCheckIfIsLogged'
import { CMyFieldRec } from '@/components/CMyFieldRec'
import { CCurrencyValue } from '@/components/CCurrencyValue'
import { CSaldo } from '@/components/CSaldo'
import { CSkill } from '@/components/CSkill'
import { CDateTime } from '@/components/CDateTime'
import { tools } from '@store/Modules/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 '@/boot/i18n'
import { toolsext } from '@store/Modules/toolsext'
import { useQuasar } from 'quasar'
import { CNotifAtTop } from '@src/components/CNotifAtTop'
import { costanti } from '@costanti'
import { ICity, IFriends, ICircuit, ISearchList, IUserFields, IAccount } from 'model'
import { shared_consts } from '@/common/shared_vuejs'
import { colmyUserPeople, colmyUserPeopleSaldi, colmyUserCircuit, colmyMovement, colmyMovementTable } from '@store/Modules/fieldsTable'
import { useNotifStore } from '@store/NotifStore'
import { useCircuitStore } from '@store/CircuitStore'


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

    const showonlymine = ref(true)
    const tabellare = ref(false)

    const animation = ref('fade')

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

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

    const circuit = ref(<ICircuit | null>{})
    const account = computed(() => circuit.value ? userStore.getAccountByCircuitId(circuit.value._id) : null)
    const mystatus = ref(<number>0)
    const users_in_circuit = ref(<IFriends[]>[])

    const qtarem = computed(() => account.value ? circuitStore.getRemainingCoinsToSend(account.value) : 0)
    const saldo = computed(() => account.value ? account.value.saldo : 0)

    const loading = ref(false)
    const requestToEnterCircuit = ref(false)

    const tabgrp = ref('info')
    const tabmembers = ref('all')
    const showsaldi = ref(false)
    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[]>[])

    watch(() => path.value, (to: any, from: any) => {
      loadCircuit()
    })


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

    async function loadCircuit() {
      loading.value = true
      // Carica il profilo di quest'utente
      if (path.value) {
        circuit.value = null
        users_in_circuit.value = []
        await userStore.loadCircuit(path.value, idnotif.value).then(({ data, status }: {data: any, status: number}) => {
          console.log('data', data)
          if (data) {
            notifStore.setAsRead(idnotif.value)
            users_in_circuit.value = data.users_in_circuit
            circuit.value = data.circuit
          } else {
            circuit.value = null
            users_in_circuit.value = []
          }

          mystatus.value = status

          searchList.value = []
          if (circuit.value) {
            filtercustom.value = [
              {
                'profile.mycircuits':
                  {
                    $elemMatch: {
                      circuitname:
                        { $eq: circuit.value.name }
                    }
                  }
              },
            ]
          }
          arrfilterand.value = []
          filtercustom_rich.value = []
          // filtroutente.value = [{ userId: userStore.my._id }]
        })

      }
      loading.value = false
    }

    async function mounted() {
      await loadCircuit()

    }

    function getImgCircuit() {
      if (circuit.value)
        return userStore.getImgByCircuit(circuit.value)
      else
        return ''
    }

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


    function extraparams() {
      let lk_tab = 'users'
      let lk_LF = 'userId'
      let lk_FF = '_id'
      let lk_as = 'user'
      let af_objId_tab = 'myId'

      return {
        lookup1: {
          lk_tab,
          lk_LF,
          lk_FF,
          lk_as,
          af_objId_tab,
          lk_proj: {
            'username': 1,
            'profile.img': 1,
            'profile.mycircuits': 1,
            'profile.qualifica': 1,
            'account.saldo': 1,
            reported: 1,
            date_report: 1,
            username_who_report: 1,
          }
        },
      }
    }

    function extraparams_rich() {
      return {
        querytype: shared_consts.QUERYTYPE_CIRCUIT,
        myid: circuit.value ? circuit.value._id : '',
      }
    }

    const extraparams_movs = (() => {
      if (showonlymine.value) {
        return {
          querytype: shared_consts.QUERYTYPE_LIST_MOVEMENTS,
          myid: circuit.value ? circuit.value._id : '',
          username: userStore.my.username,
        }
      } else {
        return {
          querytype: shared_consts.QUERYTYPE_LIST_ALLMOVEMENTS,
          myid: circuit.value ? circuit.value._id : '',
        }

      }
    })

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

    function numUsers() {
      return users_in_circuit.value ? users_in_circuit.value.length : 0
    }

    function numAdmins() {
      return (circuit.value && circuit.value.admins) ? circuit.value.admins.length : 0
    }

    function listaAdmins() {
      return (circuit.value && circuit.value.admins) ? circuit.value.admins.map((rec) => rec.username).join(', ') : ''
    }

    onMounted(mounted)

    return {
      profile,
      tools,
      costanti,
      circuit,
      account,
      shared_consts,
      getImgCircuit,
      checkifShow,

      filtroutente,
      showPic,
      userStore,
      t,
      animation,
      arrfilterand,
      filtercustom,
      filtercustom_rich,
      searchList,
      colmyMovement,
      colmyMovementTable,
      colmyUserPeople,
      colmyUserPeopleSaldi,
      colmyUserCircuit,
      extraparams,
      extraparams_rich,
      extraparams_refused,
      extraparams_movs,
      tab,
      tabgrp,
      tabmembers,
      numUsers,
      numAdmins,
      listaAdmins,
      users_in_circuit,
      loading,
      mystatus,
      cities,
      path,
      requestToEnterCircuit,
      circuitStore,
      qtarem,
      saldo,
      showonlymine,
      tabellare,
      showsaldi,
    }
  }
})
