<template>
  <div class="order-manage-container">
    <div class="page-title"><i class="title-bar"></i><span>订单管理</span></div>
    <!-- 搜索栏 -->
    <div class="flex-row-between">
      <div class="flex-row-start">
        <el-input v-model="queryParams.keyword" placeholder="搜索订单号" style="width: 260px" clearable @keyup.enter="handleQuery">
          <template #prefix
            ><el-icon><Search /></el-icon
          ></template>
        </el-input>
        <el-date-picker
          v-model="queryParams.dateRange"
          type="daterange"
          range-separator="—"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 260px; margin-left: 10px"
        />
      </div>
      <div>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </div>
    <div class="flex-row-between" style="margin-top: 10px">
      <div class="flex-row-start">
        <el-tree-select
          v-model="queryParams.department"
          style="width: 160px"
          :data="deptList"
          :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
          value-key="deptId"
          placeholder="下单部门"
          check-strictly
          :render-after-expand="false"
          clearable
        >
        </el-tree-select>
        <el-select v-model="queryParams.status" placeholder="状态" style="width: 160px; margin-left: 10px" clearable>
          <el-option v-for="dict in order_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
        <el-select v-model="queryParams.payType" placeholder="支付方式" style="width: 160px; margin-left: 10px" clearable
          ><el-option v-for="dict in pay_method" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </div>
      <div class="flex-row-start">
        <el-dropdown>
          <el-button
            >订单导出 <el-icon><ArrowDown /></el-icon
          ></el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>导出Excel</el-dropdown-item>
              <el-dropdown-item>导出PDF</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-dropdown style="margin-left: 10px">
          <el-button
            >订单打印 <el-icon><ArrowDown /></el-icon
          ></el-button>
          <template #dropdown
            ><el-dropdown-menu
              ><el-dropdown-item>打印订单</el-dropdown-item><el-dropdown-item>打印发货单</el-dropdown-item></el-dropdown-menu
            ></template
          >
        </el-dropdown>
        <el-button style="margin-left: 10px">下载电子签单</el-button>
      </div>
    </div>
    <!-- Tab切换 -->
    <div class="tab-bar">
      <div class="tab-left">
        <div v-for="tab in statusTabs" :key="tab.key" :class="['tab-item', { active: activeTab === tab.key }]" @click="activeTab = tab.key">
          <el-icon><component :is="tab.icon" /></el-icon><span>{{ tab.label }}</span>
        </div>
      </div>
      <el-button type="danger" link
        ><el-icon><Delete /></el-icon>订单回收站</el-button
      >
    </div>
    <!-- 订单列表 -->
    <div class="order-list">
      <div v-for="order in orderList" :key="order.id" class="order-card">
        <div class="order-header flex-row-between">
          <div class="flex-row-start" style="gap: 0 15px">
            <el-checkbox style="margin: 2px 0px 0px 0" v-model="order.checked" @change="handleOrderCheck" />
            <div>{{ formatOrderTime(order.orderTime) }}</div>
            <div>订单号：{{ order.orderNo }}</div>
            <div>下单人：{{ order.orderPerson }}</div>
            <div>部门：{{ order.department }}</div>
          </div>
          <div class="flex-row-start">
            <div class="expand-btn" v-for="action in getOrderActions(order)" :key="action" @click="handleAction(action, order)">{{ action }}</div>
            <div class="open-btn" v-if="order.products && order.products.length > 5" @click="handleExpand(order)">
              <span style="margin-right: 5px"> {{ order.expanded ? '收起' : '展开' }}</span>
              <el-icon v-if="order.expanded"><ArrowUp /></el-icon>
              <el-icon v-else><ArrowDown /></el-icon>
            </div>
          </div>
        </div>
        <div v-if="order.countdown" class="countdown-bar">订单锁定剩余时间：{{ order.countdown }}</div>
        <div class="product-list">
          <div v-for="(item, itemIndex) in order.expanded ? order.products : order.products.slice(0, 5)" :key="itemIndex" class="product-row">
            <div class="product-info-cell">
              <div class="product-image">
                <el-image :src="item.image" fit="contain"
                  ><template #error
                    ><div class="image-placeholder">
                      <el-icon :size="30" color="#ccc"><Picture /></el-icon></div></template
                ></el-image>
              </div>
              <div class="product-detail">
                <div class="product-name ellipsis">{{ item.name }}</div>
                <div class="product-spec">{{ item.spec1 }} | {{ item.spec2 }}</div>
                <div class="product-price">¥{{ item.price }}</div>
                <el-button size="small" @click="handleAddCart(item)">加入购物车</el-button>
              </div>
              <div class="product-quantity">x{{ item.quantity }}</div>
            </div>
            <div class="amount-cell" v-if="itemIndex === 0">
              <div class="amount-info">
                <span class="label">支付款：</span><span class="value highlight">¥{{ order.payAmount }}</span>
              </div>
              <div class="amount-info">
                <span class="label">含运费：</span><span class="value">¥{{ order.freight }}</span>
              </div>
            </div>
            <div class="status-cell" v-if="itemIndex === 0">
              <span class="status-text" :style="{ color: getStatusColor(order.status) }">{{ order.statusText }}</span>
              <span v-if="order.auditStatus" :class="['audit-status', getAuditStatusClass(order.auditStatus)]">{{
                order.auditStatus == '0' ? '待审批' : order.auditStatus == '1' ? '' : '审批驳回'
              }}</span>
              <!-- <el-button type="primary" link size="small" @click="handleViewDetail(order)">查看订单轨迹</el-button> -->
              <el-button v-if="order.fileCount" type="primary" link size="small">审核文件({{ order.fileCount }})</el-button>
            </div>
            <div v-else style="width: 340px"></div>
            <!-- <div class="product-cell action-cell" v-if="itemIndex === 0">
              <el-button
                v-for="action in getOrderActions(order)"
                :key="action"
                type="primary"
                link
                size="small"
                @click="handleAction(action, order)"
                >{{ action }}</el-button
              >
            </div> -->
          </div>
        </div>
        <!-- 显示更多商品提示 -->
        <div
          v-if="!order.expanded && order.products && order.products.length > 5"
          class="more-products-hint"
          @click="handleExpand(order)"
          style="cursor: pointer"
        >
          该订单共 {{ order.products.length }} 件商品，点击展开查看全部
        </div>
      </div>
      <el-empty v-if="orderList.length === 0" description="暂无订单" />
    </div>
    <!-- 底部操作栏 -->
    <div class="bottom-bar">
      <div class="bottom-left"><el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox></div>
      <div class="bottom-right">
        <span class="selected-info"
          >已勾选 <em>{{ selectedCount }}</em
          >/{{ totalOrders }}个订单 共计<em>¥{{ selectedAmount }}</em></span
        >
        <el-button @click="copyOrderNo">复制订单号</el-button>
        <el-dropdown
          ><el-button
            >批量订单打印 <el-icon><ArrowDown /></el-icon></el-button
          ><template #dropdown
            ><el-dropdown-menu
              ><el-dropdown-item>打印订单</el-dropdown-item><el-dropdown-item>打印发货单</el-dropdown-item></el-dropdown-menu
            ></template
          ></el-dropdown
        >
        <el-button type="danger" @click="batchConfirmationBtn">批量确认收货</el-button>
      </div>
    </div>
    <!-- 分页 -->
    <TablePagination v-model:page="queryParams.pageNum" v-model:page-size="queryParams.pageSize" :total="total" @change="fetchOrderList" />

    <el-dialog v-model="evaluateDialogVisible" :title="evaluateDialogTitle" width="600px">
      <div class="evaluate-product">
        <div class="product-image">
          <el-image :src="currentProduct?.image" fit="contain">
            <template #error
              ><div class="image-placeholder">
                <el-icon :size="30" color="#ccc"><Picture /></el-icon></div
            ></template>
          </el-image>
        </div>
        <div class="product-info">
          <div class="product-name">{{ currentProduct?.name }}</div>
          <div class="product-spec">{{ currentProduct?.spec1 }} {{ currentProduct?.spec2 }}</div>
        </div>
      </div>
      <el-form ref="evaluateFormRef" :model="evaluateForm" :rules="evaluateRules" label-width="80px">
        <el-form-item label="商品评分" prop="deliverGoods">
          <el-rate v-model="evaluateForm.deliverGoods" :colors="['#e60012', '#e60012', '#e60012']" />
        </el-form-item>
        <el-form-item label="评价内容" prop="content">
          <el-input v-model="evaluateForm.content" type="textarea" :rows="4" placeholder="请输入评价内容" maxlength="200" show-word-limit />
        </el-form-item>
        <el-form-item label="上传图片">
          <el-upload action="#" list-type="picture-card" :auto-upload="false" :limit="5">
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="evaluateDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleSubmitEvaluate">提交评价</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { Search, ArrowDown, Delete, Document, Clock, Box, CircleCheck, CircleClose, Picture } from '@element-plus/icons-vue';
import type { CheckboxValueType } from 'element-plus';
import { TablePagination } from '@/components';
import {
  getOrderList,
  getOrderStatusStats,
  getOrderProducts,
  cancelOrder,
  deleteOrder,
  batchConfirmation,
  addOrderEvaluation
} from '@/api/pc/enterprise/order';
import type { OrderMain, OrderStatusStats } from '@/api/pc/enterprise/orderTypes';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getDeptTree } from '@/api/pc/organization';
import { DeptInfo } from '@/api/pc/organization/types';
import { addProductShoppingCart } from '@/api/goods/index';
import { onPath } from '@/utils/siteConfig';
import { parseTime } from '@/utils/ruoyi';

