import { Button, View } from '@tarojs/components'
import Taro, { useDidShow, useLoad, useRouter } from '@tarojs/taro'
import { useEffect, useRef, useState } from 'react'
import { BANk_WX_APPID } from '@/common/constant'
import { SubmitNeedHandleApi } from '@/api/orderPay'

interface Param {
  merchId: string
  custMerchId: string
  needCashier?: '1'|'0'
  callBack?: (val: any) => void // 从招商银行返回时的回调函数
}
export default (props: Param) => {
  const { merchId = '', custMerchId = '', needCashier = '1', callBack } = props
  const [payStatus, setPayStatus] = useState(false)
  const openStatus = useRef(false)
  const { fetchData } = SubmitNeedHandleApi()
  console.log('openstatus::', openStatus)
  useEffect(() => {
    Taro.onAppShow((res) => {
      if (res?.referrerInfo?.appId == BANk_WX_APPID && !openStatus.current && props.custMerchId) {
        callBack?.(res)
        const tf = res?.referrerInfo?.extraData?.payStatus == 'success'
        setPayStatus(() => tf)
      }
      openStatus.current = true
    })
  }, [props])

  const pullBank = () => {
    console.log('merchId::', `${merchId}&&${custMerchId}`)
    Taro.navigateToMiniProgram({
      // appId: CURRENT_PAY_Bank_APPID, // 生产环境Id【UAT测试环境appId:wx0fb358ee24237c71】
      appId: 'wx65934ee32a88d726', // 生产环境Id【UAT测试环境appId:wx0fb358ee24237c71】
      path: 'pages/index/index',
      extraData: {
        merchId, // 传商户号（必填，此处传JE开头的商户号）
        custMerchId, // 传缴费号（必填，对接下单接口的payNo）
        needCashier, // 0-展示支付方式选择页，1-跳过支付方式选择页，直接用微信支付（当配置了多种支付方式时，传1也不会跳过支付方式选择页）
      },
      success(res) { // 打开成功的回调函数
        console.log('打开成功::', res)
        openStatus.current = false
        fetchData({ pay_no: custMerchId })
      },
      fail(res) {
        console.log('打开失败::', res)
      },
      complete(res) {
        console.log('打开结果::', res)
      },
    })
  }
  return {
    pullBank,
    payStatus,
  }
}
