import React, { useState } from 'react'
import { View, Text, Button } from '@tarojs/components'
import Taro, { useDidShow, useRouter } from '@tarojs/taro'
import { delay } from '@/utils'
import orderService from '@/services/orderService'
import detailService, { GameDetail } from '@/services/detailService'
import { withAuth } from '@/components'

const OrderCheck = () => {
  const { params } = useRouter()
  const { id, gameId } = params
  const [detail ,setDetail] = useState<GameDetail | {}>({})

  useDidShow(async () => {
    const res = await detailService.getDetail(Number(gameId))
    console.log(res)
    if (res.code === 0) {
      setDetail(res.data)
    }
  })

  //TODO: get order msg from id
  const handlePay = async () => {
    Taro.showLoading({
      title: '支付中...',
      mask: true
    })
    const res = await orderService.createOrder(Number(gameId))
    if (res.code === 0) {
      const { payment_required, payment_params } = res.data
      if (payment_required) {
        const { timeStamp, nonceStr, package: package_, signType, paySign } = payment_params
        await Taro.requestPayment({
          timeStamp,
          nonceStr,
          package: package_,
          signType,
          paySign,
          success: async () => {
            Taro.hideLoading()
            Taro.showToast({
              title: '支付成功',
              icon: 'success'
            })
            await delay(1000)
            Taro.navigateBack({
              delta: 1
            })
          },
          fail: () => {
            Taro.hideLoading()
            Taro.showToast({
              title: '支付失败',
              icon: 'none'
            })
          }
        })
      }
    }
  }
  return (
    <View>
      <Text>OrderCheck</Text>
      <Text>球局名称：{detail?.title || '-'}</Text>
      <Text>价格：¥{detail?.price || '-'}</Text>
      <Button onClick={handlePay}>支付</Button>
    </View>
  )
}

export default withAuth(OrderCheck)