// 格式化订单时间
const formatOrderTime = (timeStr: string) => {
  if (!timeStr) return '';
  try {
    // 处理后端返回的中文时间格式 "2026/3/13 上午3:35"
    const date = new Date(timeStr);
    if (isNaN(date.getTime())) return timeStr;
    return parseTime(date, '{y}-{m}-{d} {h}:{i}:{s}');
  } catch (e) {
    return timeStr;
  }
};

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { order_status, pay_method } = toRefs<any>(proxy?.useDict('order_status', 'pay_method'));

const router = useRouter();
const activeTab = ref('all');
const selectAll = ref(false);
const loading = ref(false);

const evaluateDialogVisible = ref(false);
const evaluateDialogTitle = ref('商品评价');
const evaluateFormRef = ref();
const currentProduct = ref<any>(null);
const currentOrder = ref<any>(null);

const evaluateForm = reactive({ deliverGoods: 5, content: '', evaluationType: null });
const evaluateRules = {
  deliverGoods: [{ required: true, message: '请选择评分', trigger: 'change' }],
  content: [{ required: true, message: '请输入评价内容', trigger: 'blur' }]
};
const deptList = ref([]);

const statusTabs = [
  { key: 'all', label: '全部订单', icon: Document },
  { key: 'preOrder', label: '预下单', icon: Clock },
  { key: 'shipping', label: '待收货', icon: Box },
  { key: 'completed', label: '已完成', icon: CircleCheck },
  { key: 'cancelled', label: '已取消', icon: CircleClose }
];

