import request from '@/helpers/request'
import {
  listenerMessage,
  postMessage,
  removeListenerMessage
} from '@/helpers/native-message'
import {
  Button,
  Cell,
  CellGroup,
  Icon,
  RadioGroup,
  Radio,
  Dialog,
  Toast
} from 'vant'
import { defineComponent, PropType } from 'vue'

import styles from './index.module.less'
import { state } from '@/state'
import { validStudentUrl } from '@/helpers/utils'

export default defineComponent({
  name: 'payment',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    orderInfo: {
      type: Object,
      default: () => {
        return {}
      }
    },
    onBackOut: {
      type: Function,
      default: () => {}
    },
    paymentType: {
      type: String,
      default: 'orderPay' as 'orderPay' | 'goodsPay'
    }
  },
  data() {
    return {
      payType: 'ali_app',
      pay_channel: ''
    }
  },
  methods: {
    onClose() {
      Dialog.confirm({
        message: '是否放弃本次付款',
        confirmButtonText: '继续付款',
        cancelButtonText: '放弃'
      })
        .then(() => {})
        .catch(async () => {
          this.onCancel()
        })
    },
    async onCancel(noBack?: boolean) {
      // 不管接口是否报错,都返回
      this.$emit('update:modelValue', false)

      !noBack && this.$router.go(-1)
      this.onBackOut && this.onBackOut()
    },
    async onSubmit() {
      // 支付...
      try {
        console.log(this.orderInfo, 'orderInfo payment')
        Toast.loading({
          message: '支付中...',
          forbidClick: true,
          duration: 3000,
          loadingType: 'spinner'
        })

        const pt = this.payType,
          ua = window.navigator.userAgent.toLowerCase()
        // 判断当前浏览器
        if (ua.match(/MicroMessenger/i) + '' == 'micromessenger') {
          // 微信浏览器
          if (pt == 'ali_app') {
            this.pay_channel = 'alipay_qr'
            this.getCodePay('qrCode')
          } else if (pt == 'wx_app') {
            this.pay_channel = 'wx_pub'
            this.getCodePay('pay')
          }
        } else if (ua.match(/AlipayClient/i) + '' == 'alipayclient') {
          // 支付宝浏览器
          if (pt == 'ali_app') {
            this.pay_channel = 'alipay_wap'
            // 支付宝 H5 支付
            this.getCodePay('pay')
          } else if (pt == 'wx_app') {
            this.pay_channel = 'wx_pub'
            this.getCodePay('qrCode')
          }
        } else {
          if (pt == 'ali_app') {
            this.pay_channel = 'alipay_qr'
          } else if (pt == 'wx_app') {
            this.pay_channel = 'wx_pub'
          }
          this.getCodePay('qrCode')
        }
        this.$emit('update:modelValue', false)

        setTimeout(() => {
          Toast.clear()
        }, 1000)
      } catch (e: any) {
        console.log(e)
      }
    },
    getCodePay(code) {
      // 二维码页面， 唤起支付页面
      let url = validStudentUrl()
      if (code == 'qrCode') {
        url += `/#/payQRCode`
      } else {
        url += `/#/payResult`
      }
      const orderInfo = this.orderInfo
      orderInfo.payMap.returnUrl = orderInfo.payMap.returnUrl.replace(
        /&/gi,
        '^^'
      )
      const navHeight = sessionStorage.getItem('navHeight') || 0
      // p 表示是商品购买，需要单独去学生端处理
      url += `?payType=${this.pay_channel}&payment=${JSON.stringify(
        this.orderInfo
      )}&navHeight=${navHeight}'&platform=goods`
      window.location.replace(url)
    }
  },
  render() {
    return (
      <div class={styles.payment}>
        <Icon onClick={this.onClose} name="cross" size={20} />
        <div class={[styles.title, 'van-hairline--bottom']}>选择支付方式</div>

        <div class={styles.payAmount}>
          <p>应付金额</p>
          <div class={styles.amount}>
            {(this as any).$filters.moneyFormat(
              this.orderInfo.payMap.amount || 0
            )}
            <span>元</span>
          </div>
        </div>
        <RadioGroup v-model={this.payType}>
          <CellGroup border={false}>
            <Cell
              title="支付宝支付"
              border={false}
              center
              onClick={() => {
                // alipay
                this.payType = 'ali_app'
              }}
              v-slots={{
                icon: () => <Icon name="alipay" color="#009fe9" size={22} />,
                'right-icon': () => <Radio name="ali_app" />
              }}
            ></Cell>
            <Cell
              title="微信支付"
              border={false}
              center
              onClick={() => {
                // wx_lite
                this.payType = 'wx_app'
              }}
              v-slots={{
                icon: () => (
                  <Icon name="wechat-pay" color="#15c434" size={22} />
                ),
                'right-icon': () => <Radio name="wx_app" />
              }}
            ></Cell>
          </CellGroup>
        </RadioGroup>

        <div class={styles.blank}></div>
        <Button
          type="primary"
          class={styles.payBtn}
          block
          round
          onClick={this.onSubmit}
        >
          确认支付
        </Button>
      </div>
    )
  }
})
