import { browser, getUrlCode } from '@/helpers/utils'
import { Icon } from 'vant'
import { defineComponent, onMounted, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import styles from './index.module.less'

export default defineComponent({
  name: 'pay-center',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const state = reactive({
      errorText: '',
      code: null as any,
      pay_channel: route.query.pay_channel as any,
      wxAppId: route.query.wxAppId as any,
      body: route.query.body as any,
      price: route.query.price as any,
      orderNo: route.query.orderNo as any,
      userId: route.query.userId as any
    })

    const init = () => {
      const pay_channel = state.pay_channel
      if (browser().weixin) {
        if (pay_channel === 'wx_pub') {
          //授权
          const code = getUrlCode()
          console.log(code)
          if (code) {
            state.code = code // 赋值code码
            onPayPage() // 跳转支付页
          } else {
            goAuth()
          }
          document.title = '微信支付'
        } else if (pay_channel == 'alipay_qr') {
          state.errorText = '请使用支付宝扫码'
        }
      } else if (browser().alipay) {
        if (pay_channel === 'wx_pub') {
          state.errorText = '请使用微信扫码'
        } else if (pay_channel == 'alipay_qr') {
          // 支付宝支付
          document.title = '支付宝支付'
          onPayPage() // 跳转支付页
        }
      } else {
        state.errorText = '请在微信或支付宝客户端打开'
      }
      state.errorText && (document.title = 'ERROR')
    }

    const onPayPage = () => {
      // 跳转对应支付页
      router.replace({
        path: '/payDefine',
        query: {
          pay_channel: state.pay_channel,
          wxAppId: state.wxAppId,
          body: state.body,
          price: state.price,
          code: state.code,
          orderNo: state.orderNo,
          userId: state.userId
        }
      })
    }
    const goAuth = () => {
      // 用户授权
      const urlNow = encodeURIComponent(window.location.href)
      const scope = 'snsapi_base' //snsapi_userinfo   //静默授权 用户无感知
      const appid = state.wxAppId || 'wx8654c671631cfade'
      const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${urlNow}&response_type=code&scope=${scope}&state=STATE&connect_redirect=1#wechat_redirect`
      window.location.replace(url)
    }

    onMounted(() => {
      init()
    })

    return () => (
      <div class={styles.payCenter}>
        <div class={styles['error-text']}>
          {state.errorText && <Icon class={styles['error-icon']} name="warning-o" />}

          {state.errorText}
        </div>
      </div>
    )
  }
})