// 监听标签页切换，重置页码并重新获取数据
watch(activeTab, (newTab) => {
  queryParams.pageNum = 1;
  // 根据标签页设置后端查询的状态参数
  if (newTab === 'all') {
    queryParams.status = '';
  } else {
    // 将前端标签页key映射回后端状态值
    const tabToStatusMap: Record<string, string> = {
      'preOrder': '0', // 待支付
      'shipping': '4', // 待发货,部分发货,发货完成
      'completed': '5', // 已完成
      'cancelled': '7' // 已关闭,已取消
    };
    queryParams.status = tabToStatusMap[newTab] || '';
  }
  fetchOrderList();
});

const queryParams = reactive({ keyword: '', dateRange: [], department: '', status: '', payType: '', pageNum: 1, pageSize: 5 });
const total = ref(0);
const allOrders = ref<any[]>([]);

// 将后端状态映射为前端标签页key
const mapBackendStatusToTabKey = (backendStatus: string) => {
  const statusMap: Record<string, string> = {
    '0': 'preOrder', // 待支付
    '1': 'preOrder', // 待确认
    '2': 'shipping', // 待发货
    '3': 'shipping', // 部分发货
    '4': 'shipping', // 发货完成
    '5': 'completed', // 已完成
    '6': 'cancelled', // 已关闭
    '7': 'cancelled' // 已取消
  };
  return statusMap[backendStatus] || backendStatus;
};

