import { computed, defineComponent, onMounted, PropType, ref, watch } from 'vue'

import { IAccount, ICircuit, IMyGroup, IOperators, ISendCoin, ISpecialField, IUserFields } from '../../model'
import { tools } from '@store/Modules/tools'
import { CSaldo } from '@/components/CSaldo'
import { useUserStore } from '@store/UserStore'
import { useCircuitStore } from '@store/CircuitStore'
import { useQuasar } from 'quasar'
import { useI18n } from '@/boot/i18n'
import { CMyUserOnlyView } from '@/components/CMyUserOnlyView'
import { CMyGroupOnlyView } from '@/components/CMyGroupOnlyView'
import { costanti } from '@costanti'

export default defineComponent({
  name: 'CSendCoins',
  emits: ['close'],
  props: {
    showprop: {
      type: Boolean,
      default: false,
    },
    circuitname: {
      type: String,
      default: ''
    },
    qtydefault: {
      type: String,
      required: false,
      default: '1'
    },
    to_user: {
      type: Object as PropType<IUserFields>,
      required: false,
      default: null
    },
    to_group: {
      type: Object as PropType<IMyGroup>,
      required: false,
      default: null,
    },
    to_contocom: {
      type: String,
      required: false,
      default: '',
    },
    from_group: {
      type: Object as PropType<IMyGroup>,
      required: false,
      default: null,
    },
  },
  components: { CSaldo, CMyUserOnlyView, CMyGroupOnlyView },

  setup(props, { emit }) {
    const $q = useQuasar()
    const { t } = useI18n()
    const show = ref(false)
    const userStore = useUserStore()
    const circuitStore = useCircuitStore()

    const from_username = ref(userStore.my.username)
    const from_groupname = ref('')
    const from_contocom = ref('')
    const circuitsel = ref('')
    const qty = ref(<string | number>'')
    const causal = ref('')
    const loading = ref(false)
    const bothcircuits = ref(<any>[])

    const groupSel = ref(<IMyGroup | null | undefined>null)

    const datasaved = ref(<any>null)

    const circuittoload = ref(<ICircuit | undefined>undefined)
    const circuitloaded = ref(<ICircuit>{})
    const circuitdest = ref(<ICircuit | undefined>undefined)
    const accountloaded = ref(<IAccount | undefined | null>undefined)
    const accountdest = ref(<IAccount | undefined>undefined)
    const remainingCoins = ref(0)
    const maxsendable = ref(0)
    const numstep = ref(0)
    const arrTypesAccounts = ref(<any>[
      {
        label: t('circuit.user'),
        value: costanti.AccountType.USER,
      },
    ])
    const tipoConto = ref(costanti.AccountType.USER)

    const priceLabel = computed(() => circuitloaded.value ? `${qty.value} ` + circuitloaded.value.symbol : '')
    const arrayMarkerLabel = ref(<any>[])

    const qtyRef = ref(<any>null)
    const causalRef = ref(<any>null)

    const groupsListAdmin = ref(<IMyGroup[]>[])

    const arrGroupsList = ref(<any[]>[])

    watch(() => circuitsel.value, (newval, oldval) => {
      tools.setCookie(tools.CIRCUIT_USE, newval)
      aggiorna()
    })

    watch(() => tipoConto.value, (newval, oldval) => {

      if (tipoConto.value === costanti.AccountType.COLLECTIVE_ACCOUNT) {
        if (arrGroupsList.value.length >= 1)
          from_groupname.value = arrGroupsList.value[0].value
      }

      aggiorna()
    })

    watch(() => from_groupname.value, (newval, oldval) => {
      aggiorna()
    })

    watch(() => from_username.value, (newval, oldval) => {
      aggiorna()
    })

    watch(() => props.showprop, (newval, oldval) => {
      console.log('props.showprop', props.showprop, newval)
      show.value = newval
    })

    async function aggiorna() {
      loading.value = true
      groupSel.value = null
      from_contocom.value = ''
      accountloaded.value = null

      if (!circuittoload.value || (circuittoload.value && circuittoload.value.name !== circuitsel.value)) {
        circuittoload.value = circuitStore.listcircuits.find((rec: ICircuit) => rec.name === circuitsel.value)

        if (circuittoload.value) {
          await userStore.loadCircuit(circuittoload.value.path, '').then(({ data, status }: { data: any, status: number }) => {
            datasaved.value = data
          })
        }
      }

      if (datasaved.value) {
        try {
          arrTypesAccounts.value = [
            {
              label: t('circuit.user'),
              value: costanti.AccountType.USER,
            },
          ]


          if (!!datasaved.value.circuit) {
            circuitloaded.value = datasaved.value.circuit

            if (tipoConto.value === costanti.AccountType.USER) {
              accountloaded.value = userStore.getAccountByCircuitId(circuitloaded.value._id)
            } else if (tipoConto.value === costanti.AccountType.COLLECTIVE_ACCOUNT) {
              groupSel.value = userStore.my.profile.manage_mygroups.find((group: IMyGroup) => from_groupname.value === group.groupname)

              accountloaded.value = groupSel.value ? groupSel.value.account : null
            } else if (tipoConto.value === costanti.AccountType.COMMUNITY_ACCOUNT) {
              from_contocom.value = circuitloaded.value.path
              accountloaded.value = circuitloaded.value ? circuitloaded.value.account : null
            }

            groupsListAdmin.value = userStore.GroupsListWhereIAmAdminInTheCircuit(circuitloaded.value.name)
            console.log('groupsListAdmin.value', groupsListAdmin.value)

            arrGroupsList.value = []

            if (groupsListAdmin.value) {
              for (const group of groupsListAdmin.value) {
                let aggiungi = true

                if (props.to_group && props.to_group.groupname === group.groupname)
                  aggiungi = false

                if (aggiungi)
                  arrGroupsList.value.push({ label: group.groupname, value: group.groupname });
              }
            }

            if (arrGroupsList.value.length > 0) {
              arrTypesAccounts.value.push(
                {
                  label: t('circuit.conticollettivi'),
                  value: costanti.AccountType.COLLECTIVE_ACCOUNT,
                })
            }

            if (tools.iCanSendCoinsSuperUserCircuit(circuitsel.value) && (!props.to_contocom)) {
              arrTypesAccounts.value.push({
                label: t('circuit.contocom'),
                value: costanti.AccountType.COMMUNITY_ACCOUNT,
              })
            }

            // if (tools.iAmAdminCircuit(circuitloaded.value.name))
            //  arrGroupsList.value.push({ label: circuitloaded.value.name, value: circuitloaded.value.path });

            // accountdest.value = userStore.getAccountByCircuitId(circuitloaded.value._id)
            if (accountloaded.value) {
              remainingCoins.value = circuitStore.getRemainingCoinsToSend(accountloaded.value)
              if (accountloaded.value.saldo > 0) {
                maxsendable.value = accountloaded.value.saldo + accountloaded.value.fidoConcesso
              } else {
                maxsendable.value = accountloaded.value.fidoConcesso
              }

              if (remainingCoins.value < 10) {
                remainingCoins.value = 10
              }

              numstep.value = Math.round(maxsendable.value / 10)
              if (numstep.value < 1) {
                numstep.value = 1
              }

              const quanti = [...Array(20).keys()].map(i => i + 1)
              for (const ind of quanti) {
                let valuenorm = ind * numstep.value
                let value = ind * numstep.value
                if (value > remainingCoins.value) {
                  break
                } else {
                  const label = valuenorm.toString()
                  arrayMarkerLabel.value.push({ value, label })
                }
              }
            }
          }
        } finally {
          loading.value = false
        }
      }
    }

    function mounted() {

      arrTypesAccounts.value = [
        {
          label: t('circuit.user'),
          value: costanti.AccountType.USER,
        },
      ]

      // ....
      if (props.to_user) {
        console.log('user', props.to_user)
        bothcircuits.value = userStore.getMyCircuitsInCommonByUser(props.to_user)

        if (props.circuitname) {
          circuitsel.value = props.circuitname
        } else {
          circuitsel.value = tools.getCookie(tools.CIRCUIT_USE, bothcircuits.value[0])
        }
        if (!userStore.IsMyCircuitByName(circuitsel.value)) {
          circuitsel.value = bothcircuits.value[0]
        }

        qty.value = props.qtydefault

        aggiorna()

        show.value = true
      }

      if (props.to_group) {
        console.log('group', props.to_group)
        bothcircuits.value = userStore.getMyCircuitsInCommonByGroup(props.to_group)

        if (props.circuitname) {
          circuitsel.value = props.circuitname
        } else {
          circuitsel.value = tools.getCookie(tools.CIRCUIT_USE, bothcircuits.value[0])
        }
        if (!userStore.IsMyCircuitByName(circuitsel.value)) {
          circuitsel.value = bothcircuits.value[0]
        }

        aggiorna()

        show.value = true
      }
      if (props.to_contocom) {
        bothcircuits.value = userStore.getMyCircuits()

        console.log('to_contocom', props.to_contocom)
        circuitsel.value = props.circuitname
        if (!userStore.IsMyCircuitByName(circuitsel.value)) {
          circuitsel.value = bothcircuits.value[0]
        }

        aggiorna()

        show.value = true
      }
    }

    function hide() {
      emit('close', true)
    }

    function sendCoin() {
      console.log('sendcoin', qty.value, props.to_group ? props.to_group.groupname : (props.to_user ? props.to_user.username : props.to_contocom))

      let ok = (props.to_user && props.to_user.username) ||
        (props.to_group && props.to_group.groupname) ||
        (props.to_contocom)


      if (ok && qty.value && circuitloaded.value) {
        let myrecsendcoin: ISendCoin = {
          qty: tools.convstrToNum(qty.value),
          dest: '',
          groupdest: '',
          grouporig: '',
          circuitname: circuitsel.value,
          causal: causal.value,
          symbol: circuitloaded.value.symbol,
        }

        myrecsendcoin.groupdest = props.to_group ? props.to_group.groupname : ''
        myrecsendcoin.contoComDest = props.to_contocom
        myrecsendcoin.grouporig = tipoConto.value === costanti.AccountType.COLLECTIVE_ACCOUNT ? from_groupname.value : ''
        myrecsendcoin.contoComOrig = tipoConto.value === costanti.AccountType.COMMUNITY_ACCOUNT ? from_contocom.value : ''

        myrecsendcoin.dest = props.to_user ? props.to_user.username : ''


        if (myrecsendcoin) {
          tools.sendCoinsByCircuit($q, circuitloaded.value, myrecsendcoin)
            .then((ris: any) => {
              if (ris) {
                show.value = false
              }
            })
        }
      }
    }



    onMounted(mounted)

    return {
      t,
      tools,
      show,
      bothcircuits,
      from_username,
      circuitsel,
      circuitloaded,
      accountloaded,
      accountdest,
      qty,
      hide,
      sendCoin,
      causal,
      priceLabel,
      arrayMarkerLabel,
      remainingCoins,
      qtyRef,
      causalRef,
      maxsendable,
      circuitStore,
      numstep,
      costanti,
      userStore,
      tipoConto,
      arrGroupsList,
      from_groupname,
      from_contocom,
      arrTypesAccounts,
      loading,
    }
  },
})
