<template>
  <view class="page">
    <!-- 黄色导航栏 -->
    <NavBar title="销售订单" :showBack="true" />

    <!-- Tab 栏 -->
    <view class="tab-bar">
      <view
        v-for="tab in tabs"
        :key="tab.key"
        class="tab-item"
        :class="{ active: currentTab === tab.key }"
        @click="changeTab(tab.key)"
      >
        <text>{{ tab.label }}</text>
        <view class="tab-line" v-if="currentTab === tab.key"></view>
      </view>
    </view>

    <!-- 时间筛选 -->
    <view class="time-filter">
      <text class="time-label">创建时间: {{ dateRangeFullText }}</text>
    </view>

    <!-- 统计卡片 -->
    <view class="stats-bar">
      <view class="stat-item">
        <text class="stat-value">{{ stats.totalAmount || '0.00' }}</text>
        <text class="stat-label">订单总金额</text>
      </view>
      <view class="stat-item">
        <text class="stat-value">{{ stats.wechatAmount || '0.00' }}</text>
        <text class="stat-label">微信支付</text>
      </view>
      <view class="stat-item">
        <text class="stat-value">{{ stats.alipayAmount || '0.00' }}</text>
        <text class="stat-label">支付宝</text>
      </view>
      <view class="stat-item">
        <text class="stat-value">{{ stats.otherAmount || '0.00' }}</text>
        <text class="stat-label">其他支付</text>
      </view>
    </view>

    <!-- 列表头部 -->
    <view class="list-header">
      <text class="list-info">{{ dateRangeShortText }} 共{{ total }}条</text>
      <view class="filter-btn" @click="showDatePicker = true">
        <text>筛选</text>
      </view>
    </view>

    <!-- 订单列表 -->
    <scroll-view class="order-scroll" scroll-y @scrolltolower="loadMore">
      <view class="order-list">
        <view
          class="order-card"
          v-for="order in orderList"
          :key="order.id"
          @click="goDetail(order.id)"
        >
          <!-- 头部 -->
          <view class="card-header">
            <text class="order-time">{{ formatDateTime(order.createTime) }}</text>
            <text class="order-status" :class="getStatusClass(order.status)">
              {{ order.statusLabel || getStatusText(order.status) }}
            </text>
          </view>

          <!-- 商品区域 -->
          <view class="card-product">
            <image class="product-img" :src="getProductPic(order)" mode="aspectFill" />
            <view class="product-right">
              <text class="product-amount">¥{{ formatMoney(order.paidAmount || order.totalAmount) }}</text>
              <text class="product-count">共{{ getProductCount(order) }}件</text>
            </view>
          </view>

          <!-- 信息区域 -->
          <view class="card-info">
            <view class="info-line">
              <text class="info-label">订单编号</text>
              <text class="info-value">{{ order.orderNo }}</text>
            </view>
            <view class="info-line">
              <text class="info-label">设备信息</text>
              <text class="info-value">{{ order.deviceId }}</text>
            </view>
            <view class="info-line" v-if="order.shopName">
              <text class="info-label">门店名称</text>
              <text class="info-value">{{ order.shopName }}</text>
            </view>
            <view class="info-line">
              <text class="info-label">支付方式</text>
              <text class="info-value">{{ order.payType || '-' }}</text>
            </view>
          </view>

          <!-- 操作按钮 -->
          <view class="card-action">
            <view class="view-btn" @click.stop="goDetail(order.id)">
              <text>查看详情</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载状态 -->
      <view class="loading-more" v-if="loading">
        <view class="loading-spinner"></view>
        <text>加载中...</text>
      </view>
      <view class="no-more" v-if="!hasMore && orderList.length > 0">
        <text>— 没有更多了 —</text>
      </view>
      <view class="empty-state" v-if="!loading && orderList.length === 0">
        <text class="empty-text">暂无订单数据</text>
      </view>
    </scroll-view>

    <!-- 日期选择弹窗 -->
    <view class="date-modal" v-if="showDatePicker" @click="showDatePicker = false">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">选择时间范围</text>
        </view>
        <view class="modal-body">
          <view class="date-row">
            <text>开始日期</text>
            <picker mode="date" :value="startDate" @change="onStartDateChange">
              <view class="picker-value">{{ startDate }}</view>
            </picker>
          </view>
          <view class="date-row">
            <text>结束日期</text>
            <picker mode="date" :value="endDate" @change="onEndDateChange">
              <view class="picker-value">{{ endDate }}</view>
            </picker>
          </view>
        </view>
        <view class="modal-footer">
          <button class="btn-cancel" @click="showDatePicker = false">取消</button>
          <button class="btn-confirm" @click="confirmDateRange">确定</button>
        </view>
      </view>
    </view>

    <CustomTabBar />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import NavBar from '@/components/NavBar.vue';
import CustomTabBar from '@/components/CustomTabBar.vue';
import { getOrderList, getOrderStats } from '@/api/order';
import { OrderStatusText } from '@/utils/constants';
import { formatMoney as formatMoneyUtil } from '@/utils/common';

