<template>
  <div class="pending-orders">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span>待办订单</span>
            <el-tag type="success" effect="dark" class="branch-tag">{{ branch.branchName }}</el-tag>
          </div>
          <div class="header-right">
            <el-button type="primary" @click="handleRefresh">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="订单状态">
            <el-select
              v-model="searchForm.orderStatus"
              placeholder="请选择订单状态"
              clearable
              style="width: 150px"
            >
              <el-option label="未完成" :value="0" />
              <el-option label="已完成" :value="1" />
              <el-option label="已退款" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="用户账号">
            <el-input
              v-model="searchForm.accountId"
              placeholder="请输入用户账号"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table :data="tableData" style="width: 100%" v-loading="loading" border stripe>
        <el-table-column prop="orderId" label="订单号" width="100" align="center" />
        <el-table-column prop="accountId" label="用户账号" width="120" align="center" />
        <el-table-column prop="orderTime" label="下单时间" width="180" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.orderTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="orderMoney" label="订单金额" width="120" align="center">
          <template #default="scope">
            <span class="price">￥{{ scope.row.orderMoney.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="orderRemarks" label="备注" min-width="150" show-overflow-tooltip />
        <el-table-column prop="orderStatus" label="订单状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getOrderStatusType(scope.row.orderStatus)">
              {{ getOrderStatusText(scope.row.orderStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)" type="primary" link>
              详情
            </el-button>
            <el-button
              v-if="scope.row.orderStatus === 0"
              size="small"
              @click="handleComplete(scope.row)"
              type="success"
              link
            >
              完成
            </el-button>
            <el-button
              v-if="scope.row.orderStatus === 0"
              size="small"
              @click="handleRefund(scope.row)"
              type="danger"
              link
            >
              退款
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[5, 10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="订单详情" width="700px">
      <div v-if="currentOrder" class="order-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ currentOrder.orderId }}</el-descriptions-item>
          <el-descriptions-item label="用户账号">{{ currentOrder.accountId }}</el-descriptions-item>
          <el-descriptions-item label="下单时间">{{
            formatDateTime(currentOrder.orderTime)
          }}</el-descriptions-item>
          <el-descriptions-item label="订单金额"
            >￥{{ currentOrder.orderMoney.toFixed(2) }}</el-descriptions-item
          >
          <el-descriptions-item label="订单状态">
            <el-tag :type="getOrderStatusType(currentOrder.orderStatus)">
              {{ getOrderStatusText(currentOrder.orderStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="店铺名称">{{
            currentOrder.branchName
          }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ currentOrder.orderRemarks || '无备注' }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 订单明细 -->
        <div class="order-items">
          <h3>订单明细</h3>
          <el-table :data="currentOrder.orderItems || []" border stripe style="width: 100%">
            <el-table-column prop="dishName" label="菜品名称" min-width="150" />
            <el-table-column prop="price" label="单价" width="100" align="center">
              <template #default="scope">
                <span class="price">￥{{ scope.row.price.toFixed(2) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="number" label="数量" width="80" align="center" />
            <el-table-column label="小计" width="120" align="center">
              <template #default="scope">
                <span class="price">￥{{ (scope.row.price * scope.row.number).toFixed(2) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import axios from 'axios'

// 接口类型定义
interface OrderItem {
  orderListId: number
  orderId: number
  number: number
  dishId: number
  dishName: string
  price: number
}

interface Order {
  orderId: number
  accountId: string
  orderTime: string
  branchId: number
  orderMoney: number
  orderRemarks: string
  isDeleted: number
  orderStatus: number
  branchName: string
  orderItems?: OrderItem[]
}

interface SearchForm {
  orderStatus: number | null
  accountId: string
}

interface Pagination {
  currentPage: number
  pageSize: number
  total: number
}

// 响应式数据
const loading = ref(false)
const tableData = ref<Order[]>([])
const detailDialogVisible = ref(false)
const currentOrder = ref<Order | null>(null)

// 搜索表单
const searchForm = reactive<SearchForm>({
  orderStatus: null,
  accountId: '',
})

// 分页数据
const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
})

// 当前店铺信息
const branch = reactive({
  branchId: 1,
  branchName: '北京三里屯店',
})

// API 基础URL
const API_BASE_URL = 'http://localhost:8080/api'

// 获取订单列表
const fetchOrders = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      orderStatus: searchForm.orderStatus,
      accountId: searchForm.accountId,
    }

    // 使用店铺ID查询订单
    const response = await axios.get(`${API_BASE_URL}/orders/branch/${branch.branchId}`, {
      params,
    })
    tableData.value = response.data.data.records
    pagination.total = response.data.data.total
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 获取订单详情
const fetchOrderDetail = async (orderId: number) => {
  try {
    const response = await axios.get(`${API_BASE_URL}/orders/${orderId}`)
    return response.data.data
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
    return null
  }
}

// 格式化日期时间
const formatDateTime = (dateStr: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

// 获取订单状态文本
const getOrderStatusText = (status: number) => {
  switch (status) {
    case 0:
      return '未完成'
    case 1:
      return '已完成'
    case 2:
      return '已退款'
    default:
      return '未知状态'
  }
}

// 获取订单状态对应的标签类型
const getOrderStatusType = (status: number) => {
  switch (status) {
    case 0:
      return 'warning' // 未完成
    case 1:
      return 'success' // 已完成
    case 2:
      return 'danger' // 已退款
    default:
      return 'info'
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchOrders()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    orderStatus: null,
    accountId: '',
  })
  pagination.currentPage = 1
  fetchOrders()
}

// 刷新数据
const handleRefresh = () => {
  fetchOrders()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchOrders()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchOrders()
}

// 查看订单详情
const handleView = async (order: Order) => {
  const orderDetail = await fetchOrderDetail(order.orderId)
  if (orderDetail) {
    currentOrder.value = orderDetail
    detailDialogVisible.value = true
  }
}

// 完成订单
const handleComplete = async (order: Order) => {
  try {
    await ElMessageBox.confirm(`确定要将订单 #${order.orderId} 标记为已完成吗？`, {
      title: '完成确认',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success',
    })

    // 调用更新订单状态API
    await axios.patch(`${API_BASE_URL}/orders/${order.orderId}/status`, {
      orderStatus: 1, // 已完成
    })
    ElMessage.success('订单已标记为完成')
    fetchOrders()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('完成订单失败:', error)
      ElMessage.error('完成订单失败')
    }
  }
}

// 退款订单
const handleRefund = async (order: Order) => {
  try {
    await ElMessageBox.confirm(`确定要将订单 #${order.orderId} 退款吗？`, {
      title: '退款确认',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    // 调用更新订单状态API
    await axios.patch(`${API_BASE_URL}/orders/${order.orderId}/status`, {
      orderStatus: 2, // 已退款
    })
    ElMessage.success('订单已退款')
    fetchOrders()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('退款操作失败:', error)
      ElMessage.error('退款操作失败')
    }
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.pending-orders {
  padding: 0px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
}

.branch-tag {
  margin-left: 10px;
}

.search-bar {
  margin-bottom: 5px;
}

.search-form {
  background: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-wrapper {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}

.order-detail {
  margin-bottom: 10px;
}

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

.order-items h3 {
  margin-bottom: 10px;
}
</style>
