<template>
  <div class="approval-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>审批管理</span>
          <el-select v-model="statusFilter" placeholder="状态筛选" clearable style="width: 120px">
            <el-option label="待审批" value="Pending" />
            <el-option label="已批准" value="Approved" />
            <el-option label="已拒绝" value="Rejected" />
          </el-select>
        </div>
      </template>
      
      <el-table :data="approvals" style="width: 100%" v-loading="loading">
        <el-table-column prop="type" label="类型" width="150">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">{{ getTypeName(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="requestedByUserName" label="申请人" width="120" />
        <el-table-column prop="reason" label="修改原因" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">{{ getStatusName(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="requestedAt" label="申请时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.requestedAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="reviewedByUserName" label="审批人" width="120">
          <template #default="{ row }">
            {{ row.reviewedByUserName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button type="primary" text size="small" @click="handleView(row)">查看</el-button>
            <el-button 
              v-if="row.status === 'Pending'" 
              type="success" 
              text 
              size="small" 
              @click="handleReview(row)"
            >
              审批
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        :current-page="pagination.pageNumber"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next"
        class="pagination"
        @update:current-page="handlePageChange"
        @update:page-size="handleSizeChange"
      />
    </el-card>
    
    <!-- Review Dialog -->
    <el-dialog v-model="showReviewDialog" title="审批处理" width="600px">
      <div v-if="selectedApproval" class="review-content">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="申请类型">
            <el-tag :type="getTypeTagType(selectedApproval.type)">
              {{ getTypeName(selectedApproval.type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申请人">{{ selectedApproval.requestedByUserName }}</el-descriptions-item>
          <el-descriptions-item label="修改原因">{{ selectedApproval.reason }}</el-descriptions-item>
          <el-descriptions-item label="原始数据">
            <pre class="data-preview">{{ formatJson(selectedApproval.originalData) }}</pre>
          </el-descriptions-item>
          <el-descriptions-item label="请求更改">
            <pre class="data-preview">{{ formatJson(selectedApproval.requestedChanges) }}</pre>
          </el-descriptions-item>
        </el-descriptions>
        
        <el-form :model="reviewForm" label-width="100px" class="review-form">
          <el-form-item label="审批意见">
            <el-input v-model="reviewForm.comments" type="textarea" :rows="3" placeholder="请输入审批意见（可选）" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="showReviewDialog = false">取消</el-button>
        <el-button type="danger" :loading="reviewing" @click="submitReview(false)">拒绝</el-button>
        <el-button type="success" :loading="reviewing" @click="submitReview(true)">批准</el-button>
      </template>
    </el-dialog>
  </div>
</template>

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

const router = useRouter()

const approvals = ref<ApprovalRequest[]>([])
const loading = ref(false)
const statusFilter = ref('')
const showReviewDialog = ref(false)
const reviewing = ref(false)
const selectedApproval = ref<ApprovalRequest | null>(null)

const pagination = reactive({
  pageNumber: 1,
  pageSize: 10,
  total: 0
})

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

function handlePageChange(page: number) {
  pagination.pageNumber = page
  loadApprovals()
}

function handleSizeChange(size: number) {
  pagination.pageSize = size
  pagination.pageNumber = 1
  loadApprovals()
}

async function loadApprovals() {
  loading.value = true
  try {
    const response = await approvalsApi.getAll({
      pageNumber: pagination.pageNumber,
      pageSize: pagination.pageSize,
      status: statusFilter.value || undefined
    })
    approvals.value = response.items
    pagination.total = response.totalCount
  } catch {
    ElMessage.error('加载审批列表失败')
  } finally {
    loading.value = false
  }
}

function handleView(approval: ApprovalRequest) {
  router.push(`/approvals/${approval.id}`)
}

function handleReview(approval: ApprovalRequest) {
  selectedApproval.value = approval
  reviewForm.comments = ''
  showReviewDialog.value = true
}

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

watch(statusFilter, () => {
  pagination.pageNumber = 1
  loadApprovals()
})

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

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

.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.review-content {
  margin-bottom: 20px;
}

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

.review-form {
  margin-top: 20px;
}
</style>
