<template>
  <view class="page">
    <!-- 顶部标题栏 -->
    <view class="header">
      <text class="title">临时易耗品审批</text>
    </view>

    <!-- 筛选区 -->
    <view class="filter-bar">
      <view class="switch-item">
        <text class="switch-label">显示已完成</text>
        <switch :checked="showCompleted" @change="onShowCompletedChange" color="#3a5ddd" />
      </view>
    </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/consumables-temp-approve.png" mode="aspectFit" />
        <text class="empty-text">暂无审批记录</text>
      </view>
      
      <view v-for="item in list" :key="item.id" class="card" @tap="goToApprove(item.id)">
        <!-- 进度条 -->
        <view class="progress-bar">
          <view class="progress-step" :class="{ active: true, completed: ['APPROVED', 'COMPLETED', 'REJECTED', 'CANCELLED'].includes(item.status || '') }">
            <view class="step-circle">
              <text class="step-icon">{{ ['REJECTED', 'CANCELLED'].includes(item.status || '') ? '✕' : '✓' }}</text>
            </view>
            <text class="step-label">待审批</text>
          </view>
          <view class="progress-line" :class="{ completed: ['APPROVED', 'COMPLETED'].includes(item.status || '') }"></view>
          <view class="progress-step" :class="{ active: ['APPROVED', 'COMPLETED'].includes(item.status || ''), completed: item.status === 'COMPLETED' }">
            <view class="step-circle">
              <text class="step-icon">✓</text>
            </view>
            <text class="step-label">待发放</text>
          </view>
          <view class="progress-line" :class="{ completed: item.status === 'COMPLETED' }"></view>
          <view class="progress-step" :class="{ active: item.status === 'COMPLETED', completed: item.status === 'COMPLETED' }">
            <view class="step-circle">
              <text class="step-icon">✓</text>
            </view>
            <text class="step-label">已完成</text>
          </view>
        </view>

        <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="applicant-info">
            <view class="avatar">
              <text class="avatar-text">{{ getAvatarText(item.applicantName) }}</text>
            </view>
            <view class="applicant-details">
              <text class="name">{{ item.applicantName || '未填写' }}</text>
              <text class="phone">{{ item.applicantPhone }}</text>
            </view>
          </view>
          
          <view class="info-grid">
            <view class="grid-item">
              <text class="grid-label">部门</text>
              <text class="grid-value">{{ item.department || '-' }}</text>
            </view>
            <view class="grid-item">
              <text class="grid-label">物料数量</text>
              <text class="grid-value highlight">{{ item.items?.length || 0 }} 项</text>
            </view>
          </view>
          
          <view class="reason-box">
            <text class="reason-label">申请原因：</text>
            <text class="reason-text">{{ item.reason || '-' }}</text>
          </view>
        </view>
        
        <view class="card-footer" v-if="item.status === 'PENDING'">
          <button class="btn-reject" @tap.stop="handleReject(item.id)">拒绝</button>
          <button class="btn-approve" @tap.stop="handleApprove(item.id)">通过</button>
        </view>
        <view class="card-footer" v-else-if="item.status === 'APPROVED'">
          <button class="btn-deliver" @tap.stop="handleDeliver(item.id)">确认发放</button>
        </view>
        <view class="card-footer" v-else>
          <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 v-if="showApproveModal" class="modal-mask" @tap="closeApproveModal">
      <view class="modal-content" @tap.stop>
        <view class="modal-header">
          <text class="modal-title">{{ approveType === 'APPROVED' ? '通过申请' : '拒绝申请' }}</text>
          <text class="modal-close" @tap="closeApproveModal">✕</text>
        </view>
        <view class="modal-body">
          <view class="form-item">
            <text class="form-label">审批意见</text>
            <textarea class="form-textarea" v-model="approveRemark" 
                      :placeholder="approveType === 'APPROVED' ? '请输入通过意见（可选）' : '请输入拒绝原因'"
                      maxlength="200" />
          </view>
        </view>
        <view class="modal-footer">
          <button class="btn-cancel" @tap="closeApproveModal">取消</button>
          <button class="btn-confirm" 
                  :class="approveType === 'REJECTED' ? 'btn-danger' : ''"
                  @tap="confirmApprove"
                  :disabled="submitting">
            {{ submitting ? '提交中...' : '确认' }}
          </button>
        </view>
      </view>
    </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 { refreshNow } from '@/utils/messageManager'

