<template>
  <!-- 订单列表 -->
  <view class="content">
    <!-- 搜索栏 -->
    <view class="search-container">
      <view class="search-box">
        <image :src="getFileUrl('img/personal/search.png')" mode="widthFix" class="search-icon"></image>
        <input type="text" placeholder="搜索" class="search-input" v-model="searchKeyword" />
      </view>
    </view>

    <!-- 标签页 -->
    <view class="tabs">
      <view class="tab-item" :class="{ active: activeTab === 'current' }" @click="switchTab('current')">
        当前订单
      </view>
      <view class="tab-item" :class="{ active: activeTab === 'history' }" @click="switchTab('history')">
        历史订单
      </view>
    </view>

    <!-- 订单列表 -->
    <scroll-view class="order-list" scroll-y>
      <view v-for="(order, index) in currentOrderList" :key="order.id || index" class="order-card">
        <!-- 订单头部 -->
        <view class="order-header">
          <view class="order-number">NO.{{ order.orderNo }}</view>

        </view>

        <!-- 店铺信息 -->
        <view class="store-info" @click="handleStoreClick(order)">
          <view><text class="store-name">{{ order.storeName }}</text>
            <text class="store-arrow">›</text>
          </view>
          <view class="order-status" :class="order.statusClass">{{ order.statusText }}</view>
        </view>

        <!-- 订单时间 -->
        <view class="order-time">{{ order.createTime }}</view>

        <!-- 商品信息 -->
        <view class="order-goods" @click="handleOrderDetail(order)">
          <view class="goods-images">
            <image v-for="(image, imgIndex) in order.goodsImages" :key="imgIndex" :src="getFileUrl(image)"
              mode="aspectFill" class="goods-image" />
          </view>
          <view class="goods-info">
            <view class="goods-price">¥{{ order.totalPrice }}</view>
            <view class="goods-count">共{{ order.goodsCount }}件</view>
          </view>
        </view>

        <!-- 操作按钮：已完成(3)不显示 -->
        <view class="order-actions" v-if="order.orderStatus !== 3">
          <view class="action-btn outline" @click="handleAddFood(order)">
            去加餐
          </view>
          <view class="action-btn primary" @click="handleCheckout(order)">
            去结算
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-if="currentOrderList.length === 0" class="empty-state">
        <text class="empty-text">暂无订单</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { onLoad } from "@dcloudio/uni-app";
import { ref, computed, watch } from "vue";
import { getFileUrl } from "@/utils/file.js";
import { go } from "@/utils/utils.js";
import { GetMyOrders } from "@/api/dining.js";

const activeTab = ref('current');
const searchKeyword = ref('');

// 分页参数
const pageSize = 10;
const currentPage = ref({ current: 1, history: 1 });
const loading = ref(false);
const noMore = ref({ current: false, history: false });

// records 每项：order 为订单信息，cuisineItems 为菜品数组；兼容直接平铺的旧结构
function normalizeOrder(record) {
  const order = record?.order ?? record;
  const cuisineItems = record?.cuisineItems ?? [];
  const items = Array.isArray(cuisineItems) ? cuisineItems : [];

  const orderStatus = order?.orderStatus ?? order?.status;
  const payStatus = order?.payStatus;
  const statusText = getDisplayStatusText(payStatus, orderStatus, order?.statusText ?? order?.orderStatusName);
  const statusClass = getDisplayStatusClass(payStatus, orderStatus);

  const goodsCount = items.reduce((sum, it) => sum + (Number(it?.quantity) || 0), 0) || order?.dinerCount || 0;
  const goodsImages = items
    .map((it) => it?.cuisineImage ?? it?.image ?? it?.imageUrl ?? '')
    .filter((url) => url && String(url).trim());

  return {
    id: order?.id,
    orderNo: order?.orderNo ?? order?.orderNumber ?? order?.orderId ?? '',
    storeId: order?.storeId,
    storeName: order?.storeName ?? order?.store?.name ?? (order?.storeId != null ? `门店${order.storeId}` : '—'),
    tableId: order?.tableId,
    tableNumber: order?.tableNumber ?? order?.tableId ?? '—',
    contactPhone: order?.contactPhone ?? '',
    createTime: order?.createdTime ?? order?.createTime ?? order?.orderTime ?? '—',
    totalPrice: order?.payAmount ?? order?.totalPrice ?? order?.totalAmount ?? 0,
    goodsCount,
    statusText,
    statusClass,
    orderStatus,
    payStatus,
    dinerCount: order?.dinerCount,
    discountAmount: order?.discountAmount ?? 0,
    remark: order?.remark,
    goodsImages,
    cuisineItems: items
  };
}

