<script setup lang="ts">
import { pageUrl } from '@/utils/constants'
import { getMemberProfileApi } from '@/api/member'
import { payOrderApi } from '@/api/pay'
import _ from 'lodash'
import { computed, reactive, ref } from 'vue'
import { onShowRefreshData } from '@/utils/common'

// 获取页面参数
const props = defineProps<{
  orderId: string
  payPrice: string
}>()

const state = reactive({
  orderId: Number(props.orderId),
  balance: '0.00',
})

const getBalance = async () => {
  const res = await getMemberProfileApi()
  state.balance = res.result.money || '0.00'
}

const payMethods = computed(() => {
  return [
    // #ifdef WEB
    {
      name: '支付宝支付',
      value: 'alipay',
      icon: '/static/icons/alipay.svg',
    },
    // #endif
    {
      name: '微信支付',
      value: 'wxpay',
      icon: '/static/icons/wechat-pay.svg',
    },
    {
      name: `余额支付(可用￥${state.balance})`,
      value: 'balance',
      icon: '/static/icons/balance.svg',
    },
  ]
})

const current = ref()
const payWay = ref('')

const radioChange = (event: UniHelper.RadioGroupOnChangeEvent) => {
  payWay.value = event.detail.value
}

const onPayment = async () => {
  if (!payWay.value) {
    return uni.showToast({
      title: '请选择支付方式',
      icon: 'none',
      mask: true,
    })
  }
  if (payWay.value === 'balance' && parseFloat(props.payPrice) > parseFloat(state.balance)) {
    return uni.showToast({
      title: '很抱歉,您的余额不足',
      icon: 'none',
      mask: true,
    })
  }
  try {
    const res = await payOrderApi({
      id: state.orderId,
      pay_way: payWay.value,
    })
    switch (payWay.value) {
      case 'wxpay':
        if (uni.getSystemInfoSync().uniPlatform === 'web') {
          doH5Wxpay(res)
        } else {
          doWxPay(res.result)
        }
        break
      case 'alipay':
        doAlipay(res)
        break
      case 'balance':
        successHandle()
        break
    }
  } catch (err: any) {
    console.log(err)
    // 捕获异常并处理
    uni.showModal({
      title: '提示',
      content: err.data.msg || '支付失败',
      showCancel: false,
    })
  }
}

const doWxPay = async (result: WechatMiniprogram.RequestPaymentOption) => {
  wx.requestPayment({
    ...result,
    success: () => {
      successHandle()
    },
    fail: (fail) => {
      failHandle(fail)
    },
  })
}

const doH5Wxpay = (res: any) => {
  wx.showLoading({
    title: '正在支付…',
    mask: true,
  })

  location.href = res.result.h5_url
}

const doAlipay = (res: any) => {
  wx.showLoading({
    title: '正在支付…',
    mask: true,
  })

  location.href = res.result.url
}

const successHandle = () => {
  setTimeout(() => {
    uni.redirectTo({
      url: `${pageUrl['order-payment']}?id=${state.orderId}&pay_way=${payWay.value}`,
    })
  }, 500)
}
const failHandle = (err: any) => {
  console.warn('支付异常：')
  console.warn(err)
  if (err.errMsg == 'requestPayment:fail cancel') {
    uni.showToast({
      title: '订单取消支付~',
      icon: 'none',
    })
  } else {
    uni.showToast({
      title: err.data.msg ? err.data.msg : '支付未完成',
      icon: 'none',
    })
  }
}

onShowRefreshData(() => {
  getBalance()
})
</script>

<template>
  <view class="overview">
    <view class="money">
      <span class="currency">￥</span>
      <span class="integer">{{ props.payPrice.split('.')[0] }}.</span>
      <span class="decimal">{{ props.payPrice.split('.')[1] }}</span>
    </view>
    <view class="payment">
      <radio-group @change="radioChange" class="card">
        <label class="item" v-for="(item, index) in payMethods" :key="item.value">
          <view class="method">
            <span><image :src="item.icon" class="icon" /></span>
            {{ item.name }}
          </view>
          <view>
            <radio :value="item.value" :checked="current === index" />
          </view>
        </label>
      </radio-group>
    </view>
    <shop-submit-button title="确认支付" @tap="onPayment"></shop-submit-button>
  </view>
</template>

<style lang="scss">
page {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  background: #f0f0f0;
}

.overview {
  background-color: #f0f0f0;

  .money {
    padding: 5%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    color: red;
    font-size: 50rpx;

    .currency {
      font-size: 35rpx;
      vertical-align: sub;
      align-self: flex-end;
    }

    .integer {
      font-size: 60rpx;
    }

    .decimal {
      font-size: 50rpx;
      align-self: flex-end;
    }
  }

  .payment {
    margin: 20rpx 20rpx 0;
    padding: auto;
    border-radius: 10rpx;
    background-color: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .item {
      display: flex;
      justify-content: space-between;
      padding: 5%;
    }

    .method {
      display: flex;
      align-items: center;
    }

    .icon {
      width: 40rpx;
      height: 40rpx;
      margin-right: 20rpx;
    }
  }
}
</style>
