<template>
  <view class="page">
    <!-- 导航栏 -->
    <NavBar title="订单管理" />
    
    <!-- 筛选栏 -->
    <view class="filter-header">
      <view class="filter-tabs">
        <view 
          class="filter-tab" 
          :class="{ active: currentStatus === -1 }"
          @click="changeStatus(-1)"
        >
          <text>全部</text>
        </view>
        <view 
          class="filter-tab" 
          :class="{ active: currentStatus === 2 }"
          @click="changeStatus(2)"
        >
          <text>已完成</text>
        </view>
        <view 
          class="filter-tab" 
          :class="{ active: currentStatus === 4 }"
          @click="changeStatus(4)"
        >
          <text>退款中</text>
        </view>
      </view>
      <view class="search-btn" @click="showSearch = true">
        <view class="search-icon"></view>
      </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-main">
            <view class="card-left">
              <view class="card-row">
                <text class="order-no">{{ order.orderNo }}</text>
                <view class="status-tag" :class="getStatusClass(order.status)">
                  <text>{{ getStatusText(order.status) }}</text>
                </view>
              </view>
              <view class="card-row">
                <text class="order-meta">{{ order.shopName }} · {{ order.deviceName }}</text>
              </view>
            </view>
            <view class="card-right">
              <text class="amount">¥{{ formatMoney(order.totalAmount) }}</text>
              <text class="time-text">{{ order.createdAt }}</text>
            </view>
          </view>
          
          <view class="card-action" v-if="order.status === 4">
            <view class="action-btn" @click.stop="handleRefund(order)">
              <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">
        <view class="empty-icon">
          <view class="empty-icon-inner"></view>
        </view>
        <text class="empty-text">暂无订单数据</text>
      </view>
    </scroll-view>
    
    <!-- 搜索弹窗 -->
    <view class="search-modal" v-if="showSearch" @click="showSearch = false">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">搜索订单</text>
        </view>
        <view class="modal-body">
          <input 
            class="search-input" 
            v-model="searchOrderNo" 
            placeholder="请输入订单号"
            placeholder-class="input-placeholder"
            @confirm="doSearch"
          />
        </view>
        <view class="modal-footer">
          <button class="btn-cancel" @click="showSearch = false">取消</button>
          <button class="btn-confirm" @click="doSearch">搜索</button>
        </view>
      </view>
    </view>
    
    <!-- 自定义TabBar -->
    <CustomTabBar />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import NavBar from '@/components/NavBar.vue';
import CustomTabBar from '@/components/CustomTabBar.vue';
import { getOrderList, handleRefund as refundOrder } from '@/api/order';
import { OrderStatusText, OrderStatusColor, OrderStatus } from '@/mock/order';
import { formatMoney as formatMoneyUtil, showConfirm, showToast } from '@/utils/common';

const orderList = ref<any[]>([]);
const currentStatus = ref(-1);
const searchOrderNo = ref('');
const showSearch = ref(false);
const loading = ref(false);
const hasMore = ref(true);
const page = ref(1);
const pageSize = 10;

const formatMoney = formatMoneyUtil;

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

const getStatusClass = (status: number) => {
  const classMap: Record<number, string> = {
    [OrderStatus.PENDING]: 'pending',
    [OrderStatus.PAID]: 'processing',
    [OrderStatus.COMPLETED]: 'completed',
    [OrderStatus.CANCELLED]: 'cancelled',
    [OrderStatus.REFUNDING]: 'refunding',
    [OrderStatus.REFUNDED]: 'completed'
  };
  return classMap[status] || 'pending';
};

const changeStatus = (status: number) => {
  currentStatus.value = status;
  page.value = 1;
  hasMore.value = true;
  loadOrders();
};

const loadOrders = async () => {
  loading.value = true;
  try {
    const res = await getOrderList({
      page: page.value,
      pageSize,
      status: currentStatus.value,
      orderNo: searchOrderNo.value
    });
    
    if (page.value === 1) {
      orderList.value = res.list;
    } else {
      orderList.value = [...orderList.value, ...res.list];
    }
    
    hasMore.value = orderList.value.length < res.total;
  } catch (error) {
    console.error('加载订单失败', error);
  } finally {
    loading.value = false;
  }
};

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

const doSearch = () => {
  showSearch.value = false;
  page.value = 1;
  hasMore.value = true;
  loadOrders();
};

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

const handleRefund = async (order: any) => {
  const confirmed = await showConfirm(`确认同意订单 ${order.orderNo} 的退款申请？`);
  if (confirmed) {
    try {
      await refundOrder(order.id, true);
      showToast('退款处理成功', 'success');
      loadOrders();
    } catch (error) {
      showToast('退款处理失败', 'error');
    }
  }
};

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

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: #f8fafc;
  display: flex;
  flex-direction: column;
  padding-bottom: 200rpx;
}

/* 筛选栏 */
.filter-header {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  gap: 12rpx;
  background: #ffffff;
  border-bottom: 1rpx solid #e2e8f0;
}

.filter-tabs {
  flex: 1;
  display: flex;
  gap: 10rpx;
  
  .filter-tab {
    padding: 14rpx 24rpx;
    background: #f8fafc;
    border: 2rpx solid #e2e8f0;
    border-radius: 20rpx;
    font-size: 26rpx;
    color: #64748b;
    transition: all 0.15s;
    
    &.active {
      background: #ecfdf5;
      border-color: #10b981;
      color: #10b981;
    }
  }
}