// 根据订单状态获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    '0': '待支付',
    '1': '待确认',
    '2': '待发货',
    '3': '部分发货',
    '4': '发货完成',
    '5': '已完成',
    '6': '已关闭',
    '7': '已取消'
  };
  return statusMap[status] || status;
};

// 加载部门树
const loadDeptTree = async () => {
  try {
    const res = await getDeptTree();
    if (res.code === 200 && res.data) {
      deptList.value = res.data;

      if (Array.isArray(res.data)) {
        const treeData = proxy?.handleTree<DeptInfo>(res.data, 'deptId', 'parentId');
        deptList.value = treeData || res.data;
      } else {
        deptList.value = [];
      }
    }
  } catch (error) {
    console.error('获取部门树失败:', error);
    ElMessage.error('获取部门树失败');
  }
};

/** 单个加入购物车 */
const handleAddCart = async (item: any) => {
  addProductShoppingCart({ productId: item.id, productNum: 1 }).then((res: any) => {
    if (res.code == 200) {
      ElMessage.success('已加入购物车');
    }
  });
};

/** 单个加入购物车 */
const handleAddCartBatch = async (order: any) => {
  const res = await getOrderProducts([order.id]);
  if (res.code === 200 && res.rows) {
    const products = res.rows.map((p: any) => ({
      productId: p.productId,
      productNum: p.orderQuantity || 0
    }));

    const promises = products.map((item) => addProductShoppingCart({ productId: item.productId, productNum: item.productNum }));
    Promise.all(promises).then(() => {
      ElMessage.success(`已将${products.length}件商品加入购物车`);
    });
  }
};
const formatDate = (date: Date | string | number): string => {
  if (!date) return '';
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};
// 获取订单列表
const fetchOrderList = async () => {
  loading.value = true;
  try {
    const params: any = {
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize
    };

    // 添加筛选条件
    if (queryParams.keyword) params.orderNo = queryParams.keyword;
    if (queryParams.department) params.createDept = queryParams.department;
    if (queryParams.status) params.orderStatuses = queryParams.status; // 使用orderStatuses支持多状态查询
    if (queryParams.payType) params.payType = queryParams.payType;
    if (queryParams.dateRange && queryParams.dateRange.length == 2) {
      // params.beginTime = queryParams.dateRange[0];
      // params.endTime = queryParams.dateRange[1];
      params.params = {
        beginTime: formatDate(queryParams.dateRange[0]), // 将日期转换为字符串格式
        endTime: formatDate(queryParams.dateRange[1]) // 将日期转换为字符串格式
      };
    }

    console.log('发送到后端的参数:', params);
    const res = await getOrderList(params);
    console.log('后端返回的数据:', res);
    if (res.code === 200) {
      // 调试：打印后端返回的第一条订单数据
      if (res.rows && res.rows.length > 0) {
        console.log('后端���回的订单状态值:', res.rows[0].orderStatus);
        console.log('完整的订单数据:', res.rows[0]);
      }

      // 获取订单商品数据
      const orderProductsMap: Record<number, any[]> = {};
      const orderIds = (res.rows || []).map((o: any) => o.id);
      if (orderIds.length > 0) {
        try {
          const prodRes = await getOrderProducts(orderIds);
          if (prodRes.code === 200 && prodRes.rows) {
            prodRes.rows.forEach((p: any) => {
              if (!orderProductsMap[p.orderId]) {
                orderProductsMap[p.orderId] = [];
              }
              orderProductsMap[p.orderId].push({
                id: p.id,
                productId: p.productId,
                image: p.productImage || '',
                name: p.productName || '',
                spec1: p.productUnit || '',
                spec2: p.productNo || '',
                price: p.orderPrice || 0,
                quantity: p.orderQuantity || 0
              });
            });
          }
        } catch (e) {
          console.error('获取商品列表失败:', e);
        }
      }

      // 将后端数据转换为前端需要的格式
      allOrders.value = (res.rows || []).map((order: OrderMain) => ({
        id: order.id,
        orderTime: order.createTime,
        orderNo: order.orderNo,
        orderPerson: order.createName, // 需要关联用户信息
        department: order.createDeptName, // 需要关联部门信息
        payAmount: order.payableAmount || 0,
        freight: order.shippingFee || 0,
        status: mapBackendStatusToTabKey(order.orderStatus || ''),
        statusText: getStatusText(order.orderStatus || ''),
        countdown: '',
        auditStatus: order.checkStatus,
        fileCount: 0,
        checked: false,
        expanded: false,
        products: orderProductsMap[order.id] || [] // 商品信息已加载
      }));

      // 调试：打印转换后的订单状态
      console.log(
        '转换后的订单状态分布:',
        allOrders.value.map((o) => o.status)
      );

      total.value = res.total || 0;
    }
  } catch (error) {
    console.error('获取订单列表失败:', error);
  } finally {
    loading.value = false;
  }
};

