<template>
  <div class="approval-detail">
    <el-card v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>审批详情</span>
          <el-button @click="$router.back()">返回</el-button>
        </div>
      </template>
      
      <div v-if="approval" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="申请类型">
            <el-tag :type="getTypeTagType(approval.type)">{{ getTypeName(approval.type) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(approval.status)">{{ getStatusName(approval.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申请人">{{ approval.requestedByUserName }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ formatDate(approval.requestedAt) }}</el-descriptions-item>
          <el-descriptions-item label="审批人">{{ approval.reviewedByUserName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="审批时间">{{ approval.reviewedAt ? formatDate(approval.reviewedAt) : '-' }}</el-descriptions-item>
          <el-descriptions-item label="修改原因" :span="2">{{ approval.reason }}</el-descriptions-item>
          <el-descriptions-item label="审批意见" :span="2">{{ approval.reviewComments || '-' }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider content-position="left">数据对比</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card shadow="never">
              <template #header>
                <span>原始数据</span>
              </template>
              <pre class="data-content">{{ formatJson(approval.originalData) }}</pre>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card shadow="never">
              <template #header>
                <span>请求更改</span>
              </template>
              <pre class="data-content">{{ formatJson(approval.requestedChanges) }}</pre>
            </el-card>
          </el-col>
        </el-row>
        
        <div v-if="approval.status === 'Pending'" class="action-section">
          <el-divider />
          <el-form :model="reviewForm" label-width="100px">
            <el-form-item label="审批意见">
              <el-input v-model="reviewForm.comments" type="textarea" rows="3" placeholder="请输入审批意见（可选）" />
            </el-form-item>
            <el-form-item>
              <el-button type="danger" :loading="reviewing" @click="submitReview(false)">拒绝</el-button>
              <el-button type="success" :loading="reviewing" @click="submitReview(true)">批准</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { approvalsApi } from '@/api'
import type { ApprovalRequest } from '@/types'
import { ApprovalStatus, ApprovalRequestType } from '@/types'

const route = useRoute()
const router = useRouter()

const approval = ref<ApprovalRequest | null>(null)
const loading = ref(false)
const reviewing = ref(false)

const reviewForm = reactive({
  comments: ''
})

function getTypeName(type: ApprovalRequestType): string {
  switch (type) {
    case ApprovalRequestType.AllocationModification: return '配额修改'
    case ApprovalRequestType.ReportModification: return '上报修改'
    case ApprovalRequestType.PersonnelModification: return '人员修改'
    default: return ''
  }
}

function getTypeTagType(type: ApprovalRequestType): string {
  switch (type) {
    case ApprovalRequestType.AllocationModification: return 'primary'
    case ApprovalRequestType.ReportModification: return 'success'
    case ApprovalRequestType.PersonnelModification: return 'warning'
    default: return 'info'
  }
}

function getStatusName(status: ApprovalStatus): string {
  switch (status) {
    case ApprovalStatus.Pending: return '待审批'
    case ApprovalStatus.Approved: return '已批准'
    case ApprovalStatus.Rejected: return '已拒绝'
    default: return ''
  }
}

function getStatusTagType(status: ApprovalStatus): string {
  switch (status) {
    case ApprovalStatus.Pending: return 'warning'
    case ApprovalStatus.Approved: return 'success'
    case ApprovalStatus.Rejected: return 'danger'
    default: return 'info'
  }
}

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleString('zh-CN')
}

function formatJson(jsonStr: string): string {
  try {
    return JSON.stringify(JSON.parse(jsonStr), null, 2)
  } catch {
    return jsonStr
  }
}

async function loadApproval() {
  loading.value = true
  try {
    approval.value = await approvalsApi.getById(Number(route.params.id))
  } catch {
    ElMessage.error('加载审批详情失败')
  } finally {
    loading.value = false
  }
}

async function submitReview(approved: boolean) {
  if (!approval.value) return
  
  reviewing.value = true
  try {
    await approvalsApi.review(approval.value.id, {
      approved,
      comments: reviewForm.comments
    })
    ElMessage.success(approved ? '已批准' : '已拒绝')
    router.push('/approvals')
  } catch {
    ElMessage.error('审批操作失败')
  } finally {
    reviewing.value = false
  }
}

onMounted(() => {
  loadApproval()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.data-content {
  background-color: #f5f7fa;
  padding: 12px;
  border-radius: 4px;
  font-size: 12px;
  max-height: 300px;
  overflow-y: auto;
  margin: 0;
}

.action-section {
  margin-top: 20px;
}
</style>
