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

import type { IAccount, ICircuit, IMyGroup, ISendCoin, IUserFields } from '../../model';
import { IOperators, ISpecialField } from '../../model'
import { tools } from '@tools'
import { CSaldo } from '@src/components/CSaldo'
import { useUserStore } from '@store/UserStore'
import { useCircuitStore } from '@store/CircuitStore'
import { useQuasar } from 'quasar'
import { useI18n } from 'vue-i18n'
import { CNumericKeyboard } from '@src/components/CNumericKeyboard'
import { CMyUserOnlyView } from '@src/components/CMyUserOnlyView'
import { CMyGroupOnlyView } from '@src/components/CMyGroupOnlyView'
import { CCheckCircuitsEnabled } from '@src/components/CCheckCircuitsEnabled'
import { costanti } from '@costanti'
import { useRouter } from 'vue-router'
import { shared_consts } from '@src/common/shared_vuejs'

export default defineComponent({
  name: 'CSendCoins',
  emits: ['close', 'showed'],
  props: {
    showprop: {
      type: Boolean,
      default: false,
    },
    circuitname: {
      type: String,
      default: ''
    },
    qtydefault: {
      type: String,
      required: false,
      default: ''
    },
    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,
    },
    sendRIS: {
      type: String,
      required: false,
      default: '',
    },
    causalDest: {
      type: String,
      required: false,
      default: '',
    },
  },
  components: { CSaldo, CMyUserOnlyView, CMyGroupOnlyView, CCheckCircuitsEnabled, CNumericKeyboard },

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

    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 visubanner = ref(true)
    const bothcircuits = ref(<any>[])

    const showProvinceToSelect = ref(false)

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

    const datasaved = ref(<any>null)
    const step = ref(0)
    const sendCoinDialog = ref(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>[])
    const tipoConto = ref(shared_consts.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 === shared_consts.AccountType.CONTO_DI_GRUPPO) {
        if (arrGroupsList.value.length >= 1)
          from_groupname.value = arrGroupsList.value[0].value
      }

      tools.setCookie(tools.COOK_TIPOCONTO, tipoConto.value.toString())

      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)
      showpage.value = newval
    })

    async function aggiorna() {

      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) {
          loading.value = true
          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.personale') + ' ' + from_username.value,
              value: shared_consts.AccountType.USER,
            },
          ]


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

            if (tipoConto.value === shared_consts.AccountType.USER) {
              accountloaded.value = userStore.getAccountByCircuitId(circuitloaded.value._id)
            } else if (tipoConto.value === shared_consts.AccountType.CONTO_DI_GRUPPO) {
              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 === shared_consts.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: shared_consts.AccountType.CONTO_DI_GRUPPO,
                })
            }

            if (tools.iCanSendCoinsSuperUserCircuit(circuitsel.value) && (!props.to_contocom)) {
              arrTypesAccounts.value.push({
                label: t('circuit.contocom'),
                value: shared_consts.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) {
                const valuenorm = ind * numstep.value
                const value = ind * numstep.value
                if (value > remainingCoins.value) {
                  break
                } else {
                  const label = valuenorm.toString()
                  arrayMarkerLabel.value.push({ value, label })
                }
              }
            }
          }
        } finally {
          loading.value = false
        }
      }
    }

    async function mounted() {

      loading.value = true

      arrTypesAccounts.value = [
        {
          label: t('circuit.personale') + ' ' + from_username.value,
          value: shared_consts.AccountType.USER,
        },
      ]

      let salvatoprec = tools.getCookie(tools.COOK_TIPOCONTO, -2, true)

      // ....
      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 {
          const circcookie = tools.getCookie(tools.CIRCUIT_USE, bothcircuits.value[0])
          if (circcookie && bothcircuits.value.findIndex((circ: ICircuit) => circ.name === circcookie) >= 0)
            circuitsel.value = circcookie
        }
        if (bothcircuits.value && bothcircuits.value.find((name: any) => name !== circuitsel.value)) {
          circuitsel.value = bothcircuits.value[0]
        }

        if (props.qtydefault)
          qty.value = props.qtydefault

        if (props.sendRIS) {
          if (props.sendRIS !== '0')
            qty.value = props.sendRIS
        }

        await aggiorna()

        // Se quello scelto c'è ancora sulla lista, allora lo imposto

        if (arrTypesAccounts.value.findIndex((rec: any) => rec.value === salvatoprec) >= 0) {
          tipoConto.value = salvatoprec
        } else {
          tipoConto.value = shared_consts.AccountType.USER
        }

//         tipoConto.value = tools.getCookie(tools.COOK_TIPOCONTO, shared_consts.AccountType.USER, true)

        showpage.value = true

      }

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

        console.log('bothcircuits', bothcircuits.value)

        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]
        }

        await aggiorna()

        showpage.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]
        }

        await aggiorna()

        showpage.value = true
      }

      loading.value = false
      emit('showed')
    }

    function hide() {
      emit('close', true)
      showpage.value = false
    }

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

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


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

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

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


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

    function ifNextCheck(actualstep: number) {

      let fase1ok = false

      if (circuitloaded.value && !!circuitloaded.value._id) {
        fase1ok = !(
          !circuitloaded.value.transactionsEnabled ||
          (tipoConto.value === shared_consts.AccountType.USER &&
            props.to_user &&
            from_username.value === props.to_user.username) ||
          (tipoConto.value ===
            shared_consts.AccountType.CONTO_DI_GRUPPO &&
            !from_groupname.value) ||
          (tipoConto.value ===
            shared_consts.AccountType.CONTO_DI_GRUPPO &&
            props.to_group &&
            from_groupname.value &&
            props.to_group.groupname === from_groupname.value) ||
          (tipoConto.value ===
            shared_consts.AccountType.COMMUNITY_ACCOUNT &&
            !from_contocom.value)
        )
      }

      if (actualstep === 0) {
        return fase1ok
      } else if (actualstep === 1) {
        return fase1ok && checkRisValid()
      } else if (actualstep === 2) {
        return fase1ok && checkRisValid()
      }

    }

    function checkRisValid() {
      return qty.value ? qty.value && getQty() >= 0.01 && accountloaded.value
        && getQty() <= circuitStore.getRemainingCoinsToSend(accountloaded.value) : false
    }

    function getQty(): number {
      let myqty: number | null = null

      try {
        if (qty.value) {
          myqty = parseFloat(String(qty.value))
        }
      } catch (e) {
        return 0
      }

      return myqty ? myqty : 0
    }

    function getTitle(step: number) {

      if (step === 0) {
        return 'Circuito'
      } else if (step === 1) {
        return 'Quantità'
      } else if (step === 2) {
        return 'Causale'
      }
    }
    function getIcon(step: number) {

      if (step === 0) {
        return 'circuit'
      } else if (step === 1) {
        return 'attach_money'
      } else if (step === 2) {
        return 'description'
      }
    }

    function clickAvanti(actualstep: number) {
      if (actualstep === 0) {
        step.value = 1
      } else if (actualstep === 1) {
        step.value = 2
      } else if (actualstep === 2) {
        sendCoin()
      }
    }
    function clickIndietro(actualstep: number) {
      if (actualstep === 1) {
        step.value = 0
      } else if (actualstep === 2) {
        step.value = 1
      } else if (actualstep === 0) {
        hide()
      }
    }


    onMounted(mounted)

    return {
      t,
      tools,
      showpage,
      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,
      showProvinceToSelect,
      shared_consts,
      step,
      ifNextCheck,
      clickIndietro,
      clickAvanti,
      getTitle,
      getIcon,
      sendCoinDialog,
      visubanner,
    }
  },
})