// 数据状态
const list = ref<ConsumableRequest[]>([])
const loading = ref(false)
const showCompleted = ref(false) // 是否显示已完成
const page = ref(1)
const pageSize = ref(10)
const hasMore = ref(true)
const needRefresh = ref(false) // 是否需要刷新

// 审批相关
const showApproveModal = ref(false)
const approveType = ref<'APPROVED' | 'REJECTED' | 'COMPLETED'>('APPROVED')
const approveRemark = ref('')
const currentApproveId = ref('')
const submitting = 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
    })
    
    if (res.statusCode === 200 && (res.data as any)?.data) {
      let newData = (res.data as any).data
      
      // 根据开关过滤数据：默认不显示 COMPLETED
      if (!showCompleted.value) {
        newData = newData.filter((item: ConsumableRequest) => item.status !== 'COMPLETED' && item.status !== 'REJECTED')
      }
      
      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 onShowCompletedChange(e: any) {
  showCompleted.value = e.detail.value
  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 statusMap: Record<string, string> = {
    'PENDING': '待审批',
    'APPROVED': '待发放',
    'REJECTED': '已拒绝',
    'CANCELLED': '已取消',
    'COMPLETED': '已完成'
  }
  return statusMap[status || ''] || '未知'
}

// 获取头像文本
function getAvatarText(name?: string) {
  if (!name) return '?'
  return name.substring(0, 1)
}

// 通过申请
function handleApprove(id?: string) {
  if (!id) return
  currentApproveId.value = id
  approveType.value = 'APPROVED'
  approveRemark.value = ''
  showApproveModal.value = true
}

// 拒绝申请
function handleReject(id?: string) {
  if (!id) return
  currentApproveId.value = id
  approveType.value = 'REJECTED'
  approveRemark.value = ''
  showApproveModal.value = true
}

// 确认发放
function handleDeliver(id?: string) {
  if (!id) return
  uni.showModal({
    title: '确认发放',
    content: '确认已发放该申请的易耗品？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await consumableTempAPI.updateRequestStatus(id, {
            status: 'COMPLETED'
          })
          
          if (result.statusCode === 200) {
            uni.showToast({ title: '已完成发放', icon: 'success' })
            loadList(true)
            // 刷新消息数量和通知消息页
            refreshNow()
            uni.$emit('tempMessage:changed')
          } else {
            uni.showToast({ title: '操作失败', icon: 'none' })
          }
        } catch (err) {
          console.error('发放失败：', err)
          uni.showToast({ title: '操作失败', icon: 'none' })
        }
      }
    }
  })
}

// 关闭审批弹窗
function closeApproveModal() {
  showApproveModal.value = false
  approveRemark.value = ''
  currentApproveId.value = ''
}

// 确认审批
async function confirmApprove() {
  if (submitting.value) return
  
  // 拒绝时必须填写原因
  if (approveType.value === 'REJECTED' && !approveRemark.value.trim()) {
    uni.showToast({ title: '请输入拒绝原因', icon: 'none' })
    return
  }
  
  submitting.value = true
  
  try {
    const staff = uni.getStorageSync('staff')
    const res = await consumableTempAPI.updateRequestStatus(currentApproveId.value, {
      status: approveType.value,
      approverId: staff?.id || undefined,
      remark: approveRemark.value.trim() || undefined
    })
    
    if (res.statusCode === 200) {
      uni.showToast({ 
        title: approveType.value === 'APPROVED' ? '已通过' : '已拒绝', 
        icon: 'success'
      })
      closeApproveModal()
      loadList(true)
      // 刷新消息数量和通知消息页
      refreshNow()
      uni.$emit('tempMessage:changed')
    } else {
      uni.showToast({ title: '操作失败', icon: 'none' })
    }
  } catch (err) {
    console.error('审批失败：', err)
    uni.showToast({ title: '操作失败', icon: 'none' })
  } finally {
    submitting.value = false
  }
}

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

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

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

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

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

