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 { CUserNote } from '@src/components/CUserNote'
import { CMyCircuit } from '@src/components/CMyCircuit'
import { CNotifAtTop } from '@src/components/CNotifAtTop'
import { CMyActivities } from '@src/components/CMyActivities'
import { CSendCoins } from '@src/components/CSendCoins'
import { CContactUser } from '@src/components/CContactUser'
import { CTimeAgo } from '@src/components/CTimeAgo'
import { CMyUser } from '@src/components/CMyUser'
import { CUserNonVerif } from '@src/components/CUserNonVerif'
import { CCheckIfIsLogged } from '@src/components/CCheckIfIsLogged'
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 { IMyCircuit, IMyGroup, IUserFields } from 'model';
import { ICircuit, IFriends } 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'


export default defineComponent({
  name: 'myprofile',
  components: {
    CProfile, CTitleBanner, CMyFieldDb, CSkill, CDateTime, CCopyBtn, CUserNonVerif, CMyFieldRec, CMyUser,
    CMyGroup, CLabel, CMyCircuit, CSendCoins, CNotifAtTop,
    CCheckIfIsLogged, CTimeAgo, CContactUser, CMyActivities, CUserNote,
  },
  props: {},
  setup() {
    const userStore = useUserStore()
    const globalStore = useGlobalStore()
    const $route = useRoute()
    const $q = useQuasar()
    const { t } = useI18n()

    const site = ref(globalStore.site)

    const { getRefLink } = MixinUsers()

    const animation = ref('fade')
    const spinner_visible = ref(false)
    const shownote = ref(false)
    const usersList = ref({ show: false, title: '', list: [] })

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

    const sendRIS = computed(() => $route.query.sr ? $route.query.sr : '')
    const causalDest = computed(() => $route.query.cd ? $route.query.cd : '')

    const $router = useRouter()
    const filtroutente = ref(<any[]>[])
    const showPic = ref(false)
    const caricato = ref(false)
    const showsendCoinTo = ref(false)
    const showinghand = ref(false)

    const actualcard = ref('mygoods')
    const mostranota = ref(false)

    const notifStore = useNotifStore()

    const quantiHandShake = computed(() => (userStore.userprofile.profile.handshake ? userStore.userprofile.profile.handshake.length : 0) + ' ' + t('handshake.strettedimano'))
    const handshake_inCommon = computed(() => userStore.getMyHandshakeInCommon(userStore.userprofile))
    const quanteHandShakeInCommon = computed(() => (handshake_inCommon.value ? handshake_inCommon.value.length : 0) + ' ' + t('handshake.incommon'))

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

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

    const tab = ref('')

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

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

    async function loadProfile() {
      console.log('loadProfile...', username.value)
      try {

        caricato.value = false

        if (sendRIS.value)
          spinner_visible.value = true

        // Carica il profilo di quest'utente
        if (username.value) {
          await userStore.loadUserProfile({ username: username.value, idnotif: idnotif.value }).then((ris) => {
            console.log('loadUserProfile = ', ris)
            userStore.userprofile = ris
            if (userStore.userprofile) {
              filtroutente.value = [{ userId: userStore.userprofile._id }]
              notifStore.setAsRead(idnotif.value)


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

              try {
                listcircuitsfiltered.value = userStore.userprofile.profile.mycircuits
              } catch (e) {
                listcircuitsfiltered.value = []
              }

            }
          })

          caricato.value = 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() {
      tab.value = tools.isRisoApp() ? 'attivita' : 'info'
      loadProfile()
    }

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

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

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

    function getLinkWebSite() {
      if (userStore.userprofile) {
        let mysite = userStore.userprofile.profile.website
        if (mysite) {
          if (!mysite.startsWith('http')) {
            mysite = 'https://' + mysite
          }
        }
        return mysite
      } else {
        return ''
      }
    }

    onMounted(mounted)

    function gotoPage(link: string) {
      $router.push(link)
    }

    function getlinkpage() {
      if (userStore.userprofile)
        return self.location.host + '/my/' + userStore.userprofile.username
      else
        return ''
    }

    function showed() {
      spinner_visible.value = false
    }

    function salvaUserProv(userprofile: IUserFields) {
      if (userprofile)
        userStore.userprofile = userprofile
    }

    function saveDaContattare() {
      const globalStore = useGlobalStore()
      const { t } = useI18n()

      const mydatatosave = {
        id: userStore.userprofile._id,
        table: 'users',
        fieldsvalue: { 'profile.da_contattare': userStore.userprofile.profile.da_contattare }
      }

      globalStore.saveFieldValue(mydatatosave).then((esito) => {
        if (esito) {
          tools.showPositiveNotif($q, t('db.recupdated'))
        } else {
          tools.showNegativeNotif($q, t('db.recfailed'))
        }
      })

    }
    function savePerm() {
      const globalStore = useGlobalStore()
      const { t } = useI18n()

      const mydatatosave = {
        id: userStore.userprofile._id,
        table: 'users',
        fieldsvalue: { 'perm': userStore.userprofile.perm }
      }

      globalStore.saveFieldValue(mydatatosave).then((esito) => {
        if (esito) {
          tools.showPositiveNotif($q, t('db.recupdated'))
        } else {
          tools.showNegativeNotif($q, t('db.recfailed'))
        }
      })

    }

    return {
      username,
      getlinkpage,
      profile,
      tools,
      toolsext,
      costanti,
      shared_consts,
      getImgUser,
      checkifShow,
      filtroutente,
      showPic,
      myusername,
      userStore,
      t,
      static_data,
      animation,
      isMyRecord,
      getRefLink,
      fieldsTable,
      mycards,
      actualcard,
      caricato,
      listgroupsfiltered,
      idnotif,
      showsendCoinTo,
      site,
      listcircuitsfiltered,
      isDebugOn,
      showinghand,
      quantiHandShake,
      quanteHandShakeInCommon,
      usersList,
      handshake_inCommon,
      globalStore,
      getLinkWebSite,
      gotoPage,
      sendRIS,
      causalDest,
      spinner_visible,
      showed,
      tab,
      shownote,
      mostranota,
      salvaUserProv,
      saveDaContattare,
      savePerm,
    }
  }
})
