<template>
  <Popup isClose ref="popRef">
    <template #content>
      <view class="payment-card__box">
        <view id="google_pay_card"></view>
        <view id="error-info" :style="{ color: 'red' }"></view>
      </view>
    </template>
  </Popup>
  <GlobalLoading :msg="loadingStatus" />
</template>


<script setup>
import { t } from '@/locale';
import { ref, reactive, nextTick } from "vue";
import Popup from '@/components/popup.vue';
import GlobalLoading from '@/components/GlobalLoading'
import { Toast } from "@/utils"
import { useGoogleInfo } from './hooks'

const popRef = ref(null);

// props
const props = defineProps({
  paramsObj: { type: Object }
})
// emits
const emit = defineEmits(['open', 'close', 'success', 'error']);

const loadingStatus = reactive({ show: false });
const { googleInstance, init, unmountCard, fetchCardPaymentInfo } = useGoogleInfo();


// 打开回调
const open = () => {
  emit('open');
  popRef.value && popRef.value.open();
  nextTick(() => {
    fetchCardPaymentInfo(props.paramsObj, bindEventListener);
  })
}

// 关闭回调
const close = () => {
  emit('close')
  unmountCard()
  popRef.value && popRef.value.close()
}


// 事件绑定
function bindEventListener() {
  if (!googleInstance.value) return;
  googleInstance.value.on('success', onPaymentSuccess);
  googleInstance.value.on('error', onPaymentError);
  // googleInstance.value.on('ready', onPaymentReady);
}

// 成功回调
const onPaymentSuccess = (event) => {
  console.log('----- google payment success -----', event)
  emit('success');
}

// 失败回调
const onPaymentError = (event) => {
  console.log('----- google payment error -----', event)
  Toast(event.detail.error.message || event.detail.error || t("pay_fail_msg", {}) || "fail！");
}



defineExpose({
  open,
  close
})

</script>
<style lang="less" scoped>
@import url('@/style.less');

.payment-card__box {
  width: 100%;
  height: 25vh;

  #payment_card {
    display: flex;
    align-items: center;
    padding: 12rpx;
    width: 100%;
    height: 44px;
    border: 1px solid #ccc;
    border-radius: 14rpx;
  }
}

.submit_btn {
  height: 38px;
  padding: 16rpx 30rpx;
  background-color: var(--black);
  color: var(--light);
  .flex_center();
  border-radius: 16rpx;
  .size(24rpx);
}
</style>