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'

interface IOrderInfo {
  orderNo: string | number
  actualPrice: string | number
}

const urlFix =
  state.platformType === 'TEACHER' ? '/api-teacher' : '/api-student'
const urlType = {
  goodsPay: {
    cancelUrl: '/api-mall-portal/order/cancelUserOrder',
    payUrl: '/api-mall-portal/payment/orderPay'
  },
  orderPay: {
    cancelUrl: urlFix + '/userOrder/orderCancel',
    payUrl: urlFix + '/userOrder/orderPay'
  }
}

export default defineComponent({
  name: 'payment',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    orderInfo: {
      type: Object as PropType<IOrderInfo>,
      default: {
        orderNo: '',
        actualPrice: 0
      }
    },
    onBackOut: {
      type: Function,
      default: () => {}
    },
    paymentType: {
      type: String,
      default: 'orderPay' as 'orderPay' | 'goodsPay'
    }
  },
  data() {
    return {
      payType: 'ali_app',
      pay_channel: ''
    }
  },
  unmounted() {
    removeListenerMessage('paymentOperation', this.paymentOperation)
  },
  methods: {
    onClose() {
      Dialog.confirm({
        message: '是否放弃本次付款',
        confirmButtonText: '继续付款',
        cancelButtonText: '放弃'
      })
        .then(() => {})
        .catch(async () => {
          this.onCancel()
        })
    },
    async onCancel(noBack?: boolean) {
      try {
        await request.post(urlType[this.paymentType].cancelUrl, {
          data: {
            orderNo: this.orderInfo.orderNo
          }
        })
      } catch {}
      // 不管接口是否报错,都返回
      this.$emit('update:modelValue', false)
      !noBack && this.$router.go(-1)
      this.onBackOut && this.onBackOut()
    },
    async onSubmit() {
      // 支付...
      try {
        let params = {
          orderNo: this.orderInfo.orderNo,
          payChannel: this.payType,
          paymentClient: null as any
        }
        if (this.paymentType === 'goodsPay') {
          params.paymentClient = state.platformType
        }
        let res = await request.post(urlType[this.paymentType].payUrl, {
          data: {
            ...params
          }
        })
        postMessage({
          api: 'paymentOrder',
          content: {
            orderNo: this.orderInfo.orderNo,
            payChannel: this.payType,
            // payInfo: `alipays://platformapi/startapp?saId=10000007&qrcode=${res.data.pay_info}`
            payInfo: res.data.pay_info
          }
        })
        Toast.loading({
          message: '支付中...',
          forbidClick: true,
          duration: 3000,
          loadingType: 'spinner'
        })
        Toast.clear()
        this.$emit('update:modelValue', false)
        // 唤起支付时状态
        listenerMessage('paymentOperation', (result: any) =>
          this.paymentOperation(result)
        )
      } catch (e: any) {
        console.log(e)
      }
    },
    paymentOperation(res: any) {
      if (res.status === 'success') {
        Toast.clear()
        this.$emit('update:modelValue', false)
        this.$router.replace({
          path: '/tradeDetail',
          query: {
            orderNo: this.orderInfo.orderNo
          }
        })
      } else if (res.status === 'cancel') {
        Toast.clear()
        this.$emit('update:modelValue', false)
      } else if (res.status === 'fail') {
        Dialog.alert({
          title: '提示',
          message: '您尚未安装支付宝'
        }).then(() => {
          Toast.clear()
          this.$emit('update:modelValue', false)
        })
      }
    }
  },
  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.actualPrice)}
            <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" block onClick={this.onSubmit}>
          确认支付
        </Button>
      </div>
    )
  }
})
