<template>
  <div class="admin-order-detail">
    <Breadcrumb />
    <a-skeleton animation :loading="loading" style="width: 100%">
      <StoreDetailSkeleton variant="order" />
      <template #content>
        <div v-if="data.orderId" class="detail-grid">
        <a-card :bordered="false" class="detail-card detail-card--status">
          <template #title>订单进度</template>
          <OrderProgressSteps
            class="order-steps"
            :mobile="isMobile"
            :current="stepCurrent"
            :status="stepStatus"
            :labels="adminStepLabels"
            :descriptions="adminStepDescriptions"
          />
          <div class="state-center">
            <a-tag :color="stateMeta.color" size="large">{{ stateMeta.label }}</a-tag>
          </div>
        </a-card>

        <OrderRefundPanel
          v-if="data.state === 2 && (data.canRefund || data.refundDisabledReason)"
          class="refund-panel-wrap"
          :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="admin"
          @refund="handleRefundOrder"
        />

        <a-card :bordered="false" class="detail-card">
          <template #title>订单信息</template>
          <a-descriptions :column="{ xs: 1, sm: 2 }" bordered>
            <a-descriptions-item label="订单号">{{ data.orderId }}</a-descriptions-item>
            <a-descriptions-item label="商品">{{ data.name || '-' }}</a-descriptions-item>
            <a-descriptions-item v-if="data.original_price" label="商品原价">
              ¥{{ data.original_price }}
            </a-descriptions-item>
            <a-descriptions-item v-if="data.coupon_code" label="优惠码">
              {{ data.coupon_code }}
            </a-descriptions-item>
            <a-descriptions-item v-if="data.discount_amount > 0" label="优惠减免">
              ¥{{ data.discount_amount }}
            </a-descriptions-item>
            <a-descriptions-item label="实付金额">
              <span class="price">¥{{ data.price }}</span>
            </a-descriptions-item>
            <a-descriptions-item label="支付方式">{{ getPayTypeLabel(data.pay_type) }}</a-descriptions-item>
            <a-descriptions-item label="下单时间">{{ formatStoreTimeFull(data.create_time) }}</a-descriptions-item>
            <a-descriptions-item label="支付时间">{{ formatStoreTimeFull(data.pay_time) }}</a-descriptions-item>
            <a-descriptions-item v-if="data.pay_id" label="支付平台单号" :span="isMobile ? 1 : 2">
              {{ data.pay_id }}
            </a-descriptions-item>
            <a-descriptions-item v-if="data.lepao_count != null" label="乐跑次数">
              {{ data.lepao_count }}
            </a-descriptions-item>
            <a-descriptions-item v-if="data.ic_count != null" label="IC次数">
              {{ data.ic_count }}
            </a-descriptions-item>
            <a-descriptions-item v-if="data.user_lepao_count != null" label="用户当前次数">
              {{ data.user_lepao_count }}
            </a-descriptions-item>
          </a-descriptions>
        </a-card>

        <a-card :bordered="false" class="detail-card">
          <template #title>买家信息</template>
          <a-descriptions :column="{ xs: 1, sm: 2 }" bordered>
            <a-descriptions-item label="用户名">{{ data.username || '-' }}</a-descriptions-item>
            <a-descriptions-item label="邮箱">{{ data.user_email || '-' }}</a-descriptions-item>
            <a-descriptions-item label="用户 UUID" :span="isMobile ? 1 : 2">{{ data.create_user || '-' }}</a-descriptions-item>
          </a-descriptions>
        </a-card>

        <a-card v-if="goodsContent" :bordered="false" class="detail-card detail-card--full">
          <template #title>商品详情</template>
          <div class="goods-content" v-html="goodsContent" />
        </a-card>

        </div>
      </template>
    </a-skeleton>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import { adminOrderDetail, adminRefundOrder } from '@/api/order'