const orderList = computed(() => allOrders.value);
const totalOrders = computed(() => total.value);
const selectedCount = computed(() => orderList.value.filter((o) => o.checked).length);
const selectedAmount = computed(() =>
  orderList.value
    .filter((o) => o.checked)
    .reduce((sum, o) => sum + parseFloat(o.payAmount), 0)
    .toFixed(2)
);

const getStatusColor = (status: string) =>
  ({ completed: '#67c23a', preOrder: '#e6a23c', shipping: '#409eff', cancelled: '#909399' })[status] || '#909399';
const getAuditStatusClass = (auditStatus: string) => (auditStatus === '审批通过' ? 'success' : auditStatus === '审批驳回' ? 'danger' : 'warning');
const getOrderActions = (order: any) => {
  const actions: string[] = [];
  switch (order.status) {
    case 'preOrder':
      // actions.push('再次购买', '加入采购单', '取消订单');
      actions.push('再次购买');
      break;
    case 'shipping':
      // actions.push('再次购买', '加入采购单', '取消订单');
      actions.push('再次购买');
      break;
    case 'completed':
      // actions.push('评价', '再次购买', '加入采购单', '申请售后', '删除订单', '查看发票');
      actions.push('再次购买', '申请售后');
      break;
    case 'cancelled':
      // actions.push('再次购买', '加入采购单', '删除订单');
      actions.push('再次购买');
      break;
  }
  return actions;
};

const batchConfirmationBtn = async () => {
  const ids = allOrders.value.filter((o) => o.checked).map((o) => o.id);

  try {
    const res = await batchConfirmation([...ids]);
    if (res.code === 200) {
      ElMessage.success('批量确认成功');
      fetchOrderList();
    } else {
      ElMessage.error('批量确认失败');
    }
    return;
  } catch (error) {
    console.error('批量确认失败:', error);
    ElMessage.error('批量确认失败');
  }
};
const handleExpand = async (order: any) => {
  const orderIndex = allOrders.value.findIndex((o) => o.id === order.id);
  if (orderIndex === -1) return;

  // 替换整个数组以触发响应式更新
  allOrders.value = allOrders.value.map((o, i) => (i === orderIndex ? { ...o, expanded: !o.expanded } : o));
};
const handleSelectAll = (val: CheckboxValueType) => {
  orderList.value.forEach((order) => {
    order.checked = !!val;
  });
};

async function copyOrderNo() {
  // 1. 先找出所有被勾选的订单
  const checkedOrders = orderList.value.filter((o) => o.checked);

  let orderNoStr = '';

  if (checkedOrders.length > 0) {
    // ✅ 情况 A：有勾选的，复制勾选的（支持多选）
    orderNoStr = checkedOrders.map((o) => o.orderNo).join(',');
  } else {
    // ⚠️ 情况 B：没勾选任何项
    // 策略 1：如果列表不为空，默认复制第一个
    if (orderList.value.length > 0) {
      orderNoStr = orderList.value[0].orderNo;
      ElMessage.warning('未选择订单，已默认复制第一个订单号');
    } else {
      ElMessage.error('列表为空，无法复制');
      return;
    }
  }

  // 2. 执行复制逻辑
  try {
    await navigator.clipboard.writeText(orderNoStr);
    ElMessage.success(`成功复制 ${checkedOrders.length || 1} 个订单号`);
  } catch (err) {
    const textarea = document.createElement('textarea');
    textarea.value = orderNoStr;
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand('copy');
    document.body.removeChild(textarea);
    ElMessage.success(`成功复制 ${checkedOrders.length || 1} 个订单号`);
  }
}
const handleOrderCheck = () => {
  selectAll.value = orderList.value.every((order) => order.checked);
};
const handleViewDetail = (order: any) => {
  router.push(`/order/orderManage/detail/${order.id}`);
};