.header {
  background: #fff;
  padding: 32rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

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

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

.switch-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 28rpx;
  color: #333;
}

.switch-label {
  font-weight: 500;
}

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

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

/* 进度条样式 */
.progress-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24rpx;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
}

.progress-step {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
  flex: 0 0 auto;
}

.step-circle {
  width: 48rpx;
  height: 48rpx;
  border-radius: 50%;
  background: #e0e0e0;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.progress-step.active .step-circle {
  background: #fff3e0;
  border: 3rpx solid #f57c00;
}

.progress-step.completed .step-circle {
  background: #4caf50;
  border: 3rpx solid #4caf50;
}

.step-icon {
  font-size: 24rpx;
  color: #fff;
  display: none;
}

.progress-step.completed .step-icon {
  display: block;
}

.step-label {
  font-size: 22rpx;
  color: #999;
  white-space: nowrap;
}

.progress-step.active .step-label {
  color: #f57c00;
  font-weight: 600;
}

.progress-step.completed .step-label {
  color: #4caf50;
  font-weight: 500;
}

.progress-line {
  flex: 1;
  height: 3rpx;
  background: #e0e0e0;
  margin: 0 8rpx;
  transition: all 0.3s ease;
}

.progress-line.completed {
  background: #4caf50;
}


.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  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;
}

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

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

.applicant-info {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: #3a5ddd;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #fff;
}

.applicant-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6rpx;
}

.name {
  font-size: 30rpx;
  font-weight: 600;
  color: #111;
}

.phone {
  font-size: 26rpx;
  color: #666;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16rpx;
  padding: 16rpx;
  background: #f5f7fb;
  border-radius: 12rpx;
}

.grid-item {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

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

.grid-value {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

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

.reason-box {
  padding: 16rpx;
  background: #fffbf0;
  border-left: 4rpx solid #ffa726;
  border-radius: 8rpx;
}

.reason-label {
  font-size: 24rpx;
  color: #666;
  margin-right: 8rpx;
}

.reason-text {
  font-size: 26rpx;
  color: #333;
}

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

.btn-reject,
.btn-approve,
.btn-deliver {
  flex: 1;
  height: 72rpx;
  line-height: 72rpx;
  border-radius: 12rpx;
  font-size: 28rpx;
  font-weight: 500;
}

.btn-reject {
  background: #ffebee;
  color: #c62828;
}

.btn-approve {
  background: #3a5ddd;
  color: #fff;
}

.btn-deliver {
  background: #4caf50;
  color: #fff;
}

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

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

/* 弹窗样式 */
.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  width: 600rpx;
  max-height: 70vh;
  background: #fff;
  border-radius: 24rpx;
  display: flex;
  flex-direction: column;
}

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

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

.modal-close {
  font-size: 40rpx;
  color: #999;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-body {
  flex: 1;
  padding: 32rpx;
  overflow-y: auto;
}

.form-item {
  margin-bottom: 0;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 12rpx;
}

.form-textarea {
  width: 100%;
  min-height: 200rpx;
  padding: 16rpx;
  background: #f5f7fb;
  border-radius: 12rpx;
  font-size: 28rpx;
  color: #333;
}

.modal-footer {
  padding: 24rpx 32rpx;
  border-top: 1rpx solid #f0f0f0;
  display: flex;
  gap: 16rpx;
}

.btn-cancel,
.btn-confirm {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 12rpx;
  font-size: 30rpx;
  font-weight: 500;
}

.btn-cancel {
  background: #f5f5f5;
  color: #666;
}

.btn-confirm {
  background: #3a5ddd;
  color: #fff;
}

.btn-confirm.btn-danger {
  background: #ef5350;
}

.btn-confirm[disabled] {
  opacity: 0.6;
}
</style>
