<template>
  <view class="page">
    <scroll-view scroll-y class="content" v-if="!loading">
      <!-- 状态卡片 -->
      <view class="status-card">
        <view class="status-badge" :class="`status-${detail.status?.toLowerCase()}`">
          {{ getStatusText(detail.status) }}
        </view>
        <text class="status-time">{{ formatTime(detail.createdAt) }}</text>
      </view>

      <!-- 基本信息 -->
      <view class="section">
        <view class="section-title">基本信息</view>
        <view class="info-card">
          <view class="info-row">
            <text class="label">申请人：</text>
            <text class="value">{{ detail.applicantName || '-' }}</text>
          </view>
          <view class="info-row">
            <text class="label">联系电话：</text>
            <text class="value">{{ detail.applicantPhone }}</text>
          </view>
          <view class="info-row">
            <text class="label">部门：</text>
            <text class="value">{{ detail.department || '-' }}</text>
          </view>
          <view class="info-row">
            <text class="label">申请原因：</text>
            <text class="value">{{ detail.reason || '-' }}</text>
          </view>
          <view class="info-row">
            <text class="label">需要时间：</text>
            <text class="value">{{ detail.neededAt || '-' }}</text>
          </view>
          <view class="info-row" v-if="detail.approverId">
            <text class="label">审批人ID：</text>
            <text class="value">{{ detail.approverId }}</text>
          </view>
          <view class="info-row" v-if="detail.approvedAt">
            <text class="label">审批时间：</text>
            <text class="value">{{ formatTime(detail.approvedAt) }}</text>
          </view>
          <view class="info-row" v-if="detail.remark">
            <text class="label">备注：</text>
            <text class="value">{{ detail.remark }}</text>
          </view>
        </view>
      </view>

      <!-- 物料明细 -->
      <view class="section">
        <view class="section-title">物料明细（{{ detail.items?.length || 0 }}项）</view>
        <view v-for="(item, index) in detail.items" :key="item.id" class="item-card">
          <view class="item-header">
            <text class="item-number">#{{ index + 1 }}</text>
          </view>
          <view class="item-body">
            <view class="item-name">{{ item.name }}</view>
            <view class="item-details">
              <view class="detail-item" v-if="item.spec">
                <text class="detail-label">规格：</text>
                <text class="detail-value">{{ item.spec }}</text>
              </view>
              <view class="detail-item">
                <text class="detail-label">数量：</text>
                <text class="detail-value highlight">{{ item.quantity }} {{ item.unit || '' }}</text>
              </view>
              <view class="detail-item" v-if="item.estimatedUnitCost">
                <text class="detail-label">预估单价：</text>
                <text class="detail-value">¥{{ item.estimatedUnitCost }}</text>
              </view>
              <view class="detail-item" v-if="item.estimatedUnitCost && item.quantity">
                <text class="detail-label">小计：</text>
                <text class="detail-value total">¥{{ (item.estimatedUnitCost * item.quantity).toFixed(2) }}</text>
              </view>
              <view class="detail-item full-width" v-if="item.remark">
                <text class="detail-label">备注：</text>
                <text class="detail-value">{{ item.remark }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 合计 -->
      <view class="section" v-if="totalCost > 0">
        <view class="total-card">
          <text class="total-label">预估总金额</text>
          <text class="total-value">¥{{ totalCost.toFixed(2) }}</text>
        </view>
      </view>
    </scroll-view>

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

    <!-- 底部操作按钮 -->
    <view class="footer-actions" v-if="!loading && detail.status === 'PENDING'">
      <button class="btn-danger" @tap="handleCancel">取消申请</button>
      <button class="btn-primary" @tap="handleEdit">编辑</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import consumableTempAPI, { type ConsumableRequest } from '@/pages/api/consumable-temp'

const detail = ref<ConsumableRequest>({
  applicantPhone: '',
  items: []
})
const loading = ref(true)
const requestId = ref('')

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

// 计算总金额
const totalCost = computed(() => {
  return detail.value.items?.reduce((sum, item) => {
    const cost = (item.estimatedUnitCost || 0) * (item.quantity || 0)
    return sum + cost
  }, 0) || 0
})

// 加载详情
async function loadDetail() {
  if (!requestId.value) return
  
  loading.value = true
  
  try {
    const res = await consumableTempAPI.getRequestDetail(requestId.value)
    
    if (res.statusCode === 200 && (res.data as any)?.data) {
      detail.value = (res.data as any).data
    } else {
      uni.showToast({ title: '加载失败', icon: 'none' })
    }
  } catch (err) {
    console.error('加载详情失败：', err)
    uni.showToast({ title: '加载失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

// 格式化时间
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 handleCancel() {
  uni.showModal({
    title: '确认取消',
    content: '确定要取消这个申请吗？取消后不可恢复。',
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await consumableTempAPI.updateRequestStatus(requestId.value, {
            status: 'CANCELLED'
          })
          
          if (result.statusCode === 200) {
            uni.showToast({ 
              title: '已取消', 
              icon: 'success',
              success: () => {
                setTimeout(() => {
                  // 通知列表页需要刷新
                  uni.$emit('tempRequest:changed')
                  uni.navigateBack()
                }, 1500)
              }
            })
          } else {
            uni.showToast({ title: '操作失败', icon: 'none' })
          }
        } catch (err) {
          console.error('取消失败：', err)
          uni.showToast({ title: '操作失败', icon: 'none' })
        }
      }
    }
  })
}

// 编辑申请
function handleEdit() {
  uni.navigateTo({ 
    url: `/pages/consumables/temp-request-edit?id=${requestId.value}` 
  })
}

// 页面加载
onMounted(() => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1] as any
  const options = currentPage.options || {}
  
  if (options.id) {
    requestId.value = options.id
    loadDetail()
  }
})
</script>

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

