<template>
  <view class="order-page">
    <!-- 顶部Tab切换 -->
    <view class="tab-header">
      <view
        class="tab-item"
        :class="{ active: currentTab === 'all' }"
        @click="switchTab('all')"
      >
        <text class="tab-text">全部订单</text>
        <view class="tab-line" v-if="currentTab === 'all'"></view>
      </view>
      <view
        class="tab-item"
        :class="{ active: currentTab === 'paid' }"
        @click="switchTab('paid')"
      >
        <text class="tab-text">已支付</text>
        <view class="tab-line" v-if="currentTab === 'paid'"></view>
      </view>
      <view
        class="tab-item"
        :class="{ active: currentTab === 'unpaid' }"
        @click="switchTab('unpaid')"
      >
        <text class="tab-text">未支付</text>
        <view class="tab-line" v-if="currentTab === 'unpaid'"></view>
      </view>
    </view>

    <!-- 数量统计和筛选 -->
    <view class="filter-bar">
      <text class="total-count">总数量: {{ filteredOrders.length }}</text>
      <view class="search-btn" @click="showFilterSidebar = true">
        <text class="search-icon">🔍</text>
      </view>
    </view>

    <!-- 筛选条件显示 -->
    <view class="filter-condition" v-if="filterStartTime || filterEndTime">
      <text class="filter-text">{{ filterStartTime }} - {{ filterEndTime }}</text>
      <text class="filter-clear" @click="clearFilter">✕</text>
    </view>

    <!-- 订单列表 -->
    <scroll-view class="order-scroll" scroll-y @scrolltolower="loadMore">
      <view class="order-list">
        <view
          class="order-card"
          v-for="order in filteredOrders"
          :key="order._id"
        >
          <!-- 第一行: 日期 + 状态 -->
          <view class="order-header">
            <text class="order-date">{{ formatTime(order.createdAt) }}</text>
            <view class="status-tags">
              <text class="order-status" :class="orderStatusClass(order.order_status)">
                {{ orderStatusText(order.order_status) }}
              </text>
              <text class="pay-status" :class="payStatusClass(order.payment_status)">
                {{ payStatusText(order.payment_status) }}
              </text>
            </view>
          </view>
          <view class="divider"></view>

          <!-- 商品列表 -->
          <view class="product-section" @click="goToDetail(order)">
            <view class="product-list">
              <view
                class="product-item"
                v-for="(product, pIndex) in order.products"
                :key="pIndex"
              >
                <image class="product-img" :src="product.image" mode="aspectFill" />
                <view class="product-info">
                  <text class="product-name">{{ product.name }}</text>
                  <text class="product-price-qty">￥{{ getDecimal(product.unit_price) }} x {{ product.qty }}</text>
                </view>
              </view>
            </view>
            <view class="product-arrow">
              <text class="arrow-icon">›</text>
            </view>
          </view>

          <!-- 总计 -->
          <view class="order-total">
            <text class="total-qty">共{{ order.total_qty }}件</text>
            <view class="total-amount">
              <text class="total-label">总计:</text>
              <text class="total-price">￥{{ getDecimal(order.total_amount) }}</text>
            </view>
          </view>

          <!-- 操作按钮 -->
          <view class="order-action">
            <view
              v-if="order.payment_status === 'PENDING'"
              class="action-btn pay-btn"
              @click="handlePay(order)"
            >
              立即支付
            </view>
            <view
              v-else-if="order.payment_status === 'PAID' && !order.has_refund"
              class="action-btn refund-btn"
              @click="handleRefund(order)"
            >
              申请退款
            </view>
          </view>
        </view>

        <!-- 加载状态 -->
        <view class="loading-state" v-if="loading">
          <text class="loading-text">加载中...</text>
        </view>

        <!-- 加载更多 / 没有更多 -->
        <view class="load-more" v-if="!loading && orderList.length > 0 && total > limit">
          <text class="load-more-text">{{ hasNext ? '上拉加载更多' : '没有更多了' }}</text>
        </view>

        <!-- 空状态 -->
        <view class="empty-state" v-if="!loading && filteredOrders.length === 0">
          <text class="empty-text">暂无订单</text>
        </view>
      </view>
      <view class="bottom-spacer"></view>
    </scroll-view>

    <!-- 筛选侧边栏 -->
    <view class="filter-sidebar-mask" v-if="showFilterSidebar" @click="showFilterSidebar = false">
      <view class="filter-sidebar" @click.stop>
        <view class="sidebar-header">
          <text class="sidebar-title">筛选条件</text>
          <text class="sidebar-close" @click="showFilterSidebar = false">✕</text>
        </view>
        <view class="sidebar-content">
          <view class="date-row">
            <text class="date-label">开始时间</text>
            <picker mode="date" :value="tempStartTime" @change="onStartTimeChange">
              <view class="date-picker">
                <text class="date-value">{{ tempStartTime || '请选择' }}</text>
              </view>
            </picker>
          </view>
          <view class="date-row">
            <text class="date-label">结束时间</text>
            <picker mode="date" :value="tempEndTime" @change="onEndTimeChange">
              <view class="date-picker">
                <text class="date-value">{{ tempEndTime || '请选择' }}</text>
              </view>
            </picker>
          </view>
        </view>
        <view class="sidebar-footer">
          <view class="sidebar-btn reset-btn" @click="resetFilter">
            <text class="btn-text">重置</text>
          </view>
          <view class="sidebar-btn confirm-btn" @click="confirmFilter">
            <text class="btn-text">确定</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部导航条 -->
    <page-nav-bar
      :hasPrev="true"
      :hasNext="false"
      @prev="handleNavPrev"
      @next="handleNavNext"
    />
  </view>
