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

import Big from 'big.js'
import QRCode from 'qrcode'

import { orderService } from '#/api/service/order'
import { spCoinTradeService } from '#/api/service/sp/coin-trade'
import hud from '#/utils/hud'

defineOptions({ name: 'BuyCoin' })
const props = withDefaults(
  defineProps<{
    data: any
    modelValue?: boolean
  }>(),
  {
    modelValue: false,
  },
)

const emits = defineEmits(['update:modelValue', 'refresh'])

const { updateUserInfo } = useAuthStore()
const { userInfo } = storeToRefs(useUserStore())
const show = computed({
  get() {
    return props.modelValue
  },
  set(newVal) {
    emits('update:modelValue', newVal)
    if (newVal) {
      // 刷新用户信息
      updateUserInfo()
    } else {
      paySuccess.value = false
      payType.value = pay_learn
      showWxCode.value = false
      clearTimer()
    }
  },
})

// 支付方式
const pay_weixin = 1
const pay_learn = 2
const payType = ref(pay_learn)

// 二维码地址
const wxCodeSrc = ref('')

// 显示二维码
const showWxCode = ref(false)
async function ok() {
  if (payType.value === pay_learn) {
    // 乐学金支付
    if (Big(props.data.discountedPrice).gt(userInfo.value?.learnAmount)) {
      hud.error('乐学金余额不足')
      return
    }
    // 弹框确认是否购买
    hud.confirmLoad(
      `是否花费￥${props.data.discountedPrice}乐学金购买${props.data.amount}乐贝？`,
      {
        task: async () => {
          await spCoinTradeService.createOrder({
            productId: props.data.id,
            paymentMethod: pay_learn,
          })
          show.value = false
          emits('refresh')
        },
        option: '购买',
      },
    )
  } else {
    // 微信
    // 请求生成二维码信息
    showWxCode.value = true
    const res = await spCoinTradeService.createOrder({
      productId: props.data.id,
      paymentMethod: pay_weixin,
    })
    wxCodeSrc.value = await QRCode.toDataURL(res.codeUrl)
    startTimer(res.id)
  }
}

// 开始查询订单状态的定时器
const paySuccess = ref(false)
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('refresh')
    }
  }, 3000)
}

function clearTimer() {
  clearInterval(timer)
}

onUnmounted(() => {
  clearTimer()
})
</script>

<template>
  <mj-modal
    v-model="show"
    :options="{
      title: '购买乐贝',
      width: 600,
    }"
  >
    <div class="buy-coin">
      <el-descriptions :column="2" border>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">卖家</div>
          </template>
          {{ data.sellerName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">乐贝</div>
          </template>
          {{ data.amount }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">折扣</div>
          </template>
          {{ data.discount }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">价格(¥)</div>
          </template>
          <div class="price">
            <span class="now">{{ data.discountedPrice }}</span>
            <span class="origin">{{ data.price }}</span>
          </div>
        </el-descriptions-item>
        <el-descriptions-item v-if="!showWxCode">
          <template #label>
            <div class="cell-item">支付方式</div>
          </template>
          <el-radio-group v-model="payType" class="ml-4">
            <el-radio :value="pay_learn" size="large">
              乐学金(余额￥{{ userInfo.learnAmount }})
            </el-radio>
            <el-radio :value="pay_weixin" size="large">微信支付</el-radio>
          </el-radio-group>
        </el-descriptions-item>
      </el-descriptions>
      <el-button v-if="!showWxCode" type="primary" @click="ok">确定</el-button>
      <div v-if="showWxCode" class="wx-code-box">
        <div v-if="paySuccess" class="pay-success">
          <p>支付成功</p>
          <OpenEmojiRight width="48" />
        </div>
        <img v-else :src="wxCodeSrc" alt="" />
      </div>
    </div>
  </mj-modal>
</template>

<style lang="scss" scoped>
.buy-coin {
  display: flex;
  flex-direction: column;
  gap: 16px;

  :deep(.el-descriptions) {
    .cell-item,
    .el-descriptions__cell {
      font-size: 16px;
      text-align: center;
    }
  }

  :deep(.el-radio__label) {
    font-size: 16px;
  }

  .price {
    display: flex;
    gap: 10px;
    align-items: flex-end;
    justify-content: center;

    .origin {
      font-size: 14px;
      color: #aaa;
      text-decoration: line-through;
    }
  }

  .wx-code-box {
    display: flex;
    align-items: center;
    justify-content: center;

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