.content {
  flex: 1;
  padding: 24rpx 32rpx 140rpx;
  box-sizing: border-box;
}

.loading-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #999;
}

.status-card {
  background: #3a5ddd;
  border-radius: 20rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16rpx;
}

.status-badge {
  padding: 12rpx 32rpx;
  border-radius: 24rpx;
  font-size: 32rpx;
  font-weight: 600;
  background: rgba(255, 255, 255, 0.9);
}

.status-pending {
  color: #f57c00;
}

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

.status-rejected {
  color: #c62828;
}

.status-cancelled {
  color: #757575;
}

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

.status-time {
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.9);
}

.section {
  margin-bottom: 32rpx;
}

.section-title {
  padding: 0 12rpx 16rpx;
  font-size: 32rpx;
  font-weight: 600;
  color: #111;
}

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

.info-row {
  display: flex;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.info-row:last-child {
  border-bottom: none;
}

.info-row .label {
  color: #666;
  font-size: 28rpx;
  width: 160rpx;
  flex-shrink: 0;
}

.info-row .value {
  color: #333;
  font-size: 28rpx;
  flex: 1;
}

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

.item-header {
  margin-bottom: 16rpx;
  padding-bottom: 12rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.item-number {
  font-size: 26rpx;
  font-weight: 600;
  color: #4b7aff;
}

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

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

.item-details {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12rpx;
}

.detail-item {
  display: flex;
  font-size: 26rpx;
}

.detail-item.full-width {
  grid-column: 1 / -1;
}

.detail-label {
  color: #666;
  margin-right: 8rpx;
}

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

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

.detail-value.total {
  color: #ff6b6b;
  font-weight: 600;
}

.total-card {
  background: #f9a825;
  border-radius: 20rpx;
  padding: 32rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 8rpx 24rpx rgba(249, 168, 37, 0.2);
}

.total-label {
  font-size: 32rpx;
  font-weight: 600;
  color: #fff;
}

.total-value {
  font-size: 40rpx;
  font-weight: 700;
  color: #fff;
}

.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);
  display: flex;
  gap: 16rpx;
}

.btn-danger,
.btn-primary {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  border-radius: 16rpx;
  font-size: 32rpx;
  font-weight: 600;
}

.btn-danger {
  background: #ef5350;
  color: #fff;
}

.btn-primary {
  background: #3a5ddd;
  color: #fff;
}
</style>