.search-btn {
  width: 72rpx;
  height: 72rpx;
  background: #ecfdf5;
  border: 2rpx solid #10b981;
  border-radius: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .search-icon {
    width: 28rpx;
    height: 28rpx;
    border: 3rpx solid #10b981;
    border-radius: 50%;
    position: relative;
    
    &::after {
      content: '';
      position: absolute;
      bottom: -6rpx;
      right: -6rpx;
      width: 10rpx;
      height: 3rpx;
      background: #10b981;
      transform: rotate(45deg);
    }
  }
}

/* 订单列表 */
.order-scroll {
  flex: 1;
  height: 0;
}

.order-list {
  padding: 16rpx 24rpx;
}

.order-card {
  background: #ffffff;
  border: 1rpx solid #e2e8f0;
  border-radius: 12rpx;
  margin-bottom: 10rpx;
  overflow: hidden;
  transition: transform 0.15s;
  
  &:active {
    transform: scale(0.98);
  }
}

.card-main {
  display: flex;
  padding: 14rpx 16rpx;
}

.card-left {
  flex: 1;
  min-width: 0;
}

.card-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: center;
  margin-left: 12rpx;
  min-width: 140rpx;
}

.card-row {
  display: flex;
  align-items: center;
  margin-bottom: 6rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.order-no {
  font-size: 24rpx;
  color: #64748b;
  font-family: monospace;
  margin-right: 10rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.order-meta {
  font-size: 26rpx;
  color: #1e293b;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.status-tag {
  padding: 2rpx 10rpx;
  border-radius: 4rpx;
  font-size: 20rpx;
  font-weight: 500;
  flex-shrink: 0;
  
  &.completed {
    background: #ecfdf5;
    color: #10b981;
  }
  
  &.refunding {
    background: #fff7ed;
    color: #f97316;
  }
  
  &.processing {
    background: #f0f9ff;
    color: #0ea5e9;
  }
  
  &.pending {
    background: #faf5ff;
    color: #a855f7;
  }
  
  &.cancelled {
    background: #fef2f2;
    color: #ef4444;
  }
}

.amount {
  font-size: 30rpx;
  font-weight: 700;
  color: #f97316;
  margin-bottom: 4rpx;
}

.time-text {
  font-size: 20rpx;
  color: #94a3b8;
}

.card-action {
  padding: 8rpx 16rpx 14rpx;
  display: flex;
  justify-content: flex-end;
  
  .action-btn {
    padding: 8rpx 20rpx;
    background: #ef4444;
    border-radius: 6rpx;
    font-size: 22rpx;
    font-weight: 500;
    color: #fff;
  }
}

/* 加载状态 */
.loading-more {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  padding: 32rpx;
  color: #94a3b8;
  font-size: 24rpx;
  
  .loading-spinner {
    width: 32rpx;
    height: 32rpx;
    border: 3rpx solid #e2e8f0;
    border-top-color: #10b981;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }
}

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

.no-more {
  text-align: center;
  padding: 32rpx;
  font-size: 24rpx;
  color: #cbd5e1;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 0;
  
  .empty-icon {
    width: 120rpx;
    height: 120rpx;
    background: #f1f5f9;
    border-radius: 24rpx;
    margin-bottom: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .empty-icon-inner {
      width: 48rpx;
      height: 56rpx;
      border: 4rpx solid #cbd5e1;
      border-radius: 8rpx;
      position: relative;
      
      &::before {
        content: '';
        position: absolute;
        top: 14rpx;
        left: 8rpx;
        width: 20rpx;
        height: 4rpx;
        background: #cbd5e1;
        border-radius: 2rpx;
      }
      
      &::after {
        content: '';
        position: absolute;
        top: 24rpx;
        left: 8rpx;
        width: 14rpx;
        height: 4rpx;
        background: #cbd5e1;
        border-radius: 2rpx;
      }
    }
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #94a3b8;
  }
}

/* 搜索弹窗 */
.search-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 48rpx;
}

.modal-content {
  width: 100%;
  background: #ffffff;
  border-radius: 20rpx;
  overflow: hidden;
  
  .modal-header {
    padding: 24rpx;
    border-bottom: 1rpx solid #f1f5f9;
    
    .modal-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #1e293b;
    }
  }
  
  .modal-body {
    padding: 24rpx;
    
    .search-input {
      width: 100%;
      height: 88rpx;
      background: #f8fafc;
      border: 2rpx solid #e2e8f0;
      border-radius: 12rpx;
      padding: 0 20rpx;
      font-size: 28rpx;
      color: #1e293b;
      box-sizing: border-box;
    }
  }
  
  .modal-footer {
    display: flex;
    padding: 16rpx 24rpx 24rpx;
    gap: 12rpx;
    
    button {
      flex: 1;
      height: 80rpx;
      border-radius: 12rpx;
      font-size: 28rpx;
      font-weight: 500;
      border: none;
      
      &::after {
        border: none;
      }
    }
    
    .btn-cancel {
      background: #f8fafc;
      color: #64748b;
    }
    
    .btn-confirm {
      background: #10b981;
      color: #fff;
    }
  }
}

.input-placeholder {
  color: #cbd5e1;
}
</style>