// orderStatus 订单状态：0 待支付，1 已支付，2 已取消，3 已完成
function getDisplayStatusText(payStatus, orderStatus, fallback) {
  if (fallback) return fallback;
  return getOrderStatusText(orderStatus);
}

function getOrderStatusText(status) {
  if (status == null && status !== 0) return '—';
  const n = Number(status);
  if (n === 0) return '待支付';
  if (n === 1) return '已支付';
  if (n === 2) return '已取消';
  if (n === 3) return '已完成';
  return String(status);
}

function getDisplayStatusClass(payStatus, orderStatus) {
  return getStatusClass(orderStatus);
}

function getStatusClass(status) {
  if (status == null && status !== 0) return '';
  const n = Number(status);
  if (n === 0) return 'status-unpaid';   // 待支付
  if (n === 1) return 'status-paid';      // 已支付
  if (n === 2) return 'status-cancelled'; // 已取消
  if (n === 3) return 'status-completed'; // 已完成
  return 'status-unpaid';
}

const currentOrders = ref([]);
const historyOrders = ref([]);

// 当前显示的订单列表（含搜索过滤）
const currentOrderList = computed(() => {
  const orders = activeTab.value === 'current' ? currentOrders.value : historyOrders.value;
  if (!searchKeyword.value) return orders;
  return orders.filter(order =>
    (order.orderNo && order.orderNo.includes(searchKeyword.value)) ||
    (order.storeName && order.storeName.includes(searchKeyword.value))
  );
});

// type：0 未支付订单，1 历史订单
const getOrderTypeByTab = (tab) => (tab === 'current' ? 0 : 1);

async function loadOrderList(tab, append = false) {
  const pageKey = tab === 'current' ? 'current' : 'history';
  if (loading.value) return;
  if (append && noMore.value[pageKey]) return;
  if (!append) {
    currentPage.value[pageKey] = 1;
    noMore.value[pageKey] = false;
  }
  const page = currentPage.value[pageKey];
  if (append && page === 1) return;

  loading.value = true;
  try {
    const params = {
      current: page,
      size: pageSize,
      type: getOrderTypeByTab(tab)
    };
    const res = await GetMyOrders(params);
    // /store/order/my-orders：返回 data，可能为 { records, total } 或 { data: { records, total } }
    const raw = res && typeof res === 'object' ? res : {};
    const list = Array.isArray(raw.records)
      ? raw.records
      : Array.isArray(raw.data?.records)
        ? raw.data.records
        : Array.isArray(raw.list)
          ? raw.list
          : [];
    const normalized = list.map(normalizeOrder);

    if (tab === 'current') {
      currentOrders.value = append ? [...currentOrders.value, ...normalized] : normalized;
    } else {
      historyOrders.value = append ? [...historyOrders.value, ...normalized] : normalized;
    }

    const total =
      raw.total != null ? Number(raw.total) : (raw.data?.total != null ? Number(raw.data.total) : 0);
    if (normalized.length < pageSize || (page * pageSize >= total)) {
      noMore.value[pageKey] = true;
    } else {
      currentPage.value[pageKey] = page + 1;
    }
  } catch (e) {
    uni.showToast({ title: e?.message || '加载失败', icon: 'none' });
  } finally {
    loading.value = false;
  }
}

const storeIdRef = ref('');
const tableIdRef = ref('');
const STORAGE_STORE_ID = 'currentStoreId';
const STORAGE_TABLE_ID = 'currentTableId';

function doLoad() {
  currentPage.value = { current: 1, history: 1 };
  noMore.value = { current: false, history: false };
  loadOrderList(activeTab.value, false);
}