interface OrderItem {
  id: string;
  orderNo: string;
  status: number;
  statusLabel?: string;
  paidAmount?: number;
  totalAmount?: number;
  createTime: string;
  deviceId?: string;
  shopName?: string;
  payType?: string;
  products?: { pic?: string; productNum?: number }[];
}

const tabs = [
  { key: 'sales', label: '销售订单', params: { status: 2 } },
  { key: 'refund', label: '退款订单', params: { payStatus: 'REFUND' } },
  { key: 'abnormal', label: '异常订单', params: { statusList: [0, 3] } },
  { key: 'unpaid', label: '未支付', params: { status: 1 } }
];

const currentTab = ref('sales');
const orderList = ref<OrderItem[]>([]);
const loading = ref(false);
const hasMore = ref(true);
const page = ref(1);
const pageSize = 10;
const total = ref(0);

// 日期范围（默认最近30天）
const today = new Date();
const thirtyDaysAgo = new Date(today.getTime() - 29 * 24 * 60 * 60 * 1000);
const formatDateStr = (d: Date) => {
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${y}-${m}-${day}`;
};
const startDate = ref(formatDateStr(thirtyDaysAgo));
const endDate = ref(formatDateStr(today));
const showDatePicker = ref(false);

const stats = ref<Record<string, string | number>>({});

const dateRangeFullText = computed(() => {
  return `${startDate.value} 00:00:00 - ${endDate.value} 23:59:59`;
});

const dateRangeShortText = computed(() => {
  return `${startDate.value}~${endDate.value}`;
});

const formatMoney = formatMoneyUtil;

const getStatusText = (status: number): string => OrderStatusText[status] || '未知';

const getStatusClass = (status: number): string => {
  if (status === 2) return 'completed';
  if (status === 1) return 'pending';
  if (status === 0) return 'cancelled';
  return 'closed';
};

const formatDateTime = (datetime: string): string => {
  if (!datetime) return '-';
  if (datetime.length > 16) {
    return datetime.substring(0, 16);
  }
  return datetime;
};

const getProductPic = (order: OrderItem): string => {
  const first = order.products?.[0];
  return first?.pic || '/static/images/default-product.png';
};

const getProductCount = (order: OrderItem): number => {
  if (!order.products || order.products.length === 0) return 0;
  return order.products.reduce((sum, p) => sum + (p.productNum || 0), 0);
};

const loadStats = async () => {
  try {
    const res = await getOrderStats({ startDate: startDate.value, endDate: endDate.value });
    stats.value = res || {};
  } catch {
    // stats are non-critical
  }
};

const loadOrders = async () => {
  loading.value = true;
  try {
    const tab = tabs.find(t => t.key === currentTab.value);
    const params: Record<string, unknown> = {
      page: page.value,
      pageSize,
      startDate: startDate.value,
      endDate: endDate.value,
      ...tab?.params
    };

    if (params.status === -1) {
      delete params.status;
    }

    const res = await getOrderList(params);

    if (page.value === 1) {
      orderList.value = res.list || [];
    } else {
      orderList.value = [...orderList.value, ...(res.list || [])];
    }

    total.value = res.total || 0;
    hasMore.value = orderList.value.length < total.value;
  } catch {
    // fail silently, list remains as-is
  } finally {
    loading.value = false;
  }
};

const loadMore = () => {
  if (loading.value || !hasMore.value) return;
  page.value++;
  loadOrders();
};

const changeTab = (key: string) => {
  currentTab.value = key;
  page.value = 1;
  hasMore.value = true;
  loadOrders();
  loadStats();
};

const goDetail = (orderId: string) => {
  uni.navigateTo({ url: `/pages/orders/detail?id=${orderId}` });
};

const onStartDateChange = (e: { detail: { value: string } }) => {
  startDate.value = e.detail.value;
};

const onEndDateChange = (e: { detail: { value: string } }) => {
  endDate.value = e.detail.value;
};

const confirmDateRange = () => {
  showDatePicker.value = false;
  page.value = 1;
  hasMore.value = true;
  loadOrders();
  loadStats();
};

onMounted(() => {
  loadOrders();
  loadStats();
});
</script>

<style lang="scss" scoped>
$font-stack: -apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', system-ui, sans-serif;

.page {
  height: 100vh;
  background: $bg-color-page;
  display: flex;
  flex-direction: column;
  overflow-x: hidden;
  padding-bottom: env(safe-area-inset-bottom);
  font-family: $font-stack;
}

// ====== Tab bar ======
.tab-bar {
  display: flex;
  background: $bg-color-card;
  border-bottom: 1rpx solid $border-color-light;

  .tab-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: $spacing-3 0 $spacing-2;
    position: relative;

    text {
      font-size: $font-size-base;
      color: $text-color-secondary;
    }

    &.active {
      text {
        color: $text-color-primary;
        font-weight: 600;
      }

      .tab-line {
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 60rpx;
        height: 4rpx;
        background: $primary-color;
        border-radius: 2rpx;
      }
    }
  }
}

// ====== Time filter ======
.time-filter {
  padding: $spacing-2 $spacing-3;
  background: $bg-color-card;

  .time-label {
    font-size: $font-size-sm;
    color: $text-color-muted;
  }
}

// ====== Stats bar ======
.stats-bar {
  display: flex;
  background: $bg-color-card;
  padding: $spacing-2 0;

  .stat-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;

    .stat-value {
      font-size: $font-size-xl;
      font-weight: 700;
      color: $text-color-primary;
      margin-bottom: $spacing-1;
    }

    .stat-label {
      font-size: $font-size-sm;
      color: $text-color-muted;
    }
  }
}

// ====== List header ======
.list-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: $spacing-2 $spacing-3;

  .list-info {
    font-size: $font-size-sm;
    color: $text-color-muted;
  }

  .filter-btn {
    display: flex;
    align-items: center;
    padding: $spacing-1 $spacing-2;
    background: $bg-color-card;
    border-radius: $radius-sm;
    font-size: $font-size-sm;
    color: $text-color-secondary;

    &:active { opacity: 0.7; }
  }
}

// ====== Order list ======
.order-scroll {
  flex: 1;
  height: 0;
}

.order-list {
  padding: $spacing-2 $spacing-3;
}

.order-card {
  background: $bg-color-card;
  border-radius: $radius-md;
  margin-bottom: $spacing-2;
  padding: $spacing-2;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

  &:active { opacity: 0.7; }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: $spacing-2;

    .order-time {
      font-size: $font-size-base;
      color: $text-color-primary;
    }

    .order-status {
      font-size: $font-size-sm;
      font-weight: 500;

      &.completed { color: $success-color; }
      &.pending { color: $warning-color; }
      &.cancelled { color: $text-color-muted; }
      &.closed { color: $text-color-tertiary; }
    }
  }

  .card-product {
    display: flex;
    align-items: center;
    margin-bottom: $spacing-2;

    .product-img {
      width: 120rpx;
      height: 120rpx;
      border-radius: $radius-sm;
      background: $bg-color-page;
      margin-right: 20rpx;
    }

    .product-right {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: flex-end;

      .product-amount {
        font-size: $font-size-lg;
        font-weight: 600;
        color: $text-color-primary;
        margin-bottom: $spacing-1;
      }

      .product-count {
        font-size: $font-size-sm;
        color: $text-color-muted;
      }
    }
  }

  .card-info {
    margin-bottom: $spacing-2;

    .info-line {
      display: flex;
      align-items: center;
      margin-bottom: $spacing-1;

      &:last-child { margin-bottom: 0; }

      .info-label {
        font-size: $font-size-sm;
        color: $text-color-secondary;
        margin-right: $spacing-1;
        flex-shrink: 0;
      }

      .info-value {
        font-size: $font-size-sm;
        color: $text-color-primary;
      }
    }
  }

  .card-action {
    display: flex;
    justify-content: flex-end;

    .view-btn {
      padding: $spacing-1 $spacing-4;
      background: $bg-color-page;
      border-radius: $radius-sm;

      &:active { opacity: 0.7; }

      text {
        font-size: $font-size-sm;
        color: $text-color-secondary;
        font-weight: 500;
      }
    }
  }
}

// ====== Loading ======
.loading-more {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: $spacing-1;
  padding: $spacing-4;
  color: $text-color-muted;
  font-size: $font-size-sm;

  .loading-spinner {
    width: 32rpx;
    height: 32rpx;
    border: 3rpx solid $border-color;
    border-top-color: $primary-color;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.no-more {
  text-align: center;
  padding: $spacing-4;
  font-size: $font-size-sm;
  color: $text-color-placeholder;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 0;

  .empty-text {
    font-size: $font-size-base;
    color: $text-color-muted;
  }
}

// ====== Date modal ======
.date-modal {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.45);
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 $spacing-6;
}

.modal-content {
  width: 100%;
  background: $bg-color-card;
  border-radius: $radius-xl;
  overflow: hidden;

  .modal-header {
    padding: $spacing-3;
    border-bottom: 1rpx solid $border-color-light;

    .modal-title {
      font-size: $font-size-lg;
      font-weight: 600;
      color: $text-color-primary;
    }
  }

  .modal-body {
    padding: $spacing-3;

    .date-row {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: $spacing-2 0;
      border-bottom: 1rpx solid $border-color-light;

      &:last-child { border-bottom: none; }

      text {
        font-size: $font-size-base;
        color: $text-color-primary;
      }

      .picker-value {
        font-size: $font-size-base;
        color: $text-color-primary;
        padding: $spacing-1 $spacing-2;
        background: $bg-color-page;
        border-radius: $radius-sm;
      }
    }
  }

  .modal-footer {
    display: flex;
    padding: $spacing-2 $spacing-3 $spacing-3;
    gap: $spacing-1;

    button {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      border-radius: $radius-base;
      font-size: $font-size-base;
      font-weight: 500;
      border: none;
      padding: 0;

      &::after { border: none; }
    }

    .btn-cancel {
      background: $bg-color-page;
      color: $text-color-secondary;
    }

    .btn-confirm {
      background: $primary-color;
      color: $text-color-primary;
    }
  }
}
</style>
