<template>
  <div class="container">
    <Breadcrumb :items="['Forge商城', '订单详情']" />
    <a-space direction="vertical" :size="16" fill>
      <a-card class="general-card" title="订单状态">
        <div class="step">
          <a-steps :current="current" :status="status">
            <a-step :description="oneDes">{{ oneText }}</a-step>
            <a-step :description="twoDes">{{ twoText }}</a-step>
            <a-step :description="threeDes">{{ threeText }}</a-step>
          </a-steps>
        </div>
        <a-button type="primary" size="large" class="paybutton" @click="pay"
          v-if="data?.state === 0 && payData != {}">立即支付</a-button>

      </a-card>
      <a-card class="general-card" title="订单详情">
        <a-descriptions :data="orderData" size="large" :column="1" />
      </a-card>
      <a-card class="general-card" title="商品详情">
        <div v-html="content"></div>
      </a-card>

    </a-space>
  </div>
</template>

<script setup>
import { ref, onUnmounted, onMounted, h } from 'vue'
import { orderDeatil } from '@/api/order'
import { useRoute } from 'vue-router'
import { Notification } from '@arco-design/web-vue'
import { Message } from '@arco-design/web-vue'
import { IconQq, IconWechatpay, IconAlipayCircle } from '@arco-design/web-vue/es/icon'

const route = useRoute()
const { id } = route.params

const loading = ref(true)
const data = ref({})
const payData = ref({})

const current = ref(1)
const status = ref('process')
const oneText = ref('待支付')
const twoText = ref('待处理')
const threeText = ref('已完成')
const oneDes = ref('')
const twoDes = ref('')
const threeDes = ref('')

const orderData = ref([])
const content = ref('')

const stramptoTime = (time) => {
  return new Date(time).toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' })
}

function getPayType(type) {
  switch (type) {
    case 'alipay':
      return [h(IconAlipayCircle), ' 支付宝']
    case 'qqpay':
      return [h(IconQq), ' QQ支付']
    case 'wxpay':
      return [h(IconWechatpay), ' 微信支付']
  }
}

const getOrderDeatil = async () => {
  try {
    const res = await orderDeatil({ orderId: id })
    if (!res || res.code !== 0)
      return Notification.error({
        title: '获取订单详情失败！',
        content: res?.msg ?? '请稍后再试'
      })
    data.value = res.data
    content.value = decodeURI(atob(res.data.content || ''))

    let detail = []
    if (res.data.name)
      detail.push({ label: '商品名称', value: res.data.name })
    if (res.data.price)
      detail.push({ label: '支付价格', value: '￥' + res.data.price })
    if (res.data.pay_type)
      detail.push({ label: '支付方式', value: getPayType(res.data.pay_type) })
    if (res.data.orderId)
      detail.push({ label: '平台订单号', value: res.data.orderId })
    if (res.data.pay_id)
      detail.push({ label: '支付平台订单号', value: res.data.pay_id })
    if (res.data.create_time)
      detail.push({ label: '下单时间', value: stramptoTime(res.data.create_time) })
    if (res.data.pay_time)
      detail.push({ label: '支付时间', value: stramptoTime(res.data.pay_time) })

    orderData.value = detail

    if (res.payData)
      payData.value = res.payData
    else
      payData.value = {}
  } catch (error) {
    Notification.error({
      title: '获取订单详情失败！',
      content: error.message || '请稍后再试'
    })
  }
}

let timer = null

// 轮询
const startPolling = () => {
  if (!timer) {
    timer = setInterval(async () => {
      await getOrderDeatil()
      getOrderState()
    }, 1000)
  }
}

// 停止轮询
const stopPolling = () => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
}

onMounted(async () => {
  loading.value = true
  await getOrderDeatil()
  loading.value = false
  startPolling()
})

// 组件销毁时停止轮询
onUnmounted(() => {
  stopPolling()
})

function getOrderState() {
  if (data.value) {

    switch (data.value.state) {
      case 0:
        current.value = 1
        getPaymentStatus(data.value.create_time)
        break

      case 1:
        current.value = 2
        twoDes.value = '支付完成，等待系统处理'
        oneDes.value = ''
        break

      case 2:
        current.value = 3
        threeDes.value = '订单处理完毕'
        status.value = 'finish'
        oneDes.value = ''
        twoDes.value = ''
        stopPolling()
        break

      case 3:
        current.value = 1
        status.value = 'error'
        oneText.value = '支付超时'
        oneDes.value = '订单已关闭'
        stopPolling()
        break

    }
  }
}

function getPaymentStatus(timestamp) {
  const now = Date.now();
  const diffMs = now - timestamp; // 毫秒差值
  const diffSeconds = Math.floor(diffMs / 1000); // 秒差值

  const timeout = 300;

  if (diffSeconds > timeout) {
    oneDes.value = "支付超时";
  } else {
    const remaining = timeout - diffSeconds;
    const minutes = Math.floor(remaining / 60);
    const seconds = remaining % 60;
    oneDes.value = `请在${minutes}分${seconds.toString().padStart(2, '0')}秒内完成支付`;
  }
}

const pay = () => {
  Message.success('正在跳转支付页面...请在新页面内完成支付')
  if (payData.value != {}) {
    openPaymentWindow(payData.value.payUrl, payData.value.payData)
  }
}

function openPaymentWindow(payUrl, payData) {
  const form = document.createElement('form');
  form.method = 'POST';
  form.action = payUrl;
  // form.target = '_blank'
  form.style.display = 'none';

  // 遍历 payData，将每一项添加为隐藏的 input
  for (const key in payData) {
    if (payData.hasOwnProperty(key)) {
      const input = document.createElement('input');
      input.type = 'hidden';
      input.name = key;
      input.value = payData[key];
      form.appendChild(input);
    }
  }

  document.body.appendChild(form);
  form.submit();
  document.body.removeChild(form);
}

</script>

<style lang="less" scoped>
.container {
  padding: 0 20px 20px 20px;
}

.general-card {
  border-radius: 5px;

  .step {
    width: 900px;
    margin: 30px auto;
  }

  .paybutton {
    position: relative;
    left: 50%;
    translate: (-50%);
    margin-top: 10px;
  }
}
</style>