<template>
  <view class="page">
    <!-- 顶部标题栏 -->
    <view class="header">
      <text class="title">临时易耗品申请</text>
      <view class="actions">
        <button class="btn-outline" @tap="goToCatalog">种类管理</button>
      </view>
    </view>

    <!-- 筛选区 -->
    <view class="filter-bar">
      <picker mode="selector" :range="statusOptions" range-key="label" @change="onStatusChange">
        <view class="filter-item">
          <text>{{ currentStatus?.label || '全部状态' }}</text>
          <text class="arrow">▼</text>
        </view>
      </picker>
    </view>

    <!-- 申请列表 -->
    <scroll-view scroll-y class="list-container" @scrolltolower="loadMore">
      <view v-if="list.length === 0 && !loading" class="empty">
        <image class="empty-icon" src="/static/icons/asset-inventory.png" mode="aspectFit" />
        <text class="empty-text">暂无申请记录</text>
      </view>
      
      <view v-for="item in list" :key="item.id" class="card" @tap="goToDetail(item.id)">
        <view class="card-header">
          <view class="status-badge" :class="`status-${item.status?.toLowerCase()}`">
            {{ getStatusText(item.status) }}
          </view>
          <text class="time">{{ formatTime(item.createdAt) }}</text>
        </view>
        
        <view class="card-body">
          <view class="info-row">
            <text class="label">申请人：</text>
            <text class="value">{{ item.applicantName || '-' }}</text>
          </view>
          <view class="info-row">
            <text class="label">电话：</text>
            <text class="value">{{ item.applicantPhone }}</text>
          </view>
          <view class="info-row">
            <text class="label">部门：</text>
            <text class="value">{{ item.department || '-' }}</text>
          </view>
          <view class="info-row">
            <text class="label">申请原因：</text>
            <text class="value reason">{{ item.reason || '-' }}</text>
          </view>
          <view class="info-row">
            <text class="label">物料数量：</text>
            <text class="value highlight">{{ item.items?.length || 0 }} 项</text>
          </view>
        </view>
        
        <view class="card-footer">
          <text class="detail-link">查看详情 →</text>
        </view>
      </view>

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

      <view v-if="!hasMore && list.length > 0" class="no-more">
        <text>没有更多了</text>
      </view>
    </scroll-view>

    <!-- 底部操作按钮 -->
    <view class="footer-actions">
      <button class="btn-primary" @tap="goToCreate">
        <text class="btn-icon">+</text>
        新建申请
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'
import consumableTempAPI, { type ConsumableRequest } from '@/pages/api/consumable-temp'

// 状态选项
const statusOptions = [
  { value: '', label: '全部状态' },
  { value: 'PENDING', label: '待审批' },
  { value: 'APPROVED', label: '待发放' },
  { value: 'REJECTED', label: '已拒绝' },
  { value: 'CANCELLED', label: '已取消' },
  { value: 'COMPLETED', label: '已完成' }
]

// 数据状态
const list = ref<ConsumableRequest[]>([])
const loading = ref(false)
const currentStatus = ref(statusOptions[0])
const page = ref(1)
const pageSize = ref(10)
const hasMore = ref(true)
const needRefresh = ref(false) // 是否需要刷新

