<template>
  <view class="page">
    <!-- 头部标题 -->
    <view class="header">
      <text class="title">消息通知</text>
      <text class="count" v-if="pendingCount > 0">{{ pendingCount }}条待处理</text>
    </view>

    <!-- 消息列表 -->
    <scroll-view scroll-y class="content" @scrolltolower="loadMore">
      <view v-if="list.length === 0 && !loading" class="empty">
        <image src="/static/icons/messages.png" class="icon" />
        <text class="empty-text">暂无消息</text>
      </view>

      <!-- 待审批申请列表 -->
      <view v-for="item in list" :key="item.id" class="message-card" @tap="goToApprove(item.id)">
        <view class="card-header">
          <view class="type-badge">
            <text class="badge-icon">📋</text>
            <text class="badge-text">待审批</text>
          </view>
          <text class="time">{{ formatTime(item.createdAt) }}</text>
        </view>

        <view class="card-body">
          <text class="message-title">临时易耗品申请</text>
          <view class="message-content">
            <view class="content-row">
              <text class="label">申请人：</text>
              <text class="value">{{ item.applicantName || '未填写' }}</text>
            </view>
            <view class="content-row">
              <text class="label">部门：</text>
              <text class="value">{{ item.department || '-' }}</text>
            </view>
            <view class="content-row">
              <text class="label">物料：</text>
              <text class="value highlight">{{ item.items?.length || 0 }} 项</text>
            </view>
            <view class="content-row" v-if="item.reason">
              <text class="label">原因：</text>
              <text class="value reason">{{ item.reason }}</text>
            </view>
          </view>
        </view>

        <view class="card-footer">
          <text class="action-text">点击查看详情 →</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>
</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'
import { getPendingCount, refreshNow } from '@/utils/messageManager'

const list = ref<ConsumableRequest[]>([])
const loading = ref(false)
const page = ref(1)
const pageSize = ref(20)
const hasMore = ref(true)
const pendingCount = ref(0)
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: 'PENDING' // 只显示待审批的
    })
    
    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
      
      // 更新待审批数量
      pendingCount.value = getPendingCount()
    } else {
      uni.showToast({ title: '加载失败', icon: 'none' })
    }
  } catch (err) {
    console.error('加载消息失败：', err)
    uni.showToast({ title: '加载失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

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

// 格式化时间
function formatTime(time?: string) {
  if (!time) return '-'
  const date = new Date(time)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  // 一分钟内
  if (diff < 60000) {
    return '刚刚'
  }
  // 一小时内
  if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  }
  // 一天内
  if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  }
  // 超过一天
  return `${date.getMonth() + 1}-${date.getDate()} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

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

// 生命周期
onLoad(() => {
  // 刷新消息数量
  refreshNow().then(() => {
    pendingCount.value = getPendingCount()
  })
  
  // 加载列表
  loadList(true)
  
  // 监听消息变更事件
  uni.$on('tempMessage:changed', () => {
    needRefresh.value = true
  })
})

onShow(() => {
  // 每次显示时都刷新消息数量
  pendingCount.value = getPendingCount()
  
  if (needRefresh.value) {
    loadList(true)
    needRefresh.value = false
  }
})

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

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

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

.count {
  font-size: 26rpx;
  color: #f57c00;
  background: #fff3e0;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
}

.content {
  flex: 1;
  padding: 24rpx 32rpx;
}

.empty {
  height: 60vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 24rpx;
}

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

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

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

.message-card:active {
  transform: scale(0.98);
}

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

.type-badge {
  display: flex;
  align-items: center;
  gap: 8rpx;
  background: #fff3e0;
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
}

.badge-icon {
  font-size: 24rpx;
}

.badge-text {
  font-size: 24rpx;
  color: #f57c00;
  font-weight: 500;
}

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

.card-body {
  margin-bottom: 16rpx;
}

.message-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #111;
  margin-bottom: 12rpx;
  display: block;
}

.message-content {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.content-row {
  display: flex;
  font-size: 26rpx;
}

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

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

.value.highlight {
  color: #3a5ddd;
  font-weight: 600;
}

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

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

.action-text {
  font-size: 26rpx;
  color: #3a5ddd;
}

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