watch(activeTab, (tab) => {
  // 每次切换标签都重新拉取该 tab 的数据，保证来回切换时列表会更新
  loadOrderList(tab, false);
});

// 处理订单详情（须传 orderId 详情页才会请求接口）
const handleOrderDetail = (order) => {
  const orderId = order?.id ?? order?.orderId ?? '';
  if (!orderId) {
    uni.showToast({ title: '订单ID缺失', icon: 'none' });
    return;
  }
  go(`/pages/orderInfo/orderDetail?orderId=${encodeURIComponent(String(orderId))}`);
};

// 切换标签页
const switchTab = (tab) => {
  activeTab.value = tab;
};

// 处理店铺点击
const handleStoreClick = (order) => {
  console.log('点击店铺:', order);
  // TODO: 跳转到店铺详情
};

// 处理加餐：带上该订单的桌号和人数，点餐页依赖 tableid、diners 拉取列表和购物车
const handleAddFood = (order) => {
  const tableid = order?.tableId ?? order?.tableNumber ?? uni.getStorageSync(STORAGE_TABLE_ID) ?? '';
  const diners = order?.dinerCount ?? order?.diners ?? uni.getStorageSync('currentDiners') ?? '';
  const q = [];
  if (tableid !== '' && tableid != null) q.push(`tableid=${encodeURIComponent(String(tableid))}`);
  if (diners !== '' && diners != null) q.push(`diners=${encodeURIComponent(String(diners))}`);
  go(q.length ? `/pages/orderFood/index?${q.join('&')}` : '/pages/orderFood/index');
};

// 处理结算：带上订单ID、桌号、人数、订单金额、备注，确认订单页用于调起支付
const handleCheckout = (order) => {
  const orderId = order?.id ?? order?.orderId ?? '';
  const orderNo = order?.orderNo ?? order?.orderNumber ?? orderId ?? '';
  const tableId = order?.tableId ?? order?.tableNumber ?? '';
  const tableNumber = order?.tableNumber ?? order?.tableNo ?? '';
  const diners = order?.dinerCount ?? order?.diners ?? '';
  const totalAmount = order?.totalPrice ?? order?.payAmount ?? 0;
  const remark = (order?.remark ?? '').trim().slice(0, 30);
  const q = [];
  if (orderId !== '') q.push(`orderId=${encodeURIComponent(String(orderId))}`);
  if (orderNo !== '') q.push(`orderNo=${encodeURIComponent(String(orderNo))}`);
  if (tableId !== '' && tableId != null) q.push(`tableId=${encodeURIComponent(String(tableId))}`);
  if (tableNumber !== '') q.push(`tableNumber=${encodeURIComponent(String(tableNumber))}`);
  if (diners !== '' && diners != null) q.push(`diners=${encodeURIComponent(String(diners))}`);
  if (totalAmount != null && totalAmount !== '') q.push(`totalAmount=${encodeURIComponent(String(totalAmount))}`);
  if (remark !== '') q.push(`remark=${encodeURIComponent(remark)}`);
  go(q.length ? `/pages/placeOrder/index?${q.join('&')}` : '/pages/placeOrder/index');
};

onLoad((options) => {
  uni.setNavigationBarTitle({ title: '我的订单' });
  // 优先用 URL 参数，否则用本地缓存（点餐/下单流程会写入）
  storeIdRef.value = options?.storeId ?? uni.getStorageSync(STORAGE_STORE_ID) ?? '';
  tableIdRef.value = options?.tableId ?? uni.getStorageSync(STORAGE_TABLE_ID) ?? '';
  doLoad();
});
</script>

<style lang="scss" scoped>
.content {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f7f9fa;
  box-sizing: border-box;
}

// 搜索栏
.search-container {
  width: 100%;
  padding: 20rpx 30rpx;
  background-color: #fff;
  box-sizing: border-box;

  .search-box {
    width: 100%;
    height: 80rpx;
    background-color: #f5f5f5;
    border-radius: 40rpx;
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    box-sizing: border-box;

    .search-icon {
      width: 34rpx;
      height: 34rpx;
      margin-right: 16rpx;
    }

    .search-input {
      flex: 1;
      font-size: 28rpx;
      color: #333;
      background: transparent;
      border: none;
    }
  }
}

// 标签页
.tabs {
  display: flex;
  background-color: #fff;
  border-bottom: 1rpx solid #f0f0f0;
  padding: 0 30rpx;

  .tab-item {
    flex: 1;
    height: 88rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 27rpx;
    color: #AAAAAA;
    font-weight: bold;
    position: relative;
    transition: color 0.3s;

    &.active {
      font-size: 27rpx;
      color: #151515;
      font-weight: bold;

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 40rpx;
        height: 8rpx;
        background-color: #FF6B35;
        border-radius: 5rpx;
      }
    }
  }
}

// 订单列表
.order-list {
  flex: 1;
  padding: 20rpx 30rpx;
  box-sizing: border-box;
}

// 订单卡片
.order-card {
  width: 100%;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0rpx 0rpx 11rpx 0rpx rgba(0, 0, 0, 0.06);
  box-sizing: border-box;

  // 订单头部
  .order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    .order-number {
      font-size: 28rpx;
      color: #151515;
      font-weight: 500;
    }
  }

  // 店铺信息
  .store-info {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12rpx;


    .order-status {
      font-size: 28rpx;
      font-weight: 500;

      &.status-active {
        font-size: 23rpx;
        color: #008844;
      }

      &.status-unpaid {
        color: #008844;
      }

      &.status-paid {
        color: #008844;
      }

      &.status-completed {
        color: #999;
      }

      &.status-cancelled {
        color: #FF3B30;
      }
    }

    .store-name {
      font-size: 27rpx;
      color: #151515;
      font-weight: bold;
    }

    .store-arrow {
      font-size: 36rpx;
      color: #999;
      margin-left: 10rpx;
    }
  }

  // 订单时间
  .order-time {
    font-size: 23rpx;
    color: #AAAAAA;
    margin-bottom: 20rpx;
  }

  // 商品信息
  .order-goods {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;

    .goods-images {
      display: flex;
      gap: 12rpx;
      margin-right: 20rpx;

      .goods-image {
        width: 100rpx;
        height: 100rpx;
        border-radius: 8rpx;
        background-color: #f5f5f5;
      }
    }

    .goods-info {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: flex-end;

      .goods-price {
        font-weight: bold;
        font-size: 27rpx;
        color: #151515;
        margin-bottom: 8rpx;
      }

      .goods-count {
        font-size: 23rpx;
        color: #666666;
      }
    }
  }

  // 操作按钮
  .order-actions {
    display: flex;
    gap: 20rpx;
    padding-top: 20rpx;
    border-top: 1rpx solid #f0f0f0;
    justify-content: flex-end;

    .action-btn {
      height: 68rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 34rpx;
      font-size: 28rpx;
      font-weight: 500;
      transition: all 0.3s;


      &.outline {
        border: 2rpx solid #FF6B35;
        color: #FF6B35;
        background-color: transparent;
        text-align: center;
        width: 172rpx;
        height: 73rpx;
        box-shadow: 0rpx -11rpx 46rpx 0rpx rgba(86, 125, 244, 0.05);
        border-radius: 19rpx 19rpx 19rpx 19rpx;
        border: 2rpx solid #F47D1F;

        &:active {
          background-color: #fff4e6;
        }
      }

      &.primary {
        background: linear-gradient(135deg, #FF6B35 0%, #FF8C42 100%);
        color: #fff;
        width: 172rpx;
        height: 73rpx;
        background: linear-gradient(0deg, #FCB73F 0%, #FC733D 100%);
        box-shadow: 0rpx -11rpx 46rpx 0rpx rgba(86, 125, 244, 0.05);
        border-radius: 19rpx 19rpx 19rpx 19rpx;

        &:active {
          opacity: 0.8;
        }
      }
    }
  }
}

// 空状态
.empty-state {
  width: 100%;
  padding: 100rpx 0;
  display: flex;
  justify-content: center;
  align-items: center;

  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
}
</style>
