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

      <header class="page-header">
        <div>
          <h1 class="store-section-title">我的订单</h1>
          <p class="store-section-desc">查看购买记录与支付状态</p>
        </div>
        <a-button type="outline" @click="$router.push('/store/goodsList')">
          <template #icon><icon-gift /></template>
          去商城
        </a-button>
      </header>

      <a-alert v-if="notice" type="info" closable class="notice">{{ notice }}</a-alert>

      <a-tabs v-model:active-key="statusTab" class="status-tabs">
        <a-tab-pane v-for="tab in statusTabs" :key="tab.key" :title="tab.title" />
      </a-tabs>

      <a-skeleton animation :loading="loading" class="store-spin">
        <StoreStackSkeleton :count="4" :show-action="false" :header-widths="['40%', '20%']" />
        <template #content>
          <a-empty v-if="displayList.length === 0" description="暂无相关订单">
            <a-button type="primary" @click="$router.push('/store/goodsList')">去选购</a-button>
          </a-empty>

          <div v-else class="order-list">
          <article
            v-for="record in displayList"
            :key="record.orderId"
            class="order-card"
            @click="goDetail(record.orderId)"
          >
            <div class="order-card__head">
              <span class="order-id">{{ record.orderId }}</span>
              <OrderStateTag :state="record.state" />
            </div>
            <div class="order-card__body">
              <h3 class="goods-name">{{ record.name }}</h3>
              <div class="order-card__meta">
                <span class="price">¥{{ record.price }}</span>
                <span class="pay-type">
                  <icon-wechatpay v-if="record.pay_type === 'wxpay'" />
                  <icon-alipay-circle v-else-if="record.pay_type === 'alipay'" />
                  <icon-qq v-else-if="record.pay_type === 'qqpay'" />
                  {{ getPayTypeLabel(record.pay_type) }}
                </span>
              </div>
              <time class="time">{{ formatStoreTime(record.create_time) }}</time>
            </div>
            <div class="order-card__actions">
              <template v-if="record.state === 0">
                <a-button
                  type="primary"
                  size="small"
                  @click.stop="goDetail(record.orderId)"
                >
                  去支付
                </a-button>
                <a-button
                  size="small"
                  status="danger"
                  :loading="cancelingOrderId === record.orderId"
                  @click.stop="handleCancelOrder(record)"
                >
                  取消订单
                </a-button>
              </template>
              <a-button v-else type="text" size="small" @click.stop="goDetail(record.orderId)">
                查看详情
              </a-button>
            </div>
          </article>
          </div>
        </template>
      </a-skeleton>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getMyOrder, cancelOrder } from '@/api/order'
import { Notification, Message, Modal } from '@arco-design/web-vue'
import OrderStateTag from '@/components/store/OrderStateTag.vue'
import StoreStackSkeleton from '@/components/skeleton/StoreStackSkeleton.vue'
import { getNotice } from '@/utils/util'
import { formatStoreTime, getPayTypeLabel } from '@/utils/storeFormat'

const router = useRouter()
const notice = ref('')
const data = ref([])
const loading = ref(false)
const cancelingOrderId = ref('')
const statusTab = ref('all')

const statusTabs = [
  { key: 'all', title: '全部' },
  { key: '0', title: '待支付' },
  { key: '1', title: '待处理' },
  { key: '2', title: '已完成' },
  { key: '5', title: '已退款' },
  { key: '3', title: '已关闭' }
]

const displayList = computed(() => {
  if (statusTab.value === 'all') return data.value
  const state = Number(statusTab.value)
  return data.value.filter((r) => r.state === state)
})

const goDetail = (orderId) => router.push(`/store/orderDetail/${orderId}`)

const handleCancelOrder = (record) => {
  Modal.confirm({
    title: '取消订单',
    content: `确定要取消订单 ${record.orderId} 吗？`,
    okText: '确认取消',
    cancelText: '再想想',
    okButtonProps: { status: 'danger' },
    onOk: async () => {
      try {
        cancelingOrderId.value = record.orderId
        const res = await cancelOrder({ orderId: record.orderId })
        if (!res || res.code !== 0) {
          return Notification.error({
            title: '取消订单失败',
            content: res?.msg ?? '请稍后再试'
          })
        }
        Message.success(res.msg || '订单已取消')
        await GetMyOrder()
      } catch (error) {
        Notification.error({
          title: '取消订单失败',
          content: error.message || '请稍后再试'
        })
      } finally {
        cancelingOrderId.value = ''
      }
    }
  })
}

const GetMyOrder = async () => {
  try {
    loading.value = true
    const res = await getMyOrder()
    if (!res || res.code !== 0) {
      return Notification.error({
        title: '获取订单列表失败',
        content: res?.msg ?? '请稍后再试'
      })
    }
    data.value = res.data ?? []
  } catch (error) {
    Notification.error({
      title: '获取订单列表失败',
      content: error.message || '请稍后再试'
    })
  } finally {
    loading.value = false
  }
}

const GetNotice = async () => {
  const { path } = useRoute()
  notice.value = await getNotice(path)
}

GetMyOrder()
GetNotice()
</script>

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

.page-header {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-end;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 20px;
}

.notice {
  margin-bottom: 16px;
  border-radius: @store-radius-sm;
}

.status-tabs {
  width: 100%;

  :deep(.arco-tabs-nav) {
    justify-content: center;
  }

  :deep(.arco-tabs-content) {
    width: 100%;
  }
}

.order-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  width: 100%;
}

.order-card {
  width: 100%;
  box-sizing: border-box;
  background: @store-card-bg;
  border: 1px solid @store-card-border;
  border-radius: @store-radius;
  padding: 16px 20px;
  cursor: pointer;
  transition: box-shadow 0.2s, border-color 0.2s;

  &:hover {
    box-shadow: @store-shadow;
    border-color: fade(@store-accent, 40%);
  }

  &__head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;
    padding-bottom: 12px;
    border-bottom: 1px dashed @store-card-border;
  }

  .order-id {
    font-size: 0.8rem;
    color: @store-text-muted;
    font-family: ui-monospace, monospace;
  }

  &__body {
    .goods-name {
      margin: 0 0 8px;
      font-size: 1.05rem;
      font-weight: 600;
      color: @store-primary;
    }
  }

  &__meta {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 6px;

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

    .pay-type {
      display: inline-flex;
      align-items: center;
      gap: 4px;
      font-size: 0.85rem;
      color: @store-text-muted;
    }
  }

  .time {
    font-size: 0.8rem;
    color: @store-text-muted;
  }

  &__actions {
    margin-top: 12px;
    display: flex;
    justify-content: flex-end;
    gap: 8px;
    flex-wrap: wrap;
  }
}
</style>
