<script lang="ts" setup>
import {useConfigStore} from "@/store";


const emits = defineEmits<{
  success: [password: string]
}>()

const {t} = useI18n()
const configStore = useConfigStore()

const show = ref(false)
const password = ref('')
const keyboardHeight = ref<number>(0)
const showKeyboard = ref<boolean>(false);


function init() {
  password.value = ''
  show.value = true
}

function close() {
  show.value = false
  password.value = ''
}

function handleSubmit() {
  console.log(password.value)
  if (password.value.length === 6) {
    emits('success', password.value)
    close()
  } else {
    uni.showToast({
      title: t('common.please-enter-6-digit-payment-password'),
      icon: 'none',
    })
  }
}

const listener = function (res: any) {
  console.log(res)
  keyboardHeight.value = res.height
}

onMounted(() => {
  // #ifdef APP-PLUS
  uni.onKeyboardHeightChange(listener)
  // #endif
})


onUnmounted(() => {
  // #ifdef APP-PLUS
  uni.offKeyboardHeightChange(listener)
  // #endif
})


defineOptions({
  name: 'PasswordInput',
  styleIsolation: 'shared',
})

defineExpose({
  init,
  close,
})
</script>

<template>
  <wd-popup
      v-model="show"
      custom-class="rounded-t-30rpx !p-[40rpx+20rpx+48rpx]"
      position="bottom"
      safe-area-inset-bottom
  >
    <view
        class="mb-48rpx relative flex justify-center text-center text-34rpx text-primary font-bold"
    >
      <text>{{ t('common.please-enter-your-payment-password') }}</text>
    </view>
    <view class="relative">
      <wd-password-input v-model="password"
                         :focused="showKeyboard"
                         :length="6" custom-class="flex-1 h-50px"/>
      <input
          v-model="password"
          :cursor-spacing="20"
          :maxlength="6"
          class="absolute top-0 left-0 opacity-0 w-ful h-full"
          cursor-color="transparent"
          type="number"
          @blur="showKeyboard = false"
          @focus="showKeyboard = true"
      />
    </view>
    <view class="mt-60rpx">
      <wd-button
          custom-class="!w-full !h-88rpx !m-0 !text-30rpx !font-bold !rounded-20rpx"
          @click="handleSubmit"
      >{{ t('common.confirm') }}
      </wd-button
      >
    </view>
    <view :style="[configStore.isIos?{
      height: keyboardHeight + 'px',
      transition: 'height 0.3s ease-in-out',
      overflow: 'hidden',
    }:{}]" class=""></view>
  </wd-popup>
</template>

<style lang="scss" scoped>
:deep(.wd-password-input) {
  margin: 0;
}

:deep(.wd-password-input__item) {
  background-color: transparent;
}
</style>
