<template>
  <view class="order-list-container" @pullDownRefresh="onPullDownRefresh">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-input-wrapper">
        <text class="search-icon">🔍</text>
        <input 
          type="text" 
          placeholder="请输入用户手机号" 
          v-model="searchKeyword"
          @confirm="handleSearch"
          clearable
        />
      </view>
      <button class="search-btn" @click="handleSearch">搜索</button>
    </view>
    
    <!-- 订单列表 -->
    <view class="order-list">
      <view 
        v-for="order in orderList" 
        :key="order.orderId" 
        class="order-card"
        @click="viewOrderDetail(order.orderId)"
      >
        <!-- 订单头部 -->
        <view class="order-header">
          <view class="order-id-section">
            <text class="order-id-label">订单号</text>
            <text class="order-id">{{ order.orderId }}</text>
          </view>
          <text 
            class="order-status" 
            :class="getOrderStatusClass(order.orderStatus)"
            :style="getOrderStatusStyle(order.orderStatus)"
          >
            {{ getOrderStatusText(order.orderStatus) }}
          </text>
        </view>
        
        <!-- 订单核心信息 -->
        <view class="order-core-info">
          <view class="info-item">
            <text class="info-label">设备编号</text>
            <text class="info-value">{{ order.shortId || '未知设备' }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">用户手机号</text>
            <text class="info-value">{{ order.mobilePhone || '匿名用户' }}</text>
          </view>
        </view>
        
        <!-- 时间信息 -->
        <view class="order-time-info">
          <view class="info-item">
            <text class="info-label">开始时间</text>
            <text class="info-value">{{ formatTime(order.createTime) }}</text>
          </view>
          <view class="info-item" v-if="order.endTime">
            <text class="info-label">结束时间</text>
            <text class="info-value">{{ formatTime(order.endTime) }}</text>
          </view>
        </view>
        
        <!-- 金额信息 -->
        <view class="order-amount-info">
          <view class="amount-item">
            <text class="amount-label">消费总额</text>
            <text class="amount-value">¥{{ formatAmount(order.amount) }}</text>
          </view>
          <view class="amount-item">
            <text class="amount-label">实收金额</text>
            <text class="amount-value highlight">¥{{ formatAmount(order.amountReceived) }}</text>
          </view>
          <!-- 显示应收金额 -->
          <view class="amount-item" v-if="order.amountReceivable !== undefined">
            <text class="amount-label">应收金额</text>
            <text class="amount-value">¥{{ formatAmount(order.amountReceivable) }}</text>
          </view>
        </view>
        
        <!-- 订单底部 -->
        <view class="order-footer">
          <text class="update-time">更新于: {{ formatTime(order.updateTime) }}</text>
          <button 
            v-if="order.orderStatus == '4'" 
            class="refund-btn"
            @click.stop="handleRefund(order.refundLogId)"
          >
            处理退款
          </button>
        </view>
      </view>
    </view>
    
    <!-- 加载更多 -->
    <view class="load-more-container">
      <view 
        class="load-more" 
        v-if="orderList.length > 0"
        @click="loadMore"
      >
        <text v-if="loadMoreStatus === 'loading'">正在加载...</text>
        <text v-else-if="loadMoreStatus === 'noMore'">没有更多数据了</text>
        <text v-else>点击加载更多</text>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="orderList.length === 0 && !loading">
        <text class="empty-icon">📭</text>
        <text class="empty-text">暂无订单数据</text>
        <button class="refresh-btn" @click="loadOrderList">刷新</button>
      </view>
      
      <!-- 加载状态 -->
      <view class="loading-state" v-if="loading && orderList.length === 0">
        <text class="loading-spinner">🔄</text>
        <text class="loading-text">加载中...</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { getOrderList, handleRefund as refundApi } from '../../api/order.js'
import { formatTime, showToast, formatAmount, storage } from '../../utils/index.js'

const orderList = ref([])
const loading = ref(true)
const page = ref(1)
const pageSize = ref(10)
const hasMore = ref(true)
const loadMoreStatus = ref('more')
const searchKeyword = ref('')

// 表单查询参数，与admin-web保持一致
const state = reactive({
  formQuery: {
    mobilePhone: '',
    orderId: '',
    orderStatus: '',
    payStatus: '',
    stationId: '',
    userStationId: '',
    invoiceStatus: ''
  }
})

const loadMoreText = {
  contentdown: '上拉加载更多',
  contentrefresh: '正在加载...',
  contentnomore: '没有更多数据了'
}

onMounted(() => {
  // 加载订单列表
  loadOrderList()
})

const loadOrderList = async (isLoadMore = false) => {
  // 如果没有更多数据，不执行加载
  if (isLoadMore && !hasMore.value) {
    return
  }
  
  if (!isLoadMore) {
    page.value = 1
    orderList.value = []
    loading.value = true
    // 重置加载更多状态
    hasMore.value = true
    loadMoreStatus.value = 'more'
  } else {
    // 显示加载中状态
    loadMoreStatus.value = 'loading'
  }
  
  try {
    // 更新表单查询参数中的搜索关键词（只支持手机号查询）
    state.formQuery.mobilePhone = searchKeyword.value
    state.formQuery.orderId = '' // 清空订单号搜索
    
    // 构建查询参数，与admin-web保持完全一致
    const params = {
      pageNum: page.value,
      pageSize: pageSize.value,
      ...state.formQuery
    }
    
    const res = await getOrderList(params)
    
    if (res && res.code === 200) {
      const data = res.data
      
      // 严格使用admin-web返回的数据结构
      const records = data.list || []
      const total = data.total || 0
      
      // 更新订单列表数据
      if (isLoadMore) {
        // 加载更多，追加数据
        orderList.value = [...orderList.value, ...records]
      } else {
        // 首次加载或刷新，替换数据
        orderList.value = records
      }
      
      // 计算总页数和是否还有更多数据
      const totalPages = Math.ceil(total / pageSize.value)
      hasMore.value = page.value < totalPages
      
      // 更新加载更多状态
      loadMoreStatus.value = hasMore.value ? 'more' : 'noMore'
      
      // 如果还有更多数据，页码+1
      if (hasMore.value && isLoadMore) {
        page.value++
      }
    } else {
      console.error('订单列表API返回错误:', res)
      // 加载失败，恢复加载更多状态
      loadMoreStatus.value = hasMore.value ? 'more' : 'noMore'
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    showToast('获取订单列表失败')
    // 加载失败，恢复加载更多状态
    loadMoreStatus.value = hasMore.value ? 'more' : 'noMore'
  } finally {
    loading.value = false
    // 停止下拉刷新动画
    uni.stopPullDownRefresh()
  }
}

const loadMore = () => {
  if (hasMore.value && !loading.value) {
    loadMoreStatus.value = 'loading'
    loadOrderList(true)
  }
}

const handleSearch = () => {
  loadOrderList()
}



const viewOrderDetail = (orderId) => {
  console.log('点击查看订单详情，订单ID:', orderId)
  
  if (!orderId) {
    console.error('订单ID为空，无法跳转')
    showToast('订单ID不存在')
    return
  }
  
  const targetUrl = `/pages/order/detail?orderId=${orderId}`
  console.log('跳转到:', targetUrl)
  
  uni.navigateTo({
    url: targetUrl,
    fail: (err) => {
      console.error('跳转失败:', err)
      showToast('跳转失败，请重试')
    }
  })
}

const handleRefund = async (refundLogId) => {
  try {
    await refundApi(refundLogId)
    showToast('退款处理成功', 'success')
    // 刷新订单列表
    loadOrderList()
  } catch (error) {
    console.error('处理退款失败:', error)
    showToast('处理退款失败')
  }
}

// 从字典获取订单状态文本
const getOrderStatusText = (status) => {
  if (!status) return '未知状态'
  
  try {
    const dicts = storage.get('dicts')
    if (!dicts || !dicts['Order.status']) {
      console.warn('字典数据未加载或不存在 Order.status')
      return status
    }
    
    const orderStatusDict = dicts['Order.status']
    const dictItem = orderStatusDict.find(item => item.value == status)
    
    return dictItem ? dictItem.name : status
  } catch (error) {
    console.error('获取订单状态文本失败:', error)
    return status
  }
}

// 从字典获取订单状态样式（基于字典颜色）
const getOrderStatusClass = (status) => {
  if (!status) return ''
  
  try {
    const dicts = storage.get('dicts')
    if (!dicts || !dicts['Order.status']) {
      return ''
    }
    
    const orderStatusDict = dicts['Order.status']
    const dictItem = orderStatusDict.find(item => item.value == status)
    
    // 如果字典项有颜色，返回自定义样式类名
    if (dictItem && dictItem.color) {
      return 'status-custom'
    }
    
    // 使用默认样式映射
    const statusClassMap = {
      '0': 'status-wait',        // 待支付
      '1': 'status-processing',  // 进行中
      '2': 'status-completed',   // 已完成
      '3': 'status-refunded',    // 已退款
      '4': 'status-refunding',   // 退款中
      '5': 'status-canceled'     // 已取消
    }
    return statusClassMap[status] || ''
  } catch (error) {
    console.error('获取订单状态样式失败:', error)
    return ''
  }
}

// 从字典获取订单状态内联样式（基于字典颜色）
const getOrderStatusStyle = (status) => {
  if (!status) return {}
  
  try {
    const dicts = storage.get('dicts')
    if (!dicts || !dicts['Order.status']) {
      return {}
    }
    
    const orderStatusDict = dicts['Order.status']
    const dictItem = orderStatusDict.find(item => item.value == status)
    
    // 如果字典项有颜色，使用字典颜色
    if (dictItem && dictItem.color) {
      return {
        color: dictItem.color,
        backgroundColor: `${dictItem.color}1A`, // 添加10%透明度
        borderColor: dictItem.color
      }
    }
    
    return {}
  } catch (error) {
    console.error('获取订单状态内联样式失败:', error)
    return {}
  }
}



// 下拉刷新处理函数
const onPullDownRefresh = () => {
  // 重新加载数据，不使用加载更多模式
  loadOrderList(false)
}
</script>

<style scoped>
/* 容器样式 */
.order-list-container {
  padding: 30rpx;
  background-color: #F8F9FA;
  min-height: 100vh;
  width: 100%;
  box-sizing: border-box;
  padding-bottom: 120rpx;
}

/* 搜索栏样式 */
.search-bar {
  display: flex;
  margin-bottom: 30rpx;
  background-color: #FFFFFF;
  border-radius: 24rpx;
  padding: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
  align-items: center;
}

.search-input-wrapper {
  flex: 1;
  display: flex;
  align-items: center;
  background-color: #F5F5F5;
  border-radius: 16rpx;
  padding: 0 24rpx;
  margin-right: 20rpx;
}

.search-icon {
  font-size: 28rpx;
  margin-right: 16rpx;
}

.search-bar input {
  flex: 1;
  height: 70rpx;
  border: none;
  outline: none;
  font-size: 28rpx;
  color: #1A1A1A;
  background-color: transparent;
}

.search-btn {
  padding: 20rpx 40rpx;
  background: linear-gradient(135deg, #667EEA 0%, #764BA2 100%);
  color: #FFFFFF;
  border: none;
  border-radius: 16rpx;
  font-size: 28rpx;
  font-weight: 500;
  transition: all 0.3s;
}

.search-btn:active {
  transform: scale(0.95);
  opacity: 0.9;
}

/* 订单列表样式 */
.order-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

/* 订单卡片样式 */
.order-card {
  background-color: #FFFFFF;
  border-radius: 24rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
  transition: all 0.3s;
}

.order-card:active {
  transform: translateY(-4rpx);
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
}

/* 订单头部 */
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24rpx;
  padding-bottom: 24rpx;
  border-bottom: 2rpx solid #F0F0F0;
}

.order-id-section {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
  flex: 1;
}

.order-id-label {
  font-size: 24rpx;
  color: #999999;
}

.order-id {
  font-size: 26rpx;
  color: #1A1A1A;
  font-weight: 600;
  word-break: break-all;
  line-height: 1.4;
}

/* 订单状态 */
.order-status {
  font-size: 22rpx;
  padding: 8rpx 24rpx;
  border-radius: 30rpx;
  font-weight: 600;
  white-space: nowrap;
}

/* 状态颜色 */
.status-wait {
  color: #FAAD14;
  background: linear-gradient(135deg, #FFF7E6 0%, #FFE7BA 100%);
}

.status-processing {
  color: #1890FF;
  background: linear-gradient(135deg, #E6F7FF 0%, #BAE7FF 100%);
}

.status-completed {
  color: #52C41A;
  background: linear-gradient(135deg, #F6FFED 0%, #D9F7BE 100%);
}

.status-refunded,
.status-canceled {
  color: #999999;
  background: linear-gradient(135deg, #F5F5F5 0%, #E0E0E0 100%);
}

.status-refunding {
  color: #F5222D;
  background: linear-gradient(135deg, #FFF1F0 0%, #FFCCC7 100%);
}

.status-custom {
  font-weight: 600;
}

/* 核心信息样式 */
.order-core-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 24rpx;
  padding-bottom: 24rpx;
  border-bottom: 2rpx solid #F0F0F0;
}

.order-time-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 24rpx;
  padding-bottom: 24rpx;
  border-bottom: 2rpx solid #F0F0F0;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
  min-width: 0;
  flex: 1;
}

.info-label {
  font-size: 24rpx;
  color: #999999;
}

.info-value {
  font-size: 28rpx;
  color: #1A1A1A;
  font-weight: 500;
  word-break: break-all;
}

/* 金额信息 */
.order-amount-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 24rpx;
  padding: 20rpx;
  background: linear-gradient(135deg, #FFF7E6 0%, #FFE7BA 100%);
  border-radius: 16rpx;
}

.amount-item {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
  text-align: center;
}

.amount-label {
  font-size: 24rpx;
  color: #666666;
}

.amount-value {
  font-size: 32rpx;
  color: #1A1A1A;
  font-weight: 600;
}

.amount-value.highlight {
  font-size: 36rpx;
  color: #E70316;
  font-weight: 700;
}

/* 订单底部 */
.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12rpx;
}

.update-time {
  font-size: 22rpx;
  color: #CCCCCC;
}

.refund-btn {
  padding: 12rpx 32rpx;
  background: linear-gradient(135deg, #F5222D 0%, #FF4D4F 100%);
  color: #FFFFFF;
  border: none;
  border-radius: 16rpx;
  font-size: 24rpx;
  font-weight: 500;
  transition: all 0.3s;
}

.refund-btn:active {
  transform: scale(0.95);
  opacity: 0.9;
}

/* 加载更多容器 */
.load-more-container {
  margin-top: 30rpx;
}

/* 加载更多 */
.load-more {
  text-align: center;
  padding: 40rpx;
  color: #666666;
  font-size: 28rpx;
  background-color: #FFFFFF;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
  transition: all 0.3s;
}

.load-more:active {
  transform: translateY(-4rpx);
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
  color: #999999;
  text-align: center;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 32rpx;
  opacity: 0.5;
}

.empty-text {
  font-size: 28rpx;
  margin-bottom: 40rpx;
}

.refresh-btn {
  padding: 20rpx 60rpx;
  background: linear-gradient(135deg, #667EEA 0%, #764BA2 100%);
  color: #FFFFFF;
  border: none;
  border-radius: 16rpx;
  font-size: 28rpx;
  font-weight: 500;
  transition: all 0.3s;
}

.refresh-btn:active {
  transform: scale(0.95);
  opacity: 0.9;
}

/* 加载状态 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
  color: #999999;
}

.loading-spinner {
  font-size: 64rpx;
  margin-bottom: 32rpx;
  animation: spin 1s linear infinite;
}

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

.loading-text {
  font-size: 28rpx;
}
</style>