<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'

// 接口类型定义
interface Order {
  orderId: number
  accountId: number
  orderTime: string
  branchId: number
  orderMoney: number
  orderRemarks?: string
  orderStatus: number
  isDeleted: number
  createdAt: string
  updatedAt: string
}

interface OrderDetail extends Order {
  orderLists: OrderListItem[]
}

interface OrderListItem {
  orderListId: number
  orderId: number
  dishId: number
  number: number
  dishName?: string
  price?: number
}

interface ApiResponse<T> {
  code: number
  message: string
  data: T
}

interface PageData<T> {
  records: T[]
  total: number
  current: number
  size: number
  pages: number
}

// 存储管理器类型
interface UserInfo {
  accountId: number
  branchId?: number
  accountName?: string
  accountType?: string
}

// 模拟StorageManager
const StorageManager = {
  getUserInfo: (): UserInfo | null => {
    const userStr = localStorage.getItem('userInfo')
    return userStr ? JSON.parse(userStr) : null
  }
}

const getAccountId = (): number | null => {
  const userInfo = StorageManager.getUserInfo()
  return userInfo ? userInfo.accountId : null
}

// 响应式数据
const loading = ref(false)
const tableData = ref<Order[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const branchId = ref<number | null>(null)

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

// 订单详情对话框
const dialogVisible = ref(false)
const orderDetail = ref<OrderDetail | null>(null)
const detailLoading = ref(false)

// 状态更新对话框
const statusDialogVisible = ref(false)
const selectedOrder = ref<Order | null>(null)
const newStatus = ref<number>(1)

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

// 订单状态映射
const statusMap = {
  1: '待处理',
  2: '已完成',
  '-1': '已取消'
}

const statusOptions = [
  { label: '全部', value: '' },
  { label: '待处理', value: '1' },
  { label: '已完成', value: '2' },
  { label: '已取消', value: '-1' }
]

// 状态标签类型
const getStatusType = (status: number) => {
  switch (status) {
    case 1: return 'warning'
    case 2: return 'success'
    case -1: return 'danger'
    default: return 'info'
  }
}

// 初始化branchId
const initBranchId = async () => {
  const accountId = getAccountId()
  if (!accountId) {
    ElMessage.error('未获取到用户信息，请重新登录')
    return
  }
  
  try {
    // 这里假设当前登录用户就是分店管理员，直接使用一个默认的branchId
    // 在实际应用中，您可能需要通过API获取当前用户管理的分店ID
    //branchId.value = 1 // 临时设置，实际应该通过API获取
    
    // 或者通过查询分店负责人接口获取branchId
    const response = await axios.get(`${BASE_API}/branch/branch/by-boss/${accountId}`)
    if (response.data.code === 200 && response.data.data.length > 0) {
      branchId.value = response.data.data[0].branchId
    }
  } catch (error) {
    console.error('获取分店信息失败:', error)
    ElMessage.error('获取分店信息失败')
  }
}

// 获取订单列表
const fetchOrders = async () => {
  if (!branchId.value) {
    await initBranchId()
    if (!branchId.value) return
  }

  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      ...(searchForm.orderStatus && { orderStatus: searchForm.orderStatus }),
      ...(searchForm.accountId && { accountId: searchForm.accountId })
    }

    const response = await axios.get<ApiResponse<PageData<Order>>>(
      `${BASE_API}/branch/orders/branch/${branchId.value}`,
      { params }
    )

    if (response.data.code === 200) {
      tableData.value = response.data.data.records
      total.value = response.data.data.total
    } else {
      ElMessage.error(response.data.message || '获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 获取订单详情
const fetchOrderDetail = async (orderId: number) => {
  detailLoading.value = true
  try {
    const response = await axios.get<ApiResponse<OrderDetail>>(
      `${BASE_API}/branch/orders/${orderId}`
    )

    if (response.data.code === 200) {
      orderDetail.value = response.data.data
      dialogVisible.value = true
    } else {
      ElMessage.error(response.data.message || '获取订单详情失败')
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  } finally {
    detailLoading.value = false
  }
}

// 更新订单状态
const updateOrderStatus = async () => {
  if (!selectedOrder.value) return

  try {
    const response = await axios.patch<ApiResponse<any>>(
      `${BASE_API}/branch/orders/${selectedOrder.value.orderId}/status`,
      { orderStatus: newStatus.value }
    )

    if (response.data.code === 200) {
      ElMessage.success('订单状态更新成功')
      statusDialogVisible.value = false
      await fetchOrders()
    } else {
      ElMessage.error(response.data.message || '更新订单状态失败')
    }
  } catch (error) {
    console.error('更新订单状态失败:', error)
    ElMessage.error('更新订单状态失败')
  }
}

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

    const response = await axios.delete<ApiResponse<any>>(
      `${BASE_API}/branch/orders/${order.orderId}`
    )

    if (response.data.code === 200) {
      ElMessage.success('订单取消成功')
      await fetchOrders()
    } else {
      ElMessage.error(response.data.message || '取消订单失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  }
}

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

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

// 分页变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchOrders()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchOrders()
}

// 打开状态更新对话框
const openStatusDialog = (order: Order) => {
  selectedOrder.value = order
  newStatus.value = order.orderStatus
  statusDialogVisible.value = true
}

// 格式化金额
const formatMoney = (money: number) => {
  return `¥${money.toFixed(2)}`
}

// 格式化时间
const formatTime = (time: string) => {
  return new Date(time).toLocaleString('zh-CN')
}

// 组件挂载时初始化
onMounted(() => {
  fetchOrders()
})
</script>

<template>
  <div class="order-management">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>订单管理</span>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="searchForm" label-width="80px" inline class="search-form">
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.orderStatus" placeholder="请选择状态" clearable>
            <el-option
              v-for="option in statusOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户ID">
          <el-input
            v-model="searchForm.accountId"
            placeholder="请输入用户ID"
            clearable
          />
        </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>

      <!-- 订单表格 -->
      <el-table
        :data="tableData"
        :loading="loading"
        style="width: 100%"
        class="order-table"
      >
        <el-table-column prop="orderId" label="订单ID" width="100" />
        <el-table-column prop="accountId" label="用户ID" width="100" />
        <el-table-column label="下单时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.orderTime) }}
          </template>
        </el-table-column>
        <el-table-column label="订单金额" width="120">
          <template #default="{ row }">
            <span class="money">{{ formatMoney(row.orderMoney) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.orderStatus)">
              {{ statusMap[row.orderStatus as keyof typeof statusMap] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="orderRemarks" label="备注" show-overflow-tooltip />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="fetchOrderDetail(row.orderId)"
            >
              详情
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="openStatusDialog(row)"
              :disabled="row.orderStatus === -1"
            >
              状态
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="cancelOrder(row)"
              :disabled="row.orderStatus !== 1"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

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

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="订单详情"
      width="70%"
      :close-on-click-modal="false"
    >
      <div v-if="orderDetail" class="order-detail">
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="订单ID">
            {{ orderDetail.orderId }}
          </el-descriptions-item>
          <el-descriptions-item label="用户ID">
            {{ orderDetail.accountId }}
          </el-descriptions-item>
          <el-descriptions-item label="下单时间">
            {{ formatTime(orderDetail.orderTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="订单金额">
            <span class="money">{{ formatMoney(orderDetail.orderMoney) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(orderDetail.orderStatus)">
              {{ statusMap[orderDetail.orderStatus as keyof typeof statusMap] }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="备注">
            {{ orderDetail.orderRemarks || '无' }}
          </el-descriptions-item>
        </el-descriptions>

        <el-divider />

        <h3>订单明细</h3>
        <el-table :data="orderDetail.orderLists" style="width: 100%">
          <el-table-column prop="dishId" label="菜品ID" width="100" />
          <el-table-column prop="dishName" label="菜品名称" />
          <el-table-column prop="number" label="数量" width="100" />
          <el-table-column label="单价" width="120">
            <template #default="{ row }">
              {{ row.price ? formatMoney(row.price) : '-' }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else-if="detailLoading" style="text-align: center; padding: 40px;">
        <el-icon class="is-loading"><Loading /></el-icon>
        <p>加载中...</p>
      </div>
    </el-dialog>

    <!-- 状态更新对话框 -->
    <el-dialog
      v-model="statusDialogVisible"
      title="更新订单状态"
      width="400px"
      :close-on-click-modal="false"
    >
      <div v-if="selectedOrder">
        <p>订单ID: {{ selectedOrder.orderId }}</p>
        <p>当前状态: 
          <el-tag :type="getStatusType(selectedOrder.orderStatus)">
            {{ statusMap[selectedOrder.orderStatus as keyof typeof statusMap] }}
          </el-tag>
        </p>
        <el-form label-width="80px" style="margin-top: 20px;">
          <el-form-item label="新状态">
            <el-select v-model="newStatus" placeholder="请选择新状态">
              <el-option label="待处理" :value="1" />
              <el-option label="已完成" :value="2" />
              <el-option label="已取消" :value="-1" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="statusDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateOrderStatus">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.order-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

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

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

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

.order-detail {
  max-height: 60vh;
  overflow-y: auto;
}

.order-detail h3 {
  margin: 20px 0 10px 0;
  color: #303133;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-form {
    padding: 15px;
  }
  
  .search-form .el-form-item {
    margin-bottom: 10px;
  }
  
  .order-table {
    font-size: 12px;
  }
  
  .el-dialog {
    margin: 0 5% !important;
    width: 90% !important;
  }
}

/* 加载状态样式 */
.is-loading {
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>