// 加载列表
async function loadList(reset = false) {
  if (loading.value) return
  
  if (reset) {
    page.value = 1
    hasMore.value = true
    list.value = []
  }
  
  if (!hasMore.value) return
  
  loading.value = true
  
  try {
    const res = await consumableTempAPI.getRequestList({
      page: page.value,
      pageSize: pageSize.value,
      status: currentStatus.value.value || undefined
    })
    
    if (res.statusCode === 200 && (res.data as any)?.data) {
      const newData = (res.data as any).data
      list.value = reset ? newData : [...list.value, ...newData]
      hasMore.value = newData.length >= pageSize.value
    } else {
      uni.showToast({ title: '加载失败', icon: 'none' })
    }
  } catch (err) {
    console.error('加载列表失败：', err)
    uni.showToast({ title: '加载失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

// 状态改变
function onStatusChange(e: any) {
  const index = e.detail.value
  currentStatus.value = statusOptions[index]
  loadList(true)
}

// 加载更多
function loadMore() {
  if (!loading.value && hasMore.value) {
    page.value++
    loadList()
  }
}

// 格式化时间
function formatTime(time?: string) {
  if (!time) return '-'
  const date = new Date(time)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 获取状态文本
function getStatusText(status?: string) {
  const item = statusOptions.find(s => s.value === status)
  return item?.label || '未知'
}

// 跳转到详情
function goToDetail(id?: string) {
  if (!id) return
  uni.navigateTo({ 
    url: `/pages/consumables/temp-request-detail?id=${id}` 
  })
}

// 跳转到创建页面
function goToCreate() {
  uni.navigateTo({ 
    url: '/pages/consumables/temp-request-create' 
  })
}

// 跳转到种类管理
function goToCatalog() {
  uni.navigateTo({ 
    url: '/pages/consumables/temp-catalog' 
  })
}

// 生命周期
onLoad(() => {
  loadList(true)
  // 监听申请变更事件
  uni.$on('tempRequest:changed', () => {
    needRefresh.value = true
  })
})

onShow(() => {
  if (needRefresh.value) {
    loadList(true)
    needRefresh.value = false
  }
})

onUnload(() => {
  uni.$off('tempRequest:changed')
})
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: #f5f7fb;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

.header {
  background: #fff;
  padding: 32rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.title {
  font-size: 36rpx;
  font-weight: 600;
  color: #111;
}

.actions {
  display: flex;
  gap: 12rpx;
}

.btn-outline {
  padding: 12rpx 24rpx;
  background: #fff;
  color: #4b7aff;
  border: 2rpx solid #4b7aff;
  border-radius: 8rpx;
  font-size: 26rpx;
}

.filter-bar {
  background: #fff;
  padding: 24rpx 32rpx;
  margin-bottom: 12rpx;
}

.filter-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16rpx 24rpx;
  background: #f5f7fb;
  border-radius: 12rpx;
  font-size: 28rpx;
  color: #333;
}

.arrow {
  font-size: 20rpx;
  color: #999;
}

.list-container {
  flex: 1;
  padding: 0 32rpx 120rpx;
}

.empty {
  padding: 120rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 24rpx;
}

.empty-icon {
  width: 160rpx;
  height: 160rpx;
  opacity: 0.3;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.card {
  background: #fff;
  border-radius: 20rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.status-badge {
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
  font-weight: 500;
}

.status-pending {
  background: #fff3e0;
  color: #f57c00;
}

.status-approved {
  background: #e8f5e9;
  color: #2e7d32;
}

.status-rejected {
  background: #ffebee;
  color: #c62828;
}

.status-cancelled {
  background: #f5f5f5;
  color: #757575;
}

.status-completed {
  background: #e3f2fd;
  color: #1976d2;
}

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

.card-body {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.info-row {
  display: flex;
  font-size: 28rpx;
}

.label {
  color: #666;
  width: 160rpx;
  flex-shrink: 0;
}

.value {
  color: #333;
  flex: 1;
}

.value.reason {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  overflow: hidden;
}

.value.highlight {
  color: #4b7aff;
  font-weight: 600;
}

.card-footer {
  margin-top: 16rpx;
  padding-top: 16rpx;
  border-top: 1rpx solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
}

.detail-link {
  font-size: 26rpx;
  color: #4b7aff;
}

.loading,
.no-more {
  padding: 32rpx;
  text-align: center;
  font-size: 26rpx;
  color: #999;
}

.footer-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 24rpx 32rpx;
  padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
  background: #fff;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.06);
}

.btn-primary {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  background: #3a5ddd;
  color: #fff;
  border-radius: 16rpx;
  font-size: 32rpx;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
}

.btn-icon {
  font-size: 40rpx;
  font-weight: 300;
}
</style>
