<template>
  <div class="store-page order-detail-page">
    <div class="order-detail-page__inner app-page__inner--wide">
      <Breadcrumb />

      <a-spin :loading="loading" class="store-spin">
        <div class="detail-stack">
        <!-- 待支付横幅 -->
        <div v-if="data?.state === 0 && hasPay" class="pay-banner">
          <div class="pay-banner__info">
            <icon-clock-circle class="pay-banner__icon" />
            <div>
              <div class="pay-banner__title">等待支付</div>
              <div class="pay-banner__desc">{{ paymentCountdownText }}</div>
            </div>
          </div>
          <div class="pay-banner__actions">
            <a-button type="primary" size="large" class="pay-banner__btn" @click="pay">
              立即支付 ¥{{ data?.price }}
            </a-button>
            <a-button
              size="large"
              class="pay-banner__btn"
              :loading="cancelLoading"
              @click="handleCancelOrder"
            >
              取消订单
            </a-button>
          </div>
        </div>

        <a-card :bordered="false" class="status-card">
          <OrderProgressSteps
            class="steps"
            :mobile="isMobile"
            :current="stepCurrent"
            :status="stepStatus"
            :labels="stepLabels"
            :descriptions="stepDescriptions"
          />
          <div class="status-badge-wrap">
            <OrderStateTag :state="data?.state ?? 0" />
          </div>
        </a-card>

        <a-card :bordered="false" class="info-card" title="订单信息">
          <a-descriptions :column="1" bordered size="medium">
            <a-descriptions-item label="商品名称">{{ data?.name || '-' }}</a-descriptions-item>
            <a-descriptions-item v-if="data?.original_price && data?.discount_amount > 0" label="商品原价">
              ¥{{ data.original_price }}
            </a-descriptions-item>
            <a-descriptions-item v-if="data?.coupon_code" label="优惠码">
              {{ data.coupon_code }}
              <span v-if="data?.discount_amount > 0" class="discount-tag">-¥{{ data.discount_amount }}</span>
            </a-descriptions-item>
            <a-descriptions-item label="支付金额">
              <span class="price-text">¥{{ data?.price }}</span>
            </a-descriptions-item>
            <a-descriptions-item label="支付方式">
              <span class="pay-row">
                <icon-wechatpay v-if="data?.pay_type === 'wxpay'" />
                <icon-alipay-circle v-else-if="data?.pay_type === 'alipay'" />
                {{ getPayTypeLabel(data?.pay_type) }}
              </span>
            </a-descriptions-item>
            <a-descriptions-item label="订单号">{{ data?.orderId }}</a-descriptions-item>
            <a-descriptions-item v-if="data?.pay_id" label="支付平台单号">{{ data.pay_id }}</a-descriptions-item>
            <a-descriptions-item label="下单时间">{{ formatStoreTimeFull(data?.create_time) }}</a-descriptions-item>
            <a-descriptions-item v-if="data?.pay_time" label="支付时间">
              {{ formatStoreTimeFull(data.pay_time) }}
            </a-descriptions-item>
          </a-descriptions>
        </a-card>

        <a-card v-if="content" :bordered="false" class="info-card" title="商品说明">
          <div class="rich-content" v-html="content" />
        </a-card>

        <div class="detail-actions">
          <a-button
            v-if="data?.state === 0"
            status="danger"
            :loading="cancelLoading"
            @click="handleCancelOrder"
          >
            取消订单
          </a-button>
          <a-button @click="$router.push('/store/myOrder')">返回订单列表</a-button>
          <a-button type="outline" @click="$router.push('/store/goodsList')">继续购物</a-button>
        </div>
        </div>
      </a-spin>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onUnmounted, onMounted } from 'vue'
import { orderDeatil, cancelOrder } from '@/api/order'
import { useRoute } from 'vue-router'
import { Notification, Message, Modal } from '@arco-design/web-vue'
import OrderStateTag from '@/components/store/OrderStateTag.vue'
import OrderProgressSteps from '@/components/store/OrderProgressSteps.vue'
import {
  formatStoreTimeFull,
  getPayTypeLabel,
  decodeGoodsContent,
  hasPayData
} from '@/utils/storeFormat'

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

const loading = ref(true)
const cancelLoading = ref(false)
const data = ref({})
const payData = ref({})
const content = ref('')
const paymentCountdownText = ref('')
const isMobile = ref(false)

const hasPay = computed(() => hasPayData(payData.value))

const stepCurrent = ref(1)
const stepStatus = ref('process')
const stepLabels = ref(['待支付', '待处理', '已完成'])
const stepDescriptions = ref(['', '', ''])
const PAY_TIMEOUT_SEC = 300
let pollTimer = null
let countdownTimer = null
let resizeHandler = null

const updateStepState = () => {
  const state = data.value?.state
  stepDescriptions.value = ['', '', '']

  switch (state) {
    case 0:
      stepCurrent.value = 1
      stepStatus.value = 'process'
      stepLabels.value = ['待支付', '待处理', '已完成']
      updatePaymentCountdown()
      startCountdownTicker()
      break
    case 1:
      stepCurrent.value = 2
      stepStatus.value = 'process'
      stepDescriptions.value[1] = '支付成功，等待系统处理'
      stopPendingOrderTimers()
      break
    case 2:
      stepCurrent.value = 3
      stepStatus.value = 'finish'
      stepDescriptions.value[2] = '权益已发放至账户'
      stopPendingOrderTimers()
      break
    case 3:
      stepCurrent.value = 1
      stepStatus.value = 'error'
      stepLabels.value = ['已关闭', '待处理', '已完成']
      stepDescriptions.value[0] = '订单超时或已取消'
      stopPendingOrderTimers()
      break
    default:
      break
  }
}

