<template>
  <div class="wechat-pay">
    <div class="order">
      <div>
        <div>订单编号：{{ props.order.id }}</div>
        <div>订单类型：{{ props.order.goods.type }}</div>
      </div>
      <div class="flex items-center">
        应付金额：
        <span style="font-size: 20px; color: #f5222d">
          ￥{{ props.order.amount }}</span
        >
      </div>
    </div>
    <div class="wepay">
      <h5>微信支付</h5>
      <div class="flex center middle">
        <div class="mr-20">
          <img class="wepay-qrcode" :src="payQRCode" />
          <div class="wepay-text">
            <div>请使用微信扫描</div>
            <div>二维码完成支付</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onBeforeMount, onUnmounted, ref } from 'vue';
import axios from 'axios';
import QRCode from 'qrcode';

const props = defineProps<{
  order: any;
  codeUrl: string;
}>();

const emit = defineEmits(['success']);

const payType = ref('wechat');

const payQRCode = ref('');

let timer: any;

onBeforeMount(async () => {
  payQRCode.value = await QRCode.toDataURL(props.codeUrl);

  timer = setInterval(async () => {
    const success = await getPayResult();
    if (success) {
      clearInterval(timer);
      emit('success', success);
    }
  }, 5000);
});

onUnmounted(() => {
  clearInterval(timer);
});

const getPayResult = async () => {
  const result: { state: number } = await axios.post('/api/order/pay/state', {
    id: props.order.id || props.order._id,
  });
  if (result && result.state) {
    return true;
  }
};
</script>

<style lang="postcss" scoped>
.wechat-pay {
  .order {
    padding: 10px 0;
    line-height: 30px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .pay-type {
    background-color: #f7f8fa;
  }

  .wepay {
    color: var(--color-title);
    margin-top: 16px;
  }

  .wepay-qrcode {
    width: 150px;
    margin-top: 24px;
  }
  .wepay-text {
    padding: 10px 40px;
    line-height: 20px;
    color: #ffffff;
    font-size: 13px;
  }
}
</style>
