import { CGridTableRec } from '@src/components/CGridTableRec'
import { CMyFriends } from '@src/components/CMyFriends'
import { CMyUser } from '@src/components/CMyUser'
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 { CCurrencyValue } from '@src/components/CCurrencyValue'
import { CSaldo } from '@src/components/CSaldo'
import { CSendCoins } from '@src/components/CSendCoins'
import { CUserNonVerif } from '@src/components/CUserNonVerif'
import { CTitleSec } from '@src/components/CTitleSec'
import { CSkill } from '@src/components/CSkill'
import { CFinder } from '@src/components/CFinder'
import { CDateTime } from '@src/components/CDateTime'
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 { CNotifAtTop } from '@src/components/CNotifAtTop'
import { costanti } from '@costanti'
import type { ICity, IFriends, ICircuit, ISearchList, IAccount, IMyGroup } from 'model';
import { IUserFields } from 'model'
import { shared_consts } from '@src/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, CUserNonVerif, CFinder,
  },
  props: {},
  setup() {
    const userStore = useUserStore()
    const globalStore = useGlobalStore()
    const notifStore = useNotifStore()
    const circuitStore = useCircuitStore()
    const $route = useRoute()
    const $q = useQuasar()
    const { t } = useI18n()

    const showwhommov = ref(1)
    const optionsmov = [
      { label: t('movement.onlymymov'), value: 1 },
      { label: t('movement.allmov'), value: 2 },
    ]
    const tabellare = ref(false)
    const groupsListAdmin = ref(<IMyGroup[]>[])
    const groupnameSel = ref(<any>null)

    const showsendCoinTo = ref(false)
    const showrules = ref(false)
    const showMov = 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 circuitpath_loaded = ref('')

    const filtroutente = ref([] as any[])
    const showPic = ref(false)
    const loadSaldo = ref(false)

    const card = ref(<any>{})

    const circuit = ref(<ICircuit | undefined>undefined)
    const account = ref(<IAccount | null>null)
    const mystatus = ref(0 as number)
    const users_in_circuit = ref([] as IFriends[])

    const qtarem = ref(0)
    const saldo = ref(0)
    const saldo_pend = ref(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[])

    const fidoConcesso = ref(<any>0)
    const qtaMax = ref(<any>0)

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

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

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

    watch(() => circuit.value, (to: any, from: any) => {
      if (to) {
        loadAccount()
      }
    })

    function getParamCircuitsToView() {
      return {
        'circuit.name': 1,
        'circuit._id': 1,
      }
    }

    function loadAccount() {
      // console.log('loadAccount')
      account.value = circuit.value ? userStore.getAccountByCircuitId(circuit.value._id) : null
      // console.log('saldo', account.value!.saldo)

      fidoConcesso.value = account.value ? account.value.fidoConcesso : (circuit.value ? circuit.value.fido_scoperto_default : 0)
      qtaMax.value = account.value ? account.value.qta_maxConcessa : (circuit.value ? circuit.value.qta_max_default : 0)
      qtarem.value = account.value ? circuitStore.getRemainingCoinsToSend(account.value) : 0
      saldo.value = account.value ? account.value.saldo : 0
      saldo_pend.value = account.value ? account.value.saldo_pend : 0
    }


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

    async function loadCircuit() {
      console.log(' *** INIZIO loadCircuit')

      if (!loading.value) {
        loading.value = true
        // Carica il profilo di quest'utente
        if (path.value) {
          circuitpath_loaded.value = 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

              if (circuit.value!.circuitoIndipendente) {
                showrules.value = true
              }
            } else {
              circuit.value = null
              users_in_circuit.value = []
            }

            loadAccount()

            mystatus.value = status

            searchList.value = []
            if (circuit.value) {
              const addquerysingle = [

              ];

              filterextra.value = [{
                $match: {
                  idapp: tools.getEnv('VITE_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,
                  verified_by_aportador: 1,
                  name: 1,
                  surname: 1,
                  date_reg: 1,
                  profile: 1,
                  idapp: 1,
                  ...getParamCircuitsToView(),
                }

              },

              {
                $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: tools.getEnv('VITE_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,
                  verified_by_aportador: 1,
                  admins: 1,
                  idapp: 1,
                  ...getParamCircuitsToView(),
                }
              },
              {
                $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
        console.log('    ___ FINE loadCircuit')
      }
    }

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

      loadCircuit()

      if (mycards_annunci.value)
        card.value = mycards_annunci.value[0]

    }

    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,
            verified_by_aportador: 1,
            lang: 1,
            'profile.img': 1,
            'profile.mycircuits': 1,
            'profile.qualifica': 1,
            'profile.resid_province': 1,
            'profile.resid_card': 1,
            'account._id': 1,
            'account.saldo': 1,
            'account.saldo_pend': 1,
            'account.fidoConcesso': 1,
            'account.qta_maxConcessa': 1,
            'account.totTransato': 1,
            'account.totTransato_pend': 1,
            reported: 1,
            date_report: 1,
            username_who_report: 1,
            namecomplete: 1,
            date_reg: 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 (showwhommov.value === 1) {
        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() {
      let quanti = (circuit.value && circuit.value.admins) ? circuit.value.admins.length : 0
      if (quanti === 0)
        quanti = 1

      return quanti
    }

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

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

    }

    async function aggiornaSaldo() {
      loadSaldo.value = true
      await circuitStore.aggiornaSaldo(circuit.value!._id, '');
      loadAccount()
      loadSaldo.value = false
    }


    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,
      showwhommov,
      tabellare,
      showsaldi,
      filterextra_group,
      groupsListAdmin,
      groupnameSel,
      showsendCoinTo,
      showrules,
      loadCircuit,
      extraparams_rich_groups,
      extraparams_refused_groups,
      getRegulation,
      fidoConcesso,
      qtaMax,
      showMov,
      loadAccount,
      aggiornaSaldo,
      loadSaldo,
      optionsmov,
      globalStore,
      saldo_pend,
      mycards_annunci,
      card,
    }
  }
})