const updatePaymentCountdown = () => {
  const ts = data.value?.create_time
  if (!ts) {
    paymentCountdownText.value = '请在规定时间内完成支付'
    return
  }
  const diffSec = Math.floor((Date.now() - ts) / 1000)
  if (diffSec > PAY_TIMEOUT_SEC) {
    paymentCountdownText.value = '支付已超时，订单可能已关闭'
    stepDescriptions.value[0] = '支付超时'
    return
  }
  const remaining = PAY_TIMEOUT_SEC - diffSec
  const m = Math.floor(remaining / 60)
  const s = String(remaining % 60).padStart(2, '0')
  paymentCountdownText.value = `请在 ${m} 分 ${s} 秒内完成支付`
  stepDescriptions.value[0] = paymentCountdownText.value
}

const getOrderDetail = 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 = decodeGoodsContent(res.data?.content)
    payData.value = res.payData && hasPayData(res.payData) ? res.payData : {}
    updateStepState()
  } catch (error) {
    Notification.error({
      title: '获取订单详情失败',
      content: error.message || '请稍后再试'
    })
  }
}

const startCountdownTicker = () => {
  if (countdownTimer) return
  countdownTimer = setInterval(() => {
    if (data.value?.state !== 0) {
      stopCountdownTicker()
      return
    }
    updatePaymentCountdown()
  }, 1000)
}

const stopCountdownTicker = () => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
  }
}

const startPolling = () => {
  if (pollTimer) return
  pollTimer = setInterval(async () => {
    if (data.value?.state !== 0) {
      stopPolling()
      return
    }
    await getOrderDetail()
  }, 3000)
}

const stopPolling = () => {
  if (pollTimer) {
    clearInterval(pollTimer)
    pollTimer = null
  }
}

const stopPendingOrderTimers = () => {
  stopCountdownTicker()
  stopPolling()
}

onMounted(async () => {
  const syncMobile = () => {
    isMobile.value = window.innerWidth <= 768
  }
  resizeHandler = syncMobile
  syncMobile()
  window.addEventListener('resize', resizeHandler)
  loading.value = true
  await getOrderDetail()
  loading.value = false
  if (data.value?.state === 0) startPolling()
})

onUnmounted(() => {
  stopPendingOrderTimers()
  if (resizeHandler) window.removeEventListener('resize', resizeHandler)
})

const pay = () => {
  if (!hasPay.value) {
    Message.warning('暂无支付信息，请刷新页面重试')
    return
  }
  Message.success('正在跳转支付页面，请在新页面完成支付')
  openPaymentWindow(payData.value.payUrl, payData.value.payData)
}

const handleCancelOrder = () => {
  Modal.confirm({
    title: '取消订单',
    content: '确定要取消该订单吗？取消后需重新下单购买。',
    okText: '确认取消',
    cancelText: '再想想',
    okButtonProps: { status: 'danger' },
    onOk: async () => {
      try {
        cancelLoading.value = true
        const res = await cancelOrder({ orderId: id })
        if (!res || res.code !== 0) {
          Notification.error({
            title: '取消订单失败',
            content: res?.msg ?? '请稍后再试'
          })
          return
        }
        Message.success(res.msg || '订单已取消')
        payData.value = {}
        stopPendingOrderTimers()
        await getOrderDetail()
      } catch (error) {
        Notification.error({
          title: '取消订单失败',
          content: error.message || '请稍后再试'
        })
      } finally {
        cancelLoading.value = false
      }
    }
  })
}

function openPaymentWindow(payUrl, formData) {
  const form = document.createElement('form')
  form.method = 'POST'
  form.action = payUrl
  form.style.display = 'none'
  for (const key in formData) {
    if (Object.prototype.hasOwnProperty.call(formData, key)) {
      const input = document.createElement('input')
      input.type = 'hidden'
      input.name = key
      input.value = formData[key]
      form.appendChild(input)
    }
  }
  document.body.appendChild(form)
  form.submit()
  document.body.removeChild(form)
}
</script>

<style lang="less" scoped>
@import '@/styles/store-theme.less';

.detail-stack {
  display: flex;
  flex-direction: column;
  gap: 16px;
  width: 100%;
}

.pay-banner {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  padding: 20px 24px;
  background: linear-gradient(135deg, #fff7e6 0%, #ffe7ba 100%);
  border: 1px solid #ffd591;
  border-radius: @store-radius;

  &__info {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  &__icon {
    font-size: 32px;
    color: rgb(var(--orange-6));
  }

  &__title {
    font-weight: 600;
    font-size: 1.1rem;
    color: @store-primary;
  }

  &__desc {
    font-size: 0.85rem;
    color: @store-text-muted;
    margin-top: 4px;
  }

  &__actions {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    flex-shrink: 0;
  }

  &__btn {
    border-radius: 999px;
    flex-shrink: 0;
  }
}

.status-card,
.info-card {
  border-radius: @store-radius;
  border: 1px solid @store-card-border;
  box-shadow: @store-shadow;
}

.status-badge-wrap {
  text-align: center;
}

.price-text {
  font-size: 1.15rem;
  font-weight: 700;
  color: @store-price;
}

.discount-tag {
  margin-left: 8px;
  color: rgb(var(--green-6));
  font-size: 0.9rem;
}

.pay-row {
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.rich-content {
  line-height: 1.75;
  color: @store-text-muted;

  :deep(img) {
    max-width: 100%;
  }
}

.detail-actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  margin-top: 8px;
}

@media (max-width: 768px) {
  .pay-banner {
    padding: 14px 12px;
  }

  .detail-actions {
    display: grid;
    grid-template-columns: 1fr;
  }

  .detail-actions :deep(.arco-btn) {
    width: 100%;
  }
}
</style>