const handleApplyAfter = (order: any) => {
  router.push(`/order/orderManage/applyAfter?orderId=${order.id}`);
};
const handleQuery = () => {
  queryParams.pageNum = 1;
  fetchOrderList();
};
const handleReset = () => {
  queryParams.keyword = '';
  queryParams.dateRange = null;
  queryParams.department = '';
  queryParams.payType = '';
  queryParams.pageNum = 1;
  fetchOrderList();
};
const handleAction = (action: string, order: any) => {
  switch (action) {
    case '取消订单':
      handleCancelOrder(order);
      break;
    case '删除订单':
      handleDeleteOrder(order);
      break;
    case '查看详情':
      handleViewDetail(order);
      break;
    case '评价':
      handleEvaluate(order);
      break;
    case '再次购买':
      handleAddCartBatch(order);
      break;
    case '申请售后':
      handleApplyAfter(order);
      break;
    default:
      ElMessage.info(`${action}功能开发中`);
  }
};

const handleEvaluate = (order: any) => {
  currentOrder.value = order;
  currentProduct.value = order.products[0];
  evaluateDialogTitle.value = '商品评价';
  evaluateForm.deliverGoods = undefined;
  evaluateForm.content = '';
  evaluateForm.evaluationType = 1;
  evaluateDialogVisible.value = true;
};

const handleSubmitEvaluate = async () => {
  const valid = await evaluateFormRef.value?.validate();
  if (!valid) return;

  try {
    const submitData = {
      orderId: currentOrder.value?.orderId,
      productId: currentProduct.value?.id,
      evaluationType: evaluateForm.evaluationType, // 1-评价 2-追评
      deliverGoods: evaluateForm.deliverGoods,
      content: evaluateForm.content,
      // 图片上传暂时留空，后续可以添加
      images: []
    };

    const res = await addOrderEvaluation(submitData);
    if (res.code === 200) {
      ElMessage.success('评价提交成功');
      evaluateDialogVisible.value = false;

      // 重新获取订单列表
      await getOrderList();
    } else {
      ElMessage.error(res.msg || '评价提交失败');
    }
  } catch (error) {
    console.error('评价提交失败:', error);
    ElMessage.error('评价提交失败');
  }
};
const handleCancelOrder = async (order: any) => {
  try {
    await ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    const res = await cancelOrder({ id: order.id, orderStatus: '7' });
    if (res.code === 200) {
      ElMessage.success('订单已取消');
      fetchOrderList();
    } else {
      ElMessage.error(res.msg || '取消订单失败');
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('取消订单失败');
    }
  }
};
const handleDeleteOrder = async (order: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该订单吗？删除后无法恢复。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    const res = await deleteOrder([order.id]);
    if (res.code === 200) {
      ElMessage.success('订单已删除');
      fetchOrderList();
    } else {
      ElMessage.error(res.msg || '删除订单失败');
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除订单失败');
    }
  }
};

// 页面加载时获取订单列表
onMounted(() => {
  loadDeptTree();
  fetchOrderList();
});
</script>

<style scoped lang="scss">
.order-manage-container {
  padding: 20px;
  background: #fff;
  min-height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
  // max-height: calc(100vh - 120px); // 减去顶部导航栏和其他元素高度
}
.page-title {
  font-size: 16px;
  font-weight: bold;
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
}
.title-bar {
  display: inline-block;
  width: 3px;
  height: 16px;
  background: #e60012;
  border-radius: 2px;
}

