<script setup lang='ts'>
import { wechatPay, wechatPayRequest, wechatPayQuery, wechatPayCancel } from '@/services/user'
import { ref } from 'vue'
const props = defineProps({
  record: {
    type: Object,
    default: () => ({})
  }
})
const visible = ref(false)
function handleOpen() {
  visible.value = true
}
async function getPayStatus(outTradeNo: string) {
  const res = await wechatPayQuery({
    outTradeNo
  })
  if (res.code !== 1000) {
    getPayStatus(outTradeNo)
  }
}

const handlePay = async () => {
  console.log(props.record)
  try {
    const { prepayId, outTradeNo } = await wechatPay({
      subjectId: props.record.subjectId,
    })
    const { signature,timestamp,nonceStr } = await wechatPayRequest({
      prepayId, outTradeNo
    })
    console.log(signature)
    uni.requestPayment({
      provider: "wxpay",
      timeStamp: timestamp,
      nonceStr: nonceStr,
      package: "prepay_id="+prepayId,
      paySign: signature,
      signType: "RSA",
      success: (res) => {
        console.log('res: ', res)
        uni.showToast({
          title: "支付成功",
          icon: 'success'
        });
        // 支付成功后，查询支付结果
        getPayStatus(outTradeNo)
      },
      fail: (err) => {
        console.error("err", err);
        uni.hideLoading();
        // 支付失败后，取消订单
        wechatPayCancel({
          outTradeNo
        }).then(res => {
          if (res.code === 200) {
            uni.showToast({
              title: "订单已取消",
              icon: 'success'
            });
          }
        })
      }
    });
  } catch (err: any) {
    uni.showToast({
      title: err.message,
      icon: 'error'
    });
  }

}
</script>
<template>
  <view class="absolute top-0 left-0 w-full h-full flex items-center justify-center bg1" @tap.stop="handleOpen">
    <cl-image src="https://oss.xiaoxiongcode.com/static/home/lock.png" mode="widthFix" width="30%" height="auto" />
  </view>
  <cl-popup v-model="visible" showClose :size="400" :show-header="false" direction="center">
    <view class="p-[40px] ">
      <cl-text class="text-center" color="#000" :size="20"> 小朋友，快叫爸爸妈妈帮忙，解锁更多精彩内容吧！ </cl-text>
      <cl-button class="mt-4" size="large" type="warn" block @tap="handlePay"> 前往购课 </cl-button>
    </view>
  </cl-popup>
</template>
<style lang="scss" scoped>
.bg1 {
  background-color: rgba(255, 255, 255, 0.5);
}
</style>
