<template>
  <view class="order-list-container" @pullDownRefresh="onPullDownRefresh">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-input-wrapper">
        <AppIcon name="search" :size="28" color="#999999" class="search-icon" />
        <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-header-row">
            <text class="order-id-label">订单号</text>
            <text
              class="order-status"
              :style="getOrderStatusStyle(order.orderStatus)"
            >
              {{ getOrderStatusText(order.orderStatus) }}
            </text>
          </view>
          <view class="order-header-row">
            <view class="order-id-wrapper">
              <text class="order-id">{{ order.orderId }}</text>
              <AppIcon
                name="copy"
                :size="28"
                color="#C6171E"
                class="copy-icon"
                @click.stop="copyOrderId(order.orderId)"
              />
            </view>
            <text
              class="pay-status"
              :style="getPayStatusStyle(order.payStatus)"
            >
              {{ getPayStatusText(order.payStatus) }}
            </text>
          </view>
        </view>
        
        <!-- 订单核心信息 -->
        <view class="order-core-info">
          <view class="info-item">
            <text class="info-label">消费站点</text>
            <text class="info-value">{{ order.stationName || '未知站点' }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">归属站点</text>
            <text class="info-value">{{ order.userStationName || '未知站点' }}</text>
          </view>
        </view>
        <view class="order-core-info">
          <view class="info-item">
            <text class="info-label">用户手机号</text>
            <view class="info-value-row">
              <text class="info-value">{{ order.mobilePhone || '匿名用户' }}</text>
              <AppIcon v-if="order.mobilePhone" name="copy" :size="28" color="#C6171E" class="copy-icon" @click.stop="copyText(order.mobilePhone)" />
            </view>
          </view>
          <view class="info-item">
            <text class="info-label">设备编号</text>
            <view class="info-value-row">
              <text class="info-value">{{ order.shortId || '未知设备' }}</text>
              <AppIcon v-if="order.shortId" name="copy" :size="28" color="#C6171E" class="copy-icon" @click.stop="copyText(order.shortId)" />
            </view>
          </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" v-if="order.amountReceivable !== undefined">
            <text class="amount-label">应收金额</text>
            <text class="amount-value">¥{{ formatAmount(order.amountReceivable) }}</text>
          </view>
          <view class="amount-item">
            <text class="amount-label">实收金额</text>
            <text class="amount-value highlight">¥{{ formatAmount(order.amountReceived) }}</text>
          </view>
        </view>
        
        <!-- 订单底部 -->
        <view class="order-footer">
          <text class="update-time">更新于: {{ formatTime(order.updateTime) }}</text>
          <button 
            v-if="isRefundStatus(order.orderStatus)"
            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"
      >
        <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">
        <view class="empty-icon-wrapper">
          <AppIcon name="inbox" size="48" color="#B0B0B0" />
        </view>
        <text class="empty-text">暂无订单数据</text>
        <button class="empty-refresh-btn" @click="loadOrderList">刷新</button>
      </view>
      
      <!-- 加载状态 -->
      <view class="loading-state" v-if="loading && orderList.length === 0">
        <view class="loading-spinner"></view>
        <text class="loading-text">加载中...</text>
      </view>
    </view>

    <CustomTabBar :selected="1" />
  </view>
</template>

<script setup>
import CustomTabBar from '../../components/CustomTabBar.vue'
import { ref, onMounted, reactive } from 'vue'
import { onReachBottom } from '@dcloudio/uni-app'
import { getOrderList, handleRefund as refundApi } from '../../api/order.js'
import { formatTime, showToast, formatAmount, fmtDictName, getDictColor, copyText } from '../../utils/index.js'
import dictUtil, { loadDicts } from '../../utils/dict.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: ''
  }
})

onMounted(async () => {
  await loadDicts()
  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') {
    loadMoreStatus.value = 'loading'
    loadOrderList(true)
  }
}

// 滚动到底部自动加载
onReachBottom(() => {
  loadMore()
})

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



const copyOrderId = (orderId) => {
  copyText(orderId)
}

