<!-- eslint-disable unicorn/prefer-ternary -->
<script setup lang="ts">
import { OpenEmojiRight } from '@vben/icons'

import QRCode from 'qrcode'

import { orderService } from '#/api/service/order'
import hud from '#/utils/hud'
import num from '#/utils/num'

defineOptions({ name: 'WxTopUp' })
const props = withDefaults(
  defineProps<{
    moneyOptions: any[]
    // 支付函数
    pay: (money: any) => Promise<any>
    title: any
  }>(),
  {},
)

const emits = defineEmits(['success'])

// 自定义的金额
const customMoney = ref('')
const defaultMoneyType = props.moneyOptions[0].value
const moneyType = ref(defaultMoneyType as any)
// 步骤
const step_1 = 1
const step_2 = 2
const step = ref(step_1)

// 最终的充值金额
const finalMoney = ref(0)

// 二维码图片
const qrCode = ref('')

// 支付成功
const paySuccess = ref(false)

// 显示二维码
const qrCodeVisible = ref(false)
function showQrCode() {
  let value = Number(moneyType.value)
  if (value === 0) {
    value = Number(customMoney.value)
    if (
      Number.isNaN(value) ||
      value < defaultMoneyType ||
      !num.isPositiveInt(num.toFixed2(value))
    ) {
      hud.error(`请输入大于等于${defaultMoneyType}的正整数金额`)
      return
    }
  }
  hud.load({
    task: async () => {
      const data = await props.pay(value)
      finalMoney.value = value
      step.value = step_2
      qrCode.value = await QRCode.toDataURL(data.codeUrl)
      // 开启定时器
      startTimer(data.id)
    },
    option: '生成订单',
  })
}

// 开始查询订单状态的定时器
let timer: any
function startTimer(orderId: any) {
  clearTimer()
  timer = setInterval(async () => {
    const data = await orderService.getOrder(orderId)
    if (Number(data.status) === 1) {
      clearTimer()
      paySuccess.value = true
      emits('success')
    }
  }, 3000)
}

function clearTimer() {
  clearInterval(timer)
}

onUnmounted(() => {
  clearTimer()
})

watch(
  () => step.value,
  () => {
    if (step.value === step_2) {
      qrCodeVisible.value = true
    } else {
      qrCodeVisible.value = false
      finalMoney.value = 0
      customMoney.value = ''
      moneyType.value = defaultMoneyType
    }
  },
)

const _title = computed(() => {
  if (step.value === step_1) {
    return props.title
  }
  return `微信扫描支付￥${finalMoney.value}元`
})

defineExpose({
  reset() {
    clearTimer()
    step.value = step_1
    paySuccess.value = false
    qrCodeVisible.value = false
  },
})
</script>

<template>
  <div class="wx-top-up">
    <p class="title">{{ _title }}</p>
    <div v-if="step === step_1" class="top-up-content">
      <el-radio-group v-model="moneyType" size="large">
        <el-radio-button
          class="radio-money"
          v-for="item in moneyOptions"
          :value="item.value"
          :label="item.label"
          :key="item.value"
        />
      </el-radio-group>
      <mj-form-money
        v-if="moneyType === 0"
        class="custom-money"
        v-model="customMoney"
        :placeholder="`请输入自定义金额（${defaultMoneyType}元起）`"
      />
      <el-button class="sure-btn" type="primary" @click="showQrCode">
        确定
      </el-button>
    </div>
    <div v-else-if="step === step_2">
      <div v-if="paySuccess" class="pay-success">
        <p>支付成功</p>
        <OpenEmojiRight width="48" />
      </div>
      <img v-else :src="qrCode" alt="" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
$width: 503px;
$gap: 20px;
$fz: 16px;

.wx-top-up {
  display: flex;
  flex-direction: column;
  gap: $gap;
  align-items: center;

  .pay-success {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 150px;
    font-size: 28px;
    gap: 10px;
  }

  .title {
    width: 100%;
    font-size: 20px;
    text-align: center;
  }

  .top-up-content {
    display: flex;
    flex-direction: column;
    gap: $gap;
    align-items: center;
    width: 100%;

    .radio-money {
      :deep(.el-radio-button__inner) {
        font-size: $fz;
      }
    }

    .custom-money {
      width: $width;
      height: 40px;
      font-size: $fz;
    }

    .sure-btn {
      width: $width;
      height: 40px;
      font-size: $fz;
    }
  }
}
</style>
