<template>
  <div class="dingdan-container">
    <el-page-header content="历史订单" />
    <!-- 订单列表 -->
    <div class="order-list" v-if="orders.length > 0">
      <el-card
        class="order-item"
        v-for="(order, index) in orders"
        :key="index"
        shadow="hover"
        @click="showOrderDetails(order)"
        style="
          margin-bottom: 16px;
          cursor: pointer;
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <div>
          <div>订单号: {{ order.orderId }}</div>
          <div>创建时间: {{ order.orderTime }}</div>
          <div>金额: ¥{{ order.orderMoney ? order.orderMoney.toFixed(2) : '0.00' }}</div>
        </div>
        <div style="font-weight: bold; color: #409eff; min-width: 80px; text-align: right">
          {{ getOrderStatusText(order.orderStatus) }}
        </div>
      </el-card>
    </div>

    <div v-else>
      <el-empty description="暂无订单信息" />
    </div>

    <!-- 使用 Element Plus Dialog 作为弹窗 -->
    <el-dialog v-model="showModal" width="600px" :before-close="hideOrderDetails" title="订单详情">
      <div class="order-header" style="margin-bottom: 12px">
        <div>订单号: {{ selectedOrder?.orderId }}</div>
        <div>创建时间: {{ selectedOrder?.orderTime }}</div>
      </div>

      <div class="order-item-list">
        <div
          class="order-item"
          v-for="item in selectedOrder?.items || []"
          :key="item.orderListId"
          style="
            display: flex;
            gap: 12px;
            padding: 12px;
            border: 1px solid #ebeef5;
            border-radius: 8px;
            margin-bottom: 12px;
            background-color: #fafafa;
          "
        >
          <el-image
            v-if="item.dishDetail?.imageUrl"
            :src="item.dishDetail.imageUrl"
            fit="cover"
            style="width: 80px; height: 80px; border-radius: 6px"
            alt="菜品图片"
          />
          <div style="flex: 1">
            <div style="font-weight: bold; font-size: 16px">
              {{ item.dishDetail?.dishName || '未知菜品' }}
            </div>
            <div style="margin-top: 4px; color: #666">
              单价：¥{{ item.dishDetail?.price?.toFixed(2) || '0.00' }}<br />
              数量：{{ item.number }}<br />
              小计：¥{{
                item.dishDetail && item.dishDetail.price
                  ? (item.dishDetail.price * item.number).toFixed(2)
                  : '0.00'
              }}
            </div>
          </div>
        </div>
      </div>

      <div class="order-total" style="font-weight: bold; font-size: 16px">
        总计：¥{{ selectedOrder?.orderMoney?.toFixed(2) || '0.00' }}
      </div>

      <template #footer>
        <el-button @click="hideOrderDetails">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { useUserStore } from '@/userStores/user'

interface OrderListItem {
  orderListId: number
  orderId: number
  dishId: number
  number: number
  dishDetail?: Dish | null
}

interface Order {
  orderId: number
  accountId?: number
  orderTime: string
  branchId?: number
  orderMoney: number
  orderRemarks?: string
  isDeleted?: boolean
  deletedAt?: string | null
  createdAt?: string
  updatedAt?: string
  orderStatus?: number
  items: OrderListItem[]
}

interface Dish {
  dishId: number
  dishName: string
  category?: string
  price?: number
  stock?: number
  status?: string
  description?: string
  imageUrl?: string
  sales?: number
  createdAt?: string
  updatedAt?: string
  tag?: string
  isDeleted?: number
  deletedAt?: string
}
const getOrderStatusText = (status: number | undefined): string => {
  switch (status) {
    case -1:
      return '已取消'
    case 1:
      return '待处理'
    case 2:
      return '已完成'
    default:
      return '未知状态'
  }
}

const getOrderStatusType = (status: number | undefined): string => {
  switch (status) {
    case -1:
      return 'danger'
    case 1:
      return 'warning'
    case 2:
      return 'success'
    default:
      return 'info'
  }
}

const orders = ref<Order[]>([])
const showModal = ref(false)
const selectedOrder = ref<Order | null>(null)

const userStore = useUserStore()

onMounted(async () => {
  const userId = userStore.getUserId
  if (!userId) return

  try {
    const response = await axios.get<Order[]>(`http://localhost:8080/user/orders/user/${userId}`) //ok
    orders.value = response.data
  } catch (error) {
    console.error('获取订单失败:', error)
  }
})

const showOrderDetails = async (order: Order) => {
  showModal.value = true

  try {
    // 第一步：获取订单明细
    const detailResponse = await axios.get(`http://localhost:8080/branch/orders/${order.orderId}`)
    if (detailResponse.data.code !== 200) {
      console.error('订单详情查询失败:', detailResponse.data.message)
      selectedOrder.value = { ...order, items: [] }
      return
    }

    const fullOrder = detailResponse.data.data
    const itemsFromBackend = fullOrder.orderLists ?? []

    // 第二步：提取 dishIds 并获取菜品详情
    const dishIds = itemsFromBackend.map((item: any) => item.dishId)
    const dishResponse = await axios.post<Dish[]>(
      'http://localhost:8080/user/dishes/batch',
      dishIds,
    )
    const dishes = dishResponse.data

    // 第三步：组装 order.items 并补全 dishDetail
    const itemsWithDetails: OrderListItem[] = itemsFromBackend.map((item: any) => ({
      orderListId: item.orderListId,
      orderId: item.orderId,
      dishId: item.dishId,
      number: item.number,
      dishDetail: dishes.find((d) => d.dishId === item.dishId) ?? null,
    }))

    selectedOrder.value = {
      ...order,
      items: itemsWithDetails,
    }
  } catch (error) {
    console.error('查看订单详情失败:', error)
    selectedOrder.value = { ...order, items: [] }
  }
}

const hideOrderDetails = () => {
  showModal.value = false
}
</script>

<style scoped>
.dingdan-container {
  font-size: 20px;
  font-weight: 600;
  margin: 0 auto 24px auto; /* 上右下左，自动水平居中 */
  max-width: 800px; /* 限制最大宽度，比如800px */
  padding: 0 16px; /* 保证左右内边距 */
  color: #333;
}

.title {
  text-align: center;
  margin-bottom: 30px;
}

.order-list {
  display: grid;
  gap: 20px;
}

.order-item {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: background-color 0.3s;
}

.order-item:hover {
  background-color: #f0f0f0;
}

.order-id,
.order-time,
.order-total {
  color: #606266;
  margin-bottom: 5px;
}

.no-order {
  text-align: center;
  padding: 50px 0;
}

.order-details-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  width: 80%;
  max-width: 600px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
}

.order-info {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.order-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e0e0e0;
}

.order-id,
.order-time {
  color: #606266;
}

.order-items {
  margin-bottom: 20px;
}

.order-items h3 {
  margin-top: 0;
}

.item-list {
  display: grid;
  gap: 10px;
}

.item {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px dashed #e0e0e0;
}

.item:last-child {
  border-bottom: none;
}

.order-total {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 15px 0;
  border-top: 1px solid #e0e0e0;
  font-weight: bold;
}

.order-total span {
  font-size: 18px;
}

.total-price {
  color: #f56c6c;
  margin-left: 10px;
}
</style>