const viewOrderDetail = (orderId) => {
  if (!orderId) {
    showToast('订单ID不存在')
    return
  }

  uni.navigateTo({
    url: `/pages/order/detail?orderId=${orderId}`,
    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) => {
  return fmtDictName('Order.status', status)
}

// 从字典获取订单状态内联样式
const getOrderStatusStyle = (status) => {
  const color = getDictColor('Order.status', status)
  if (color) {
    return {
      color: color,
      backgroundColor: `${color}1A`
    }
  }
  return {}
}

// 从字典获取支付状态文本
const getPayStatusText = (status) => {
  return fmtDictName('Order.pay', status)
}

// 从字典获取支付状态内联样式
const getPayStatusStyle = (status) => {
  const color = getDictColor('Order.pay', status)
  if (color) {
    return {
      color: color,
      backgroundColor: `${color}1A`
    }
  }
  return {}
}

// 判断是否为退款状态
const isRefundStatus = (status) => {
  return status === dictUtil.getDictValue('Order.status', '退款中')
}



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

<style scoped>
/* 容器样式 */
.order-list-container {
  padding: 30rpx;
  background-color: #F5F7FA;
  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 1px 3px rgba(0,0,0,0.08), 0 1px 2px rgba(0,0,0,0.06);
  align-items: center;
}

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

.search-icon {
  margin-right: 16rpx;
  flex-shrink: 0;
}

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

.search-input-wrapper:focus-within {
  box-shadow: 0 0 0 6rpx rgba(198,23,30,0.2);
}

.search-btn {
  height: 70rpx;
  line-height: 70rpx;
  padding: 0 40rpx;
  background: #C6171E;
  color: #FFFFFF;
  border: none;
  border-radius: 16rpx;
  font-size: 28rpx;
  font-weight: 500;
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
}

.search-btn:active {
  background: #A81212;
  transform: scale(0.97);
}

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

/* 订单卡片样式 */
.order-card {
  background-color: #FFFFFF;
  border-radius: 48rpx;
  padding: 30rpx;
  transition: box-shadow 0.25s cubic-bezier(0.4, 0, 0.2, 1), transform 0.25s cubic-bezier(0.4, 0, 0.2, 1);
}

.order-card:active {
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(0,0,0,0.07), 0 2px 4px rgba(0,0,0,0.06);
}

/* 订单头部 */
.order-header {
  display: flex;
  flex-direction: column;
  margin-bottom: 24rpx;
  padding-bottom: 24rpx;
  border-bottom: 2rpx solid #F0F0F0;
}

.order-header-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}

.order-header-row:last-child {
  margin-bottom: 0;
}

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

.order-id-wrapper {
  display: flex;
  align-items: center;
  flex: 1;
  margin-right: 16rpx;
  min-width: 0;
}

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

.copy-icon {
  margin-left: 12rpx;
  flex-shrink: 0;
}

/* 订单状态 */
.order-status,
.pay-status {
  font-size: 24rpx;
  padding: 6rpx 24rpx;
  border-radius: 200rpx;
  font-weight: 500;
  white-space: nowrap;
}


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

.order-core-info--single {
  margin-bottom: 16rpx;
  padding-bottom: 16rpx;
}

.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;
}

.info-value-row {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

/* 金额信息 */
.order-amount-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 24rpx;
  padding: 20rpx;
  background: #FAF8F8;
  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 {
  color: #C6171E;
  font-weight: 700;
}

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

.update-time {
  font-size: 24rpx;
  color: #B0B0B0;
}

.refund-btn {
  padding: 12rpx 32rpx;
  background: #C6171E;
  color: #FFFFFF;
  border: none;
  border-radius: 16rpx;
  font-size: 24rpx;
  font-weight: 500;
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
}

.refund-btn:active {
  background: #A81212;
  transform: scale(0.97);
}

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

/* 加载更多指示器 */
.load-more {
  text-align: center;
  padding: 40rpx;
  color: #999999;
  font-size: 28rpx;
}

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

.empty-icon-wrapper {
  margin-bottom: 24rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999999;
  margin-bottom: 32rpx;
}

.empty-refresh-btn {
  padding: 20rpx 60rpx;
  background: #C6171E;
  color: #FFFFFF;
  border: none;
  border-radius: 32rpx;
  font-size: 28rpx;
  font-weight: 500;
}

.empty-refresh-btn:active {
  background: #A81212;
  transform: scale(0.97);
}

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

.loading-text {
  font-size: 28rpx;
}

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