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 { CSendCoins } from '@/components/CSendCoins'
import { CTitleSec } from '@/components/CTitleSec'
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, IMyGroup } from 'model'
import { shared_consts } from '@/common/shared_vuejs'
import { colmyUserPeople, colmyUserPeopleSaldi, colmyUserCircuit, colmyMovement, colmyMovementTable, colmyUserGroup } from '@store/Modules/fieldsTable'
import { useNotifStore } from '@store/NotifStore'
import { useCircuitStore } from '@store/CircuitStore'


export default defineComponent({
  name: 'mycircuit',
  components: {
    CProfile, CTitleBanner, CMyFieldRec, CSkill, CTitleSec, CDateTime, CMyFriends,
    CGridTableRec, CMyUser, CCheckIfIsLogged, CCurrencyValue, CSaldo, CNotifAtTop,
    CSendCoins,
  },
  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 groupsListAdmin = ref(<IMyGroup[]>[])
    const groupnameSel = ref('')

    const showsendCoinTo = ref(false)
    const showrules = 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([] as any[])
    const showPic = ref(false)

    const circuit = ref({} as ICircuit | null)
    const account = computed(() => circuit.value ? userStore.getAccountByCircuitId(circuit.value._id) : null)
    const mystatus = ref(0 as number)
    const users_in_circuit = ref([] as 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 tabcircuit = ref('info')
    const tabmembers = ref('all')
    const showsaldi = ref(false)
    const tab = ref('membri')

    const arrfilterand: any = ref([])
    const filterextra: any = ref([])
    const filterextra_group: any = ref([])
    const filterextra2: any = ref([])
    const filtercustom: any = ref([])
    const filtercustom_rich: any = ref([])
    const searchList = ref([] as ISearchList[])

    const cities = ref([] as ICity[])


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

    watch(() => tabcircuit.value, (to: any, from: any) => {
      tools.setCookie(tools.COOK_TAB_CIRCUIT + path.value, tabcircuit.value)
    })

    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) {
            let addquerysingle = [

            ];

            filterextra.value = [{
              $match: {
                idapp: process.env.APP_ID,
                'profile.mycircuits': {
                  $elemMatch: { circuitname: { $eq: circuit.value.name } },
                },
              },
            },

            {
              $lookup: {
                from: 'circuits',
                as: 'circuit',
                let: { circuitname: circuit.value.name, idapp: '$idapp' },
                pipeline: [
                  {
                    $match:
                    {
                      $expr:
                      {
                        $and:
                          [
                            { $eq: ['$name', '$$circuitname'] },
                            { $eq: ['$idapp', '$$idapp'] },

                          ],
                      },
                    },
                  },
                ],
              },

            },
            { $unwind: '$circuit' },
            {
              $project: {
                username: 1,
                name: 1,
                surname: 1,
                date_reg: 1,
                profile: 1, idapp: 1, 'circuit.name': 1, 'circuit._id': 1
              }

            },

            {
              $lookup: {
                from: 'accounts',
                as: 'account',
                let: { username: '$username', idapp: '$idapp', circuitId: '$circuit._id' },
                pipeline: [
                  {
                    $match:
                    {
                      $expr:
                      {
                        $and:
                          [
                            { $eq: ['$$username', '$username'] },
                            { $eq: ['$$idapp', '$idapp'] },
                            { $eq: ['$$circuitId', '$circuitId'] },
                          ],
                      },
                    },
                  },
                ],
              },
            },
            { $unwind: '$account' },
            ]

            filterextra_group.value = [{
              $match: {
                idapp: process.env.APP_ID,
                'mycircuits': {
                  $elemMatch: { circuitname: { $eq: circuit.value.name } },
                },
              },
            },

            {
              $lookup: {
                from: 'circuits',
                as: 'circuit',
                let: { circuitname: circuit.value.name, idapp: '$idapp' },
                pipeline: [
                  {
                    $match:
                    {
                      $expr:
                      {
                        $and:
                          [
                            { $eq: ['$name', '$$circuitname'] },
                            { $eq: ['$idapp', '$$idapp'] },

                          ],
                      },
                    },
                  },
                ],
              },

            },
            { $unwind: '$circuit' },
            {
              $project: {
                groupname: 1,
                title: 1,
                descr: 1,
                photos: 1,
                surname: 1,
                admins: 1,
                idapp: 1,
                'circuit.name': 1, 'circuit._id': 1
              }
            },
            {
              $lookup: {
                from: 'accounts',
                as: 'account',
                let: { groupname: '$groupname', idapp: '$idapp', circuitId: '$circuit._id' },
                pipeline: [
                  {
                    $match:
                    {
                      $expr:
                      {
                        $and:
                          [
                            { $eq: ['$groupname', '$$groupname'] },
                            { $eq: ['$idapp', '$$idapp'] },
                            { $eq: ['$circuitId', '$$circuitId'] },

                          ],
                      },
                    },
                  },
                ],
              },

            },
            {
              $unwind: '$account',
            },
            {
              $match: { 'account.groupname': { $exists: true, $ne: '' } }
            },
            ]
          }
          arrfilterand.value = []
          filtercustom_rich.value = []

          if (userStore.my.username && circuit.value)
            groupsListAdmin.value = userStore.GroupsListWhereIAmAdmin()

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

      }
      loading.value = false
    }

    async function mounted() {
      tabcircuit.value = tools.getCookie(tools.COOK_TAB_CIRCUIT + path.value, 'info')


      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() {
      const lk_tab = 'users'
      const lk_LF = 'userId'
      const lk_FF = '_id'
      const lk_as = 'user'
      const af_objId_tab = 'myId'

      return {
        lookup1: {
          lk_tab,
          lk_LF,
          lk_FF,
          lk_as,
          af_objId_tab,
          lk_proj: {
            username: 1,
            name: 1,
            surname: 1,
            'profile.img': 1,
            'profile.mycircuits': 1,
            'profile.qualifica': 1,
            'profile.resid_province': 1,
            'account._id': 1,
            'account.saldo': 1,
            'account.fidoConcesso': 1,
            'account.qta_maxConcessa': 1,
            'account.totTransato': 1,
            reported: 1,
            date_report: 1,
            username_who_report: 1,
          }
        },
      }
    }

    function extraparams_groups() {
      const lk_tab = 'mygroups'
      const lk_LF = 'userId'
      const lk_FF = '_id'
      const lk_as = 'group'
      const af_objId_tab = 'myId'

      return {
        lookup1: {
          lk_tab,
          lk_LF,
          lk_FF,
          lk_as,
          af_objId_tab,
          lk_proj: {
            groupname: 1,
            title: 1,
            descr: 1,
            photos: 1,
          }
        },
      }
    }

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

    function extraparams_rich_groups() {
      return {
        querytype: shared_consts.QUERYTYPE_GROUP_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 extraparams_refused_groups() {
      return {
        querytype: shared_consts.QUERYTYPE_REFUSED_GROUP_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(', ') : ''
    }

    function getRegulation(reg: string) {
      let strreg = reg + ''
      if (!reg) {
        const mystringa = t('circuit.regolamento', {nomecircuito: circuit.value!.name})
        return mystringa
      } else {
        return reg
      }

    }

    onMounted(mounted)

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

      filtroutente,
      showPic,
      userStore,
      t,
      animation,
      arrfilterand,
      filterextra,
      filterextra2,
      filtercustom,
      filtercustom_rich,
      searchList,
      colmyMovement,
      colmyMovementTable,
      colmyUserPeople,
      colmyUserPeopleSaldi,
      colmyUserCircuit,
      colmyUserGroup,
      extraparams,
      extraparams_rich,
      extraparams_refused,
      extraparams_movs,
      tab,
      tabcircuit,
      tabmembers,
      numUsers,
      numAdmins,
      listaAdmins,
      users_in_circuit,
      loading,
      mystatus,
      cities,
      path,
      requestToEnterCircuit,
      circuitStore,
      qtarem,
      saldo,
      showonlymine,
      tabellare,
      showsaldi,
      extraparams_groups,
      filterextra_group,
      groupsListAdmin,
      groupnameSel,
      showsendCoinTo,
      showrules,
      loadCircuit,
      extraparams_rich_groups,
      extraparams_refused_groups,
      getRegulation,
    }
  }
})
