<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"></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>
    </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" @click="handleAddCart(order)">批量加入购物车</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>
              </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 v-else style="width: 200px"></div>
            <div class="status-cell">
              <el-button size="small" @click="handleAddCart(order)">加入购物车</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>
    <!-- 分页 -->
    <TablePagination v-model:page="queryParams.pageNum" v-model:page-size="queryParams.pageSize" :total="total" @change="fetchOrderList" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { Search, ArrowDown, Document, Clock, Box, CircleCheck, CircleClose, Picture } from '@element-plus/icons-vue';
import { TablePagination } from '@/components';
import { getOrderList, getOrderProducts } from '@/api/pc/enterprise/order';
import type { OrderMain } from '@/api/pc/enterprise/orderTypes';
import { ElMessage } from 'element-plus';
import { getDeptTree } from '@/api/pc/organization';
import { DeptInfo } from '@/api/pc/organization/types';
import { addProductShoppingCart } from '@/api/goods/index';
import { parseTime } from '@/utils/ruoyi';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { order_status, pay_method } = toRefs<any>(proxy?.useDict('order_status', 'pay_method'));

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

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 }
];

// 格式化时间
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;
  }
};

// 监听标签页切换，重置页码并重新获取数据
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 (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}件商品加入购物车`);
    });
  }

  // addProductShoppingCart({ productId: item.id, productNum: 1 }).then((res: any) => {
  //   if (res.code == 200) {
  //     ElMessage.success('已加入购物车');
  //   }
  // });
};
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.department = 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.customerName, // 需要关联用户信息
        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 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 handleOrderCheck = () => {
  selectAll.value = orderList.value.every((order) => order.checked);
};

const handleQuery = () => {
  queryParams.pageNum = 1;
  fetchOrderList();
};
const handleReset = () => {
  queryParams.keyword = '';
  queryParams.dateRange = null;
  queryParams.department = '';
  queryParams.payType = '';
  queryParams.pageNum = 1;
  fetchOrderList();
};

// 页面加载时获取订单列表
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>
