<script setup>
import { payment, queryProvisionalOrder } from '@/api/apis'

const selectedPaymentMethod = ref('alipay')
const id = ref(null)
const order = ref({
  productName: '',
  price: null,
})
function handlePayment() {
  if (selectedPaymentMethod.value === 'alipay') {
    payment({ id: id.value, pay_method: selectedPaymentMethod.value }).then((res) => {
      if (res.code === 200) {
        uni.requestPayment({
          provider: 'alipay', // 支付宝
          orderInfo: res.data.prepay_id, // 后台返回的orderInfo
          success: () => {
            handlePaySuccess(res.data.order_id)
          },
          fail: (err) => {
            console.log('支付失败:', err)
          },
        })
      }
    })
  }
}
function handlePaySuccess(orderID) {
  uni.redirectTo({
    url: `/pages/result?id=${orderID}`,
  })
}
onLoad((option) => {
  if (option.id) {
    id.value = option.id
    queryProvisionalOrder(option.id).then((res) => {
      console.log('res', res)
      if (res.code === 200) {
        order.value.productName = res.data.product.product_name
        order.value.price = res.data.product.sell_price
      }
    })
  }
})
</script>

<template>
  <view class="min-h-screen from-blue-200 via-sky-200 to-sky-100 bg-gradient-to-b p-6">
    <view class="card">
      <h1 class="mb-4 text-xl font-bold">
        订单支付
      </h1>
      <view class="my-10 text-center">
        <view class="text-2xl font-bold">
          ¥{{ order.price }}
        </view>
        <view class="text-gray-600">
          {{ order.productName }}
        </view>
      </view>
      <view class="mb-4">
        <label class="mb-2 block text-sm text-gray-600">支付方式</label>
        <wd-radio-group v-model="selectedPaymentMethod" shape="dot" size="large">
          <view class="border-3 border-blue-500 rounded-lg border-solid px-4 py-2">
            <wd-radio value="alipay">
              <view class="flex" items-center>
                <image
                  src="/static/image/alipay_icon.svg"
                  mode="aspectFit"
                  class="mr-1 h-5 w-5"
                /> 支付宝
              </view>
            </wd-radio>
          </view>
        </wd-radio-group>
      </view>
      <button
        class="w-full rounded-xl from-blue-500 via-blue-500 to-blue-400 bg-gradient-to-b px-4 py-2 text-white"
        @click="handlePayment"
      >
        立即支付
      </button>
    </view>
  </view>
</template>

<style scoped>
:deep(.wd-radio){
  margin-top: 0;
}
</style>

<route lang="json">
  {
    "layout": "page",
    "title": "全能查收款"
  }
  </route>