import { Notification, Message, Modal } from '@arco-design/web-vue'
import OrderProgressSteps from '@/components/store/OrderProgressSteps.vue'
import StoreDetailSkeleton from '@/components/skeleton/StoreDetailSkeleton.vue'
import OrderRefundPanel from '@/components/store/OrderRefundPanel.vue'
import {
  formatStoreTimeFull,
  getPayTypeLabel,
  getOrderStateMeta,
  decodeGoodsContent
} from '@/utils/storeFormat'

const route = useRoute()
const loading = ref(true)
const refundLoading = ref(false)
const data = ref({})
const goodsContent = ref('')
const isMobile = ref(false)
let resizeHandler = null

const adminStepLabels = ['待支付', '待处理', '已完成']
const adminStepDescriptions = computed(() =>
  isMobile.value
    ? ['', '', '']
    : ['用户提交订单', '支付成功，系统处理', '权益已发放']
)

const stateMeta = computed(() => getOrderStateMeta(data.value?.state ?? -1))

const stepCurrent = computed(() => {
  const state = data.value?.state
  if (state === 0 || state === 3) return 1
  if (state === 1) return 2
  if (state === 2 || state === 4 || state === 5) return 3
  return 1
})

const stepStatus = computed(() => {
  const state = data.value?.state
  if (state === 3 || state === 4) return 'error'
  if (state === 2 || state === 5) return 'finish'
  return 'process'
})

const fetchDetail = async () => {
  try {
    loading.value = true
    const res = await adminOrderDetail({ orderId: route.params.orderId })
    if (!res || res.code !== 0) {
      return Notification.error({
        title: '获取订单详情失败',
        content: res?.msg ?? '请稍后再试'
      })
    }
    data.value = res.data || {}
    goodsContent.value = decodeGoodsContent(res.data?.content)
  } catch (error) {
    Notification.error({
      title: '获取订单详情失败',
      content: error.message || '请稍后再试'
    })
  } finally {
    loading.value = false
  }
}

const handleRefundOrder = () => {
  const purchased = data.value?.lepao_count ?? 0
  const remaining = data.value?.user_lepao_count ?? 0
  Modal.confirm({
    title: '管理员退款',
    content: `将为用户退款 ¥${data.value?.price}，并扣回 ${purchased} 次乐跑次数（用户当前剩余 ${remaining} 次）。确定继续吗？`,
    okText: '确认退款',
    cancelText: '取消',
    okButtonProps: { status: 'warning' },
    onOk: async () => {
      try {
        refundLoading.value = true
        const res = await adminRefundOrder({ orderId: route.params.orderId })
        if (!res || res.code !== 0) {
          Notification.error({
            title: '退款失败',
            content: res?.msg ?? '请稍后再试'
          })
          return
        }
        Message.success(res.msg || '退款成功')
        await fetchDetail()
      } catch (error) {
        Notification.error({
          title: '退款失败',
          content: error.message || '请稍后再试'
        })
      } finally {
        refundLoading.value = false
      }
    }
  })
}

onMounted(async () => {
  const syncMobile = () => {
    isMobile.value = window.innerWidth <= 768
  }
  resizeHandler = syncMobile
  syncMobile()
  window.addEventListener('resize', resizeHandler)
  await fetchDetail()
})

onUnmounted(() => {
  if (resizeHandler) window.removeEventListener('resize', resizeHandler)
})
</script>

<style scoped lang="less">
.admin-order-detail {
  padding: 0 20px 20px;
}

.detail-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;

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

  @media (min-width: 960px) {
    grid-template-columns: 1fr 1fr;

    .detail-card--status,
    .detail-card--full,
    .refund-panel-wrap {
      grid-column: 1 / -1;
    }
  }
}

.detail-card {
  border-radius: 12px;
  border: 1px solid var(--color-border-2);
}

.state-center {
  margin-top: 20px;
  text-align: center;
}

.price {
  font-weight: 700;
  color: #e85d04;
}

.goods-content {
  line-height: 1.75;

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

@media (max-width: 768px) {
  .admin-order-detail {
    padding: 0 12px 16px;
  }

  :deep(.arco-descriptions-item-value) {
    white-space: normal;
    word-break: break-all;
    overflow-wrap: anywhere;
  }
}
</style>
