<template>
  <view class="page">
    <scroll-view scroll-y class="content" v-if="!loading">
      <!-- 进度条 -->
      <view class="progress-section">
        <view class="progress-bar">
          <view class="progress-step" :class="{ active: true, completed: ['APPROVED', 'COMPLETED', 'REJECTED', 'CANCELLED'].includes(detail.status || '') }">
            <view class="step-circle">
              <text class="step-icon">{{ ['REJECTED', 'CANCELLED'].includes(detail.status || '') ? '✕' : '✓' }}</text>
            </view>
            <text class="step-label">待审批</text>
          </view>
          <view class="progress-line" :class="{ completed: ['APPROVED', 'COMPLETED'].includes(detail.status || '') }"></view>
          <view class="progress-step" :class="{ active: ['APPROVED', 'COMPLETED'].includes(detail.status || ''), completed: detail.status === 'COMPLETED' }">
            <view class="step-circle">
              <text class="step-icon">✓</text>
            </view>
            <text class="step-label">待发放</text>
          </view>
          <view class="progress-line" :class="{ completed: detail.status === 'COMPLETED' }"></view>
          <view class="progress-step" :class="{ active: detail.status === 'COMPLETED', completed: detail.status === 'COMPLETED' }">
            <view class="step-circle">
              <text class="step-icon">✓</text>
            </view>
            <text class="step-label">已完成</text>
          </view>
        </view>
      </view>

      <!-- 状态卡片 -->
      <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="applicant-card">
          <view class="avatar">
            <text class="avatar-text">{{ getAvatarText(detail.applicantName) }}</text>
          </view>
          <view class="applicant-info">
            <text class="name">{{ detail.applicantName || '未填写' }}</text>
            <text class="phone">{{ detail.applicantPhone }}</text>
            <text class="department" v-if="detail.department">{{ detail.department }}</text>
          </view>
        </view>
      </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.reason || '-' }}</text>
          </view>
          <view class="info-row">
            <text class="label">需要时间：</text>
            <text class="value">{{ detail.neededAt ? new Date(detail.neededAt).toLocaleDateString() : '-' }}</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 remark">{{ 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>
            <text class="item-name">{{ item.name }}</text>
          </view>
          <view class="item-details">
            <view class="detail-row" v-if="item.spec">
              <text class="detail-label">规格</text>
              <text class="detail-value">{{ item.spec }}</text>
            </view>
            <view class="detail-row">
              <text class="detail-label">数量</text>
              <text class="detail-value highlight">{{ item.quantity }} {{ item.unit || '' }}</text>
            </view>
            <view class="detail-row" v-if="item.estimatedUnitCost">
              <text class="detail-label">预估单价</text>
              <text class="detail-value">¥{{ item.estimatedUnitCost }}</text>
            </view>
            <view class="detail-row" 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>
          <view class="item-remark" v-if="item.remark">
            <text class="remark-label">备注：</text>
            <text class="remark-text">{{ item.remark }}</text>
          </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-reject" @tap="handleReject">拒绝</button>
      <button class="btn-approve" @tap="handleApprove">通过</button>
    </view>
    <view class="footer-actions" v-if="!loading && detail.status === 'APPROVED'">
      <button class="btn-deliver" @tap="handleDeliver">确认发放</button>
    </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, computed, onMounted } from 'vue'
import consumableTempAPI, { type ConsumableRequest } from '@/pages/api/consumable-temp'
import { refreshNow } from '@/utils/messageManager'

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

// 审批相关
const showApproveModal = ref(false)
const approveType = ref<'APPROVED' | 'REJECTED' | 'COMPLETED'>('APPROVED')
const approveRemark = ref('')
const submitting = ref(false)

// 获取状态文本
function getStatusText(status?: string) {
  const statusMap: Record<string, string> = {
    'PENDING': '待审批',
    'APPROVED': '待发放',
    'REJECTED': '已拒绝',
    'CANCELLED': '已取消',
    'COMPLETED': '已完成'
  }
  return statusMap[status || ''] || '未知'
}

// 计算总金额
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 getAvatarText(name?: string) {
  if (!name) return '?'
  return name.substring(0, 1)
}

// 通过申请
function handleApprove() {
  approveType.value = 'APPROVED'
  approveRemark.value = ''
  showApproveModal.value = true
}

// 拒绝申请
function handleReject() {
  approveType.value = 'REJECTED'
  approveRemark.value = ''
  showApproveModal.value = true
}

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

// 关闭审批弹窗
function closeApproveModal() {
  showApproveModal.value = false
  approveRemark.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(requestId.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',
        success: () => {
          setTimeout(() => {
            // 通知列表页和消息页需要刷新
            uni.$emit('tempApprove:changed')
            uni.$emit('tempMessage:changed')
            uni.navigateBack()
          }, 500)
        }
      })
      closeApproveModal()
      // 刷新消息数量
      refreshNow()
    } else {
      uni.showToast({ title: '操作失败', icon: 'none' })
    }
  } catch (err) {
    console.error('审批失败：', err)
    uni.showToast({ title: '操作失败', icon: 'none' })
  } finally {
    submitting.value = false
  }
}

// 页面加载
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;
}

/* 进度条区域 */
.progress-section {
  margin-bottom: 24rpx;
}

.progress-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx;
  background: #fff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);
}

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

.step-circle {
  width: 56rpx;
  height: 56rpx;
  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: 28rpx;
  color: #fff;
  display: none;
}

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

.step-label {
  font-size: 24rpx;
  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 12rpx;
  transition: all 0.3s ease;
}

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

.status-card {
  background: #fff;
  border-radius: 20rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);
}

.status-badge {
  padding: 8rpx 24rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  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;
}

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

.section {
  margin-bottom: 32rpx;
}

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

.applicant-card {
  background: #fff;
  border-radius: 20rpx;
  padding: 32rpx;
  display: flex;
  align-items: center;
  gap: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);
}

.avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  border: 4rpx solid #f0f0f0;
}

.avatar-text {
  font-size: 36rpx;
  font-weight: 500;
  color: #fff;
}

.applicant-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

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

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

.department {
  font-size: 26rpx;
  color: #999;
}

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

.info-row .value.remark {
  color: #f57c00;
  font-weight: 500;
}

.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 {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 16rpx;
  padding-bottom: 12rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.item-number {
  font-size: 24rpx;
  font-weight: 600;
  color: #4b7aff;
  padding: 4rpx 12rpx;
  background: #e3f2fd;
  border-radius: 6rpx;
}

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

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

.detail-row {
  display: flex;
  flex-direction: column;
  gap: 6rpx;
}

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

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

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

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

.item-remark {
  margin-top: 16rpx;
  padding-top: 16rpx;
  border-top: 1rpx solid #f5f5f5;
  font-size: 26rpx;
}

.remark-label {
  color: #999;
}

.remark-text {
  color: #666;
}

.total-card {
  background: #fff;
  border-radius: 20rpx;
  padding: 32rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);
  border-left: 6rpx solid #ff9800;
}

.total-label {
  font-size: 32rpx;
  font-weight: 500;
  color: #666;
}

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

.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-reject,
.btn-approve,
.btn-deliver {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  border-radius: 16rpx;
  font-size: 32rpx;
  font-weight: 600;
}

.btn-reject {
  background: #fff;
  color: #f44336;
  border: 2rpx solid #f44336;
}

.btn-approve {
  background: #007aff;
  color: #fff;
}

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

/* 弹窗样式 */
.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: #007aff;
  color: #fff;
}

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

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