.tab-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;
  margin-bottom: 15px;
  .tab-left {
    display: flex;
    gap: 25px;
  }
  .tab-item {
    display: flex;
    align-items: center;
    gap: 5px;
    padding: 12px 0;
    cursor: pointer;
    color: #666;
    font-size: 14px;
    border-bottom: 2px solid transparent;
    margin-bottom: -1px;
    &:hover,
    &.active {
      color: #333;
    }
    &.active {
      border-bottom-color: #e60012;
    }
  }
}
.order-list {
  // flex: 1;
  // overflow-y: auto;
  margin-bottom: 15px;
  .order-card {
    border: 1px solid #eee;
    border-radius: 4px;
    margin-bottom: 15px;
    overflow: hidden;
    .order-header {
      padding: 12px 15px;
      background: #f9f9f9;
      border-bottom: 1px solid #eee;
      font-size: 14px;
      color: #101828;
      .expand-btn {
        color: #165dff;
        margin-left: 10px;
        cursor: pointer;
      }
      .open-btn {
        color: #364153;
        margin-left: 10px;
        cursor: pointer;
      }
    }
    .countdown-bar {
      background: #fff5e6;
      color: #e6a23c;
      padding: 8px 15px;
      font-size: 13px;
      border-bottom: 1px solid #eee;
    }
    .product-list {
      .product-row {
        display: flex;
        // border-bottom: 1px solid #f5f5f5;
        &:last-child {
          border-bottom: none;
        }
      }
      .product-cell {
        padding: 15px;
        display: flex;
        flex-direction: column;
        justify-content: center;
      }
      .product-info-cell {
        display: flex;
        flex: 1;
        padding: 15px;
        gap: 15px;
        .product-image {
          width: 80px;
          height: 80px;
          background: #f5f5f5;
          border-radius: 4px;
          overflow: hidden;
          flex-shrink: 0;
          .el-image {
            width: 100%;
            height: 100%;
          }
          .image-placeholder {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
          }
        }
        .product-detail {
          flex: 1;
          width: 0;
          .product-name {
            font-size: 14px;
            color: #000000;
            margin-bottom: 5px;
          }
          .product-spec {
            font-size: 12px;
            color: #999;
            margin-bottom: 10px;
          }
          .product-price {
            font-size: 16px;
            font-weight: bold;
            color: #e60012;
            margin-bottom: 5px;
          }
        }
        .product-quantity {
          font-size: 13px;
          color: #666;
        }
      }
      .amount-cell {
        width: 200px;
        padding: 15px;
        .amount-info {
          margin-bottom: 5px;
          .label {
            font-size: 12px;
            color: #999;
            margin-right: 4px;
          }
          .value {
            font-size: 14px;
            color: #333;
            &.highlight {
              font-size: 16px;
              font-weight: bold;
              color: #e60012;
            }
          }
        }
      }
      .status-cell {
        width: 140px;
        padding: 15px;
        display: flex;
        align-items: flex-start;
        justify-content: flex-end;
        gap: 10px;
        .status-text {
          font-size: 14px;
          font-weight: 500;
        }
        .audit-status {
          font-size: 14px;
          &.success {
            color: #e60012;
          }
          &.warning {
            color: #e6a23c;
          }
          &.danger {
            color: #e60012;
          }
        }
      }
      .action-cell {
        width: 100px;
        border-left: 1px solid #f5f5f5;
        align-items: flex-start;
        gap: 3px;
      }
    }
    .more-products-hint {
      padding: 10px 15px;
      background: #f5f5f5;
      font-size: 12px;
      color: #666;
      text-align: center;
      border-top: 1px solid #f0f0f0;
    }
  }
}

.bottom-bar {
  background: #fafafa;
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
  .bottom-right {
    display: flex;
    align-items: center;
    gap: 15px;
    .selected-info {
      font-size: 14px;
      color: #666;
      em {
        color: #e60012;
        font-style: normal;
        font-weight: bold;
      }
    }
  }
}
.evaluate-product {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  background: #f9f9f9;
  border-radius: 4px;
  margin-bottom: 20px;
  .product-image {
    width: 60px;
    height: 60px;
    background: #fff;
    border-radius: 4px;
    overflow: hidden;
    flex-shrink: 0;
    .el-image {
      width: 100%;
      height: 100%;
    }
    .image-placeholder {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  .product-info {
    .product-name {
      font-size: 14px;
      color: #333;
      margin-bottom: 5px;
    }
    .product-spec {
      font-size: 12px;
      color: #999;
    }
  }
}
:deep(.table-pagination) {
  flex-shrink: 0;
  margin-top: 15px;
}
</style>
