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

      <a-skeleton animation :loading="loading" class="store-spin">
        <StoreDetailSkeleton variant="order" />
        <template #content>
          <div class="detail-stack">
        <!-- 待支付横幅 -->
        <div v-if="data?.state === 0" class="pay-banner detail-stack__section">
          <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" :loading="payLoading" @click="pay">
              继续支付 ¥{{ data?.price }}
            </a-button>
            <a-button
              size="large"
              class="pay-banner__btn"
              :loading="cancelLoading"
              @click="handleCancelOrder"
            >
              取消订单
            </a-button>
          </div>
        </div>

        <a-card
          v-if="data?.state === 0 && data?.canChangePayType !== false"
          :bordered="false"
          class="payment-method-card detail-stack__section"
          title="选择支付方式"
        >
          <!-- <p class="payment-method-card__hint">可以随时切换，确认后将直接跳转至对应支付页面。</p> -->
          <PayMethodPicker
            v-model="selectedPayType"
            :methods="availablePaymentMethods"
            :fallback-default="false"
            layout="grid"
          />
          <p v-if="availablePaymentMethods.length === 0" class="payment-method-card__empty">
            暂无可用支付方式，请稍后再试或联系管理员
          </p>
          <a-button
            type="primary"
            long
            size="large"
            class="payment-method-card__submit"
            :disabled="!selectedPayType || availablePaymentMethods.length === 0"
            :loading="payLoading"
            @click="pay"
          >
            确认并支付
          </a-button>
        </a-card>

        <a-card :bordered="false" class="status-card detail-stack__section">
          <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>

        <OrderRefundPanel
          v-if="data?.state === 2 && (data?.canRefund || data?.refundDisabledReason)"
          class="detail-stack__section"
          :can-refund="!!data?.canRefund"
          :refund-disabled-reason="data?.refundDisabledReason"
          :loading="refundLoading"
          :price="data?.price"
          :lepao-count="data?.lepao_count ?? 0"
          :user-lepao-count="data?.user_lepao_count"
          variant="user"
          @refund="handleRefundOrder"
        />

        <a-card :bordered="false" class="info-card detail-stack__section" 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-item v-if="data?.state === 2 && data?.lepao_count > 0" label="购买次数">
              {{ data.lepao_count }} 次
            </a-descriptions-item>
            <a-descriptions-item v-if="data?.state === 2 && data?.user_lepao_count != null" label="当前剩余次数">
              {{ data.user_lepao_count }} 次
            </a-descriptions-item>
          </a-descriptions>
        </a-card>

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

        <div class="detail-actions detail-stack__section">
          <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>
        </template>
      </a-skeleton>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onUnmounted, onMounted } from 'vue'
import { orderDeatil, cancelOrder, refundOrder, payOrder } 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 StoreDetailSkeleton from '@/components/skeleton/StoreDetailSkeleton.vue'
import OrderRefundPanel from '@/components/store/OrderRefundPanel.vue'
import PayMethodPicker from '@/components/store/PayMethodPicker.vue'
import {
  formatStoreTimeFull,
  getPayTypeLabel,
  decodeGoodsContent
} from '@/utils/storeFormat'
import { submitPayment } from '@/utils/payment'

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

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

const availablePaymentMethods = computed(() => data.value?.paymentMethods || [])

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 5:
      stepCurrent.value = 3
      stepStatus.value = 'finish'
      stepLabels.value = ['待支付', '待处理', '已退款']
      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)
    if (data.value?.state === 0 && !selectedPayType.value) {
      selectedPayType.value = availablePaymentMethods.value.some(method => method.type === data.value.pay_type)
        ? data.value.pay_type
        : availablePaymentMethods.value[0]?.type || ''
    }
    if (data.value?.state === 0 && selectedPayType.value && !availablePaymentMethods.value.some(method => method.type === selectedPayType.value)) {
      selectedPayType.value = availablePaymentMethods.value[0]?.type || ''
    }
    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 = async () => {
  if (availablePaymentMethods.value.length === 0) {
    Message.warning('暂无可用支付方式，请稍后再试')
    return
  }
  if (!selectedPayType.value) {
    Message.warning('请选择支付方式')
    return
  }
  if (!availablePaymentMethods.value.some(method => method.type === selectedPayType.value)) {
    Message.warning('该支付方式当前不可用，请重新选择')
    selectedPayType.value = availablePaymentMethods.value[0]?.type || ''
    return
  }
  const paymentWindow = window.open('', '_blank')
  if (!paymentWindow) {
    Message.warning('浏览器拦截了支付页弹窗，请允许弹窗后重试')
    return
  }
  try {
    payLoading.value = true
    const res = await payOrder({ orderId: id, pay_type: selectedPayType.value })
    if (!res || res.code !== 0 || !submitPayment(res.pay, { targetWindow: paymentWindow })) {
      if (paymentWindow && !paymentWindow.closed) paymentWindow.close()
      Notification.error({
        title: '发起支付失败',
        content: res?.msg || '支付信息无效，请稍后重试'
      })
    }
  } catch (error) {
    if (paymentWindow && !paymentWindow.closed) paymentWindow.close()
    Notification.error({
      title: '发起支付失败',
      content: error.message || '请稍后重试'
    })
  } finally {
    payLoading.value = false
  }
}

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 || '订单已取消')
        stopPendingOrderTimers()
        await getOrderDetail()
      } catch (error) {
        Notification.error({
          title: '取消订单失败',
          content: error.message || '请稍后再试'
        })
      } finally {
        cancelLoading.value = false
      }
    }
  })
}

const handleRefundOrder = () => {
  const purchased = data.value?.lepao_count ?? 0
  const remaining = data.value?.user_lepao_count ?? 0
  Modal.confirm({
    title: '申请退款',
    content: `退款将扣回 ${purchased} 次乐跑次数（当前剩余 ${remaining} 次），款项原路退回。确定继续吗？`,
    okText: '确认退款',
    cancelText: '再想想',
    okButtonProps: { status: 'warning' },
    onOk: async () => {
      try {
        refundLoading.value = true
        const res = await refundOrder({ orderId: id })
        if (!res || res.code !== 0) {
          Notification.error({
            title: '退款失败',
            content: res?.msg ?? '请稍后再试'
          })
          return
        }
        Message.success(res.msg || '退款成功')
        await getOrderDetail()
      } catch (error) {
        Notification.error({
          title: '退款失败',
          content: error.message || '请稍后再试'
        })
      } finally {
        refundLoading.value = false
      }
    }
  })
}

</script>

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

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

  &__section {
    margin: 0;
  }

  :deep(.arco-card) {
    margin-bottom: 0;
  }
}

.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,
.payment-method-card {
  border-radius: @store-radius;
  border: 1px solid @store-card-border;
  box-shadow: @store-shadow;
}

.payment-method-card {
  overflow: hidden;
  background:
    radial-gradient(circle at 100% 0, fade(@store-accent, 12%) 0, transparent 33%),
    @store-card-bg;

  &__hint {
    margin: 0 0 18px;
    color: @store-text-muted;
    font-size: 0.9rem;
    line-height: 1.6;
  }

  &__submit {
    margin-top: 20px;
    height: 46px;
    border-radius: 999px;
    font-weight: 600;
    letter-spacing: 0.04em;
    background: linear-gradient(110deg, @store-primary, lighten(@store-primary, 13%)) !important;
    border-color: transparent !important;
    box-shadow: 0 8px 18px fade(@store-primary, 24%);
  }

  &__empty {
    margin: 10px 0 0;
    font-size: 12px;
    color: rgb(var(--orange-6));
  }
}

.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;
  padding-top: 4px;
}

@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>
