<template>
  <Popup isClose ref="popRef">
    <template #content>
      <view class="apple-pay__box">
        <view id="apple_pay_card"></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 { useAppleInfo } from './hooks'


const popRef = ref(null);

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

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


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

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


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

// 加载完成
const onPaymentReady = (event) => {
  console.log('----- apple payment ready -----', event)
}
// 成功回调
const onPaymentSuccess = (event) => {
  console.log('----- apple payment success -----', event)
  return
  emit('on-success');
}
// 失败回调
const onPaymentError = (event) => {
  console.log('----- apple 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');

.apple-pay__box {
  width: 100%;
  height: 25vh;

  #apple_pay_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>