</template>

<script>
import PageNavBar from '@/components/page-nav-bar/page-nav-bar.vue';
import { get } from '@/utils/request.js';
import { checkLoginWithPrompt, getCachedUserInfo } from '@/utils/auth-guard.js';

export default {
  components: { PageNavBar },
  data() {
    return {
      currentTab: 'all',
      showFilterSidebar: false,
      tempStartTime: '',
      tempEndTime: '',
      filterStartTime: '',
      filterEndTime: '',
      orderList: [],
      loading: false,
      page: 1,
      limit: 10,
      hasNext: true,
      total: 0
    };
  },
  computed: {
    filteredOrders() {
      let list = this.orderList;

      if (this.currentTab === 'paid') {
        list = list.filter(o => o.payment_status === 'PAID');
      } else if (this.currentTab === 'unpaid') {
        list = list.filter(o => o.payment_status === 'PENDING');
      }

      return list;
    }
  },
  onLoad() {
    if (!checkLoginWithPrompt('order')) return;
    this.fetchOrders();
  },
  methods: {
    // 拉取订单列表
    async fetchOrders(append = false) {
      if (this.loading) return;
      this.loading = true;

      try {
        const userInfo = getCachedUserInfo();
        const userId = userInfo && userInfo.user_id;
        if (!userId) {
          uni.showToast({ title: '无法获取用户信息', icon: 'none' });
          return;
        }

        const filter = { user_id: userId };
        if (this.filterStartTime) filter.start_time = this.filterStartTime;
        if (this.filterEndTime) filter.end_time = this.filterEndTime;

        const res = await get('/user/orders', {
          page: this.page,
          limit: this.limit,
          filter: JSON.stringify(filter)
        });

        const ret = res.data || {};
        if (ret.code === 0) {
          const list = Array.isArray(ret.data) ? ret.data : [];
          const meta = ret.meta || {};

          if (append) {
            this.orderList = this.orderList.concat(list);
          } else {
            this.orderList = list;
          }

          this.total = meta.total || list.length;
          this.hasNext = !!meta.hasNext;
        } else {
          uni.showToast({ title: ret.message || '获取订单失败', icon: 'none' });
        }
      } catch (e) {
        uni.showToast({ title: '网络请求失败', icon: 'none' });
      } finally {
        this.loading = false;
      }
    },

    // 上拉加载更多
    loadMore() {
      if (!this.hasNext || this.loading) return;
      this.page++;
      this.fetchOrders(true);
    },

    switchTab(tab) {
      this.currentTab = tab;
    },

    // 筛选
    onStartTimeChange(e) { this.tempStartTime = e.detail.value; },
    onEndTimeChange(e) { this.tempEndTime = e.detail.value; },
    resetFilter() {
      this.tempStartTime = '';
      this.tempEndTime = '';
    },
    confirmFilter() {
      this.filterStartTime = this.tempStartTime;
      this.filterEndTime = this.tempEndTime;
      this.showFilterSidebar = false;
      this.page = 1;
      this.hasNext = true;
      this.fetchOrders();
    },
    clearFilter() {
      this.filterStartTime = '';
      this.filterEndTime = '';
      this.page = 1;
      this.hasNext = true;
      this.fetchOrders();
    },

    // 格式化时间
    formatTime(iso) {
      if (!iso) return '';
      const d = new Date(iso);
      const pad = n => String(n).padStart(2, '0');
      return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
    },

    // 解析 MongoDB Decimal128
    getDecimal(val) {
      if (!val) return '0.00';
      if (val.$numberDecimal) return val.$numberDecimal;
      return String(val);
    },

    // 订单状态
    orderStatusText(status) {
      const map = { PROCESSING: '处理中', COMPLETED: '已完成', CANCELLED: '已取消' };
      return map[status] || status;
    },
    orderStatusClass(status) {
      if (status === 'COMPLETED') return 'paid';
      if (status === 'CANCELLED') return 'cancelled';
      return 'processing';
    },

    // 支付状态
    payStatusText(status) {
      const map = { PENDING: '待支付', PAID: '已支付', REFUNDED: '已退款', PARTIAL_REFUND: '部分退款' };
      return map[status] || status;
    },
    payStatusClass(status) {
      if (status === 'PAID') return 'paid';
      if (status === 'PENDING') return 'unpaid';
      return '';
    },

    goToDetail(order) {
      uni.setStorageSync('__order_detail_cache', order);
      uni.navigateTo({ url: `/pages/order/detail?order_id=${order.order_id}` });
    },
    handlePay(order) {
      if (!checkLoginWithPrompt('pay')) return;
      uni.showModal({
        title: '立即支付',
        content: `确认支付￥${this.getDecimal(order.total_amount)}？`,
        success: (res) => {
          if (res.confirm) {
            uni.showToast({ title: '支付功能开发中', icon: 'none' });
          }
        }
      });
    },
    handleRefund(order) {
      uni.showModal({
        title: '申请退款',
        content: '确认申请退款？',
        success: (res) => {
          if (res.confirm) {
            uni.showToast({ title: '退款功能开发中', icon: 'none' });
          }
        }
      });
    },

    handleNavPrev() {
      uni.navigateBack({ fail: () => { uni.switchTab({ url: '/pages/index/index' }); } });
    },
    handleNavNext() {
      uni.showToast({ title: '暂无下一页', icon: 'none' });
    }
  }
};
</script>

<style scoped>
page { height: 100%; background-color: #f5f5f5; }

.order-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

/* 顶部Tab */
.tab-header {
  display: flex;
  background: #fff;
  padding: 0 24rpx;
}
.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 28rpx 0 20rpx;
  position: relative;
}
.tab-text {
  font-size: 30rpx;
  color: #666;
}
.tab-item.active .tab-text {
  color: #2979ff;
  font-weight: bold;
}
.tab-line {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 48rpx;
  height: 6rpx;
  background: #2979ff;
  border-radius: 3rpx;
}

/* 筛选栏 */
.filter-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 28rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
}
.total-count {
  font-size: 28rpx;
  color: #333;
}
.search-btn {
  padding: 8rpx 16rpx;
}
.search-icon {
  font-size: 36rpx;
}

/* 筛选条件显示 */
.filter-condition {
  display: flex;
  align-items: center;
  padding: 16rpx 28rpx;
  background: #e8f4ff;
}
.filter-text {
  font-size: 26rpx;
  color: #2979ff;
  flex: 1;
}
.filter-clear {
  font-size: 28rpx;
  color: #999;
  padding: 8rpx;
}

/* 订单列表 */
.order-scroll {
  flex: 1;
  height: 0;
}
.order-list {
  padding: 20rpx;
}
.order-card {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 24rpx;
}

/* 订单头部 */
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.order-date {
  font-size: 26rpx;
  color: #666;
}
.status-tags {
  display: flex;
  gap: 12rpx;
}
.order-status, .pay-status {
  font-size: 22rpx;
  padding: 4rpx 14rpx;
  border-radius: 6rpx;
}
.order-status.processing {
  background: #e8f4ff;
  color: #2979ff;
}
.order-status.paid {
  background: #e8faf0;
  color: #19be6b;
}
.order-status.cancelled {
  background: #f5f5f5;
  color: #999;
}
.pay-status.paid {
  background: #e8faf0;
  color: #19be6b;
}
.pay-status.unpaid {
  background: #fff0f0;
  color: #e4393c;
}

.divider {
  height: 1rpx;
  background: #f0f0f0;
  margin: 20rpx 0;
}

/* 商品列表 */
.product-section {
  display: flex;
  align-items: stretch;
  margin-bottom: 20rpx;
}
.product-list {
  flex: 1;
  min-width: 0;
}
.product-item {
  display: flex;
  align-items: center;
  padding: 16rpx 0;
}
.product-img {
  width: 100rpx;
  height: 100rpx;
  border-radius: 8rpx;
  background: #f0f0f0;
  flex-shrink: 0;
}
.product-info {
  flex: 1;
  margin-left: 20rpx;
  min-width: 0;
}
.product-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.product-price-qty {
  font-size: 24rpx;
  color: #999;
  margin-top: 8rpx;
  display: block;
}
.product-arrow {
  display: flex;
  align-items: center;
  padding: 0 16rpx 0 20rpx;
}
.arrow-icon {
  font-size: 52rpx;
  color: #bbb;
}

/* 总计 */
.order-total {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 16rpx;
  border-top: 1rpx solid #f0f0f0;
}
.total-qty {
  font-size: 26rpx;
  color: #666;
}
.total-amount {
  display: flex;
  align-items: center;
}
.total-label {
  font-size: 26rpx;
  color: #666;
}
.total-price {
  font-size: 32rpx;
  font-weight: bold;
  color: #e4393c;
  margin-left: 4rpx;
}

/* 操作按钮 */
.order-action {
  display: flex;
  justify-content: flex-end;
  margin-top: 20rpx;
}
.action-btn {
  padding: 16rpx 40rpx;
  border-radius: 40rpx;
  font-size: 26rpx;
}
.pay-btn {
  background: linear-gradient(135deg, #2979ff, #1e60e0);
  color: #fff;
}
.refund-btn {
  background: #fff;
  border: 2rpx solid #2979ff;
  color: #2979ff;
}

/* 空状态 */
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 100rpx 0;
}
.empty-text {
  font-size: 28rpx;
  color: #999;
}

/* 加载状态 */
.loading-state {
  display: flex;
  justify-content: center;
  padding: 40rpx 0;
}
.loading-text {
  font-size: 26rpx;
  color: #999;
}

/* 加载更多 */
.load-more {
  display: flex;
  justify-content: center;
  padding: 30rpx 0;
}
.load-more-text {
  font-size: 24rpx;
  color: #ccc;
}

/* 筛选侧边栏 */
.filter-sidebar-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1000;
}
.filter-sidebar {
  position: absolute;
  top: 0;
  right: 0;
  width: 600rpx;
  height: 100%;
  background: #fff;
  display: flex;
  flex-direction: column;
}
.sidebar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx 28rpx;
  border-bottom: 1rpx solid #f0f0f0;
}
.sidebar-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}
.sidebar-close {
  font-size: 36rpx;
  color: #999;
  padding: 8rpx;
}
.sidebar-content {
  flex: 1;
  padding: 28rpx;
}
.date-row {
  margin-bottom: 32rpx;
}
.date-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 16rpx;
  display: block;
}
.date-picker {
  background: #f5f5f5;
  border-radius: 8rpx;
  padding: 24rpx;
}
.date-value {
  font-size: 28rpx;
  color: #333;
}
.sidebar-footer {
  display: flex;
  padding: 28rpx;
  border-top: 1rpx solid #f0f0f0;
}
.sidebar-btn {
  flex: 1;
  padding: 24rpx 0;
  text-align: center;
  border-radius: 8rpx;
  margin: 0 8rpx;
}
.reset-btn {
  background: #f5f5f5;
}
.confirm-btn {
  background: #2979ff;
}
.reset-btn .btn-text {
  color: #666;
}
.confirm-btn .btn-text {
  color: #fff;
}
.btn-text {
  font-size: 28rpx;
}

/* 底部占位 */
.bottom-spacer {
  height: 120rpx;
}
</style>
