<template>
  <div class="page-container">
    <h1 class="page-title">审批流程管理</h1>
    
    <!-- 操作按钮区域 -->
    <!-- <div class="action-buttons"> -->
      <!-- <a-button type="primary" @click="showCreateModal">新建审批流程</a-button>
      <a-button style="margin-left: 8px;" @click="exportApprovalList">导出列表</a-button>
    </div> -->

    <!-- 标签页和搜索 -->
    <div class="filter-section">
      <a-tabs v-model:activeKey="activeTab" @change="handleTabChange">
        <a-tab-pane key="pending" tab="待审批"></a-tab-pane>
        <a-tab-pane key="approved" tab="已审批"></a-tab-pane>
      </a-tabs>
      <a-input-search
        placeholder="请输入认证申请人"
        style="width: 200px; margin-bottom: 16px;"
        @search="onSearch"
      />
    </div>

    <!-- 审批卡片列表 -->
    <div class="card-list" v-loading="loading">
      <a-row :gutter="[16, 16]">
        <a-col :span="8" v-for="item in approvalList" :key="item.id">
          <a-card class="approval-card" @click="() => viewApprovalDetail(item.id)">
            <template #title>
              <div class="card-title">
                <span>当前状态:</span>
                <a-tag :color="getStatusColor(item.status)">{{ getStatusText(item.status) }}</a-tag>
              </div>
            </template>
            <p><strong>审批标题:</strong> {{ item.title }}</p>
            <p><strong>申请人:</strong> {{ item.applicant }}</p>
            <p><strong>审批类型:</strong> {{ getTypeText(item.type) }}</p>
            <p><strong>申请时间:</strong> {{ item.create_time }}</p>
            <p><strong>联系电话:</strong> {{ item.phone || '未填写' }}</p>
            <p><strong>养殖场名称:</strong> {{ item.farmName }}</p>
            <p v-if="item.quantity"><strong>认证数量:</strong> {{ item.quantity }}</p>
          </a-card>
        </a-col>
      </a-row>
      
      <!-- 空状态 -->
      <div v-if="!loading && approvalList.length === 0" class="empty-state">
        <a-empty description="暂无审批流程数据" />
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <a-pagination
        v-model:current="currentPage"
        :total="totalItems"
        :page-size="pageSize"
        @change="handlePageChange"
        show-quick-jumper
      />
    </div>

    <!-- 新建审批流程弹窗 -->
    <a-modal
      class="custom-modal"
      title="新建审批流程"
      v-model:open="createModalVisible"
      :footer="null"
      @cancel="closeCreateModal"
    >
      <a-form
        class="custom-form"
        ref="createFormRef"
        :model="createFormData"
        layout="vertical"
        :rules="createFormRules"
      >
        <a-form-item name="title" label="审批标题">
          <a-input v-model:value="createFormData.title" placeholder="请输入审批标题" />
        </a-form-item>
        <a-form-item name="type" label="审批类型">
          <a-select v-model:value="createFormData.type" placeholder="请选择审批类型">
            <a-select-option value="enterprise">企业资质</a-select-option>
            <a-select-option value="license">许可证</a-select-option>
            <a-select-option value="project">项目审批</a-select-option>
            <a-select-option value="other">其他</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item name="applicant" label="申请人">
          <a-input v-model:value="createFormData.applicant" placeholder="请输入申请人姓名" />
        </a-form-item>
        <a-form-item name="description" label="审批说明">
          <a-textarea v-model:value="createFormData.description" placeholder="请输入审批说明" rows={4} />
        </a-form-item>
        <a-form-item name="files" label="附件上传">
          <a-upload
            name="file"
            :multiple="true"
            :file-list="createFormData.files"
            :before-upload="beforeUpload"
            @change="handleFileChange"
          >
            <a-button>
              <upload-outlined /> 点击上传
            </a-button>
          </a-upload>
        </a-form-item>
        <div style="text-align: right;">
          <a-button @click="closeCreateModal">取消</a-button>
          <a-button type="primary" @click="submitCreateForm">提交</a-button>
        </div>
      </a-form>
    </a-modal>

    <!-- 审批弹窗 -->
    <a-modal
      class="custom-modal"
      title="审批操作"
      v-model:open="processModalVisible"
      :footer="null"
      @cancel="closeProcessModal"
    >
      <div v-if="currentApproval" class="detail-info">
        <h3>{{ currentApproval.title }}</h3>
        <p>申请人: {{ currentApproval.applicant }}</p>
        <p>申请时间: {{ currentApproval.create_time }}</p>
        <p>审批类型: {{ getTypeText(currentApproval.type) }}</p>
        <p>审批说明: {{ currentApproval.description }}</p>
        
        <a-form-item label="审批意见">
          <a-textarea v-model:value="approvalComment" placeholder="请输入审批意见" rows={4} />
        </a-form-item>
        
        <div style="text-align: right;">
          <a-button @click="closeProcessModal">取消</a-button>
          <a-button danger style="margin-left: 8px;" @click="rejectApproval">拒绝</a-button>
          <a-button type="primary" style="margin-left: 8px;" @click="approveApproval">通过</a-button>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import approvalProcessApi from '@/utils/approvalProcessApi'
import { UploadOutlined } from '@ant-design/icons-vue'

const allData = ref([])
const approvalList = ref([])
const activeTab = ref('pending')
const currentPage = ref(1)
const pageSize = ref(9)
const totalItems = ref(0)
const searchInput = ref('')
const loading = ref(false)

const createModalVisible = ref(false)
const processModalVisible = ref(false)
const currentApproval = ref(null)
const approvalComment = ref('')
const createFormRef = ref(null)
const createFormData = ref({
  title: '',
  type: '',
  applicant: '',
  description: '',
  files: []
})
const createFormRules = ref({
  title: [{ required: true, message: '请输入审批标题', trigger: 'blur' }],
  type: [{ required: true, message: '请选择审批类型', trigger: 'change' }],
  applicant: [{ required: true, message: '请输入申请人姓名', trigger: 'blur' }],
  description: [{ required: true, message: '请输入审批说明', trigger: 'blur' }]
})

const approvalColumns = []

// 根据状态获取标签颜色
const getStatusColor = (status) => {
  const colorMap = {
    pending: 'orange',
    approved: 'green',
    rejected: 'red',
    processing: 'blue'
  }
  return colorMap[status] || 'default'
}

// 根据状态获取显示文本
const getStatusText = (status) => {
  const textMap = {
    pending: '待审批',
    approved: '已通过',
    rejected: '已拒绝',
    processing: '处理中'
  }
  return textMap[status] || status
}

// 根据类型获取显示文本
const getTypeText = (type) => {
  const textMap = {
    enterprise: '企业资质',
    license: '许可证',
    project: '项目审批',
    other: '其他'
  }
  return textMap[type] || type
}

// 获取审批流程列表
const fetchApprovalList = async () => {
  try {
    loading.value = true
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      status: activeTab.value === 'pending' ? 'pending' : activeTab.value === 'approved' ? 'approved' : undefined,
      applicant: searchInput.value
    }
    
    const response = await approvalProcessApi.getApprovalProcesses(params)
    if (response.code === 200) {
      approvalList.value = response.data.list.map(item => ({
        ...item,
        create_time: item.createdAt,
        farmName: item.farmName || '未填写'
      }))
      totalItems.value = response.data.total
    } else {
      message.error(response.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取审批流程列表失败:', error)
    message.error('获取审批流程列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 搜索审批
const onSearch = (value) => {
  searchInput.value = value
  currentPage.value = 1
  fetchApprovalList()
}

// 查看审批详情
const viewApprovalDetail = async (id) => {
  try {
    const response = await approvalProcessApi.getApprovalProcessById(id)
    if (response.code === 200) {
      currentApproval.value = {
        ...response.data,
        create_time: response.data.createdAt,
        farmName: response.data.farmName || '未填写'
      }
      processModalVisible.value = true
    } else {
      message.error(response.message || '获取详情失败')
    }
  } catch (error) {
    console.error('获取审批详情失败:', error)
    message.error('获取详情失败')
  }
}

// 编辑审批
const editApproval = (id) => {
  message.info(`编辑审批ID: ${id}`)
  // 这里应该打开编辑弹窗并加载数据
}

// 删除审批
const deleteApproval = (id) => {
  message.info(`删除审批ID: ${id}`)
  // 这里应该弹出确认框并调用删除API
}

// 处理审批
const processApproval = (id) => {
  // 找到当前审批项
  const approval = approvalList.value.find(item => item.id === id)
  if (approval) {
    currentApproval.value = { ...approval }
    approvalComment.value = ''
    processModalVisible.value = true
  }
}

// 通过审批
const approveApproval = async () => {
  if (!currentApproval.value) return
  
  try {
    const response = await approvalProcessApi.processApproval(currentApproval.value.id, {
      action: 'approve',
      approvalComment: approvalComment.value,
      approver: '当前用户' // 这里应该从用户信息中获取
    })
    
    if (response.code === 200) {
      message.success(`已通过审批: ${currentApproval.value.title}`)
      closeProcessModal()
      fetchApprovalList() // 重新加载数据
    } else {
      message.error(response.message || '审批失败')
    }
  } catch (error) {
    console.error('审批操作失败:', error)
    message.error('审批失败')
  }
}

// 拒绝审批
const rejectApproval = async () => {
  if (!currentApproval.value) return
  
  if (!approvalComment.value.trim()) {
    message.warning('请输入拒绝理由')
    return
  }
  
  try {
    const response = await approvalProcessApi.processApproval(currentApproval.value.id, {
      action: 'reject',
      approvalComment: approvalComment.value,
      approver: '当前用户' // 这里应该从用户信息中获取
    })
    
    if (response.code === 200) {
      message.success(`已拒绝审批: ${currentApproval.value.title}`)
      closeProcessModal()
      fetchApprovalList() // 重新加载数据
    } else {
      message.error(response.message || '审批失败')
    }
  } catch (error) {
    console.error('审批操作失败:', error)
    message.error('审批失败')
  }
}

// 显示新建弹窗
const showCreateModal = () => {
  createFormData.value = {
    title: '',
    type: '',
    applicant: '',
    description: '',
    files: []
  }
  if (createFormRef.value) {
    createFormRef.value.resetFields()
  }
  createModalVisible.value = true
}

// 关闭新建弹窗
const closeCreateModal = () => {
  createModalVisible.value = false
}

// 关闭审批弹窗
const closeProcessModal = () => {
  processModalVisible.value = false
  currentApproval.value = null
  approvalComment.value = ''
}

// 提交新建表单
const submitCreateForm = async () => {
  if (!createFormRef.value) return
  
  try {
    await createFormRef.value.validate()
    
    const response = await approvalProcessApi.createApprovalProcess({
      title: createFormData.value.title,
      type: createFormData.value.type,
      applicant: createFormData.value.applicant,
      description: createFormData.value.description,
      files: createFormData.value.files
    })
    
    if (response.code === 201) {
      message.success('新建审批流程成功')
      closeCreateModal()
      fetchApprovalList() // 重新加载数据
    } else {
      message.error(response.message || '创建失败')
    }
  } catch (error) {
    console.error('表单验证失败:', error)
    message.error('创建失败')
  }
}

// 上传前处理
const beforeUpload = (file) => {
  // 这里可以添加文件类型和大小的校验
  return false; // 阻止自动上传
}

// 文件变化处理
const handleFileChange = ({ fileList }) => {
  createFormData.value.files = fileList
}

// 导出列表
const exportApprovalList = () => {
  message.info('导出审批流程列表')
  // 这里应该调用导出API
}

// 标签页切换
const handleTabChange = (key) => {
  activeTab.value = key
  currentPage.value = 1
  fetchApprovalList()
}

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  fetchApprovalList()
}

// 组件挂载
onMounted(() => {
  fetchApprovalList()
})
</script>

<style scoped>
/* 页面容器样式 */
.page-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 页面标题样式 */
.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #262626;
  margin-bottom: 24px;
}

/* 操作按钮区域样式 */
.action-buttons {
  margin-bottom: 16px;
  background-color: #fff;
  padding: 16px;
  border-radius: 6px;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03);
}

/* 过滤器和搜索区域样式 */
.filter-section {
  margin-bottom: 16px;
  background-color: #fff;
  padding: 16px;
  border-radius: 6px;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03);
}

/* 表格卡片样式 */
.table-card {
  background-color: #fff;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03);
}

/* 表格样式优化 */
.custom-table {
  border-radius: 6px;
  overflow: hidden;
}

.custom-table .ant-table-thead > tr > th {
  background-color: #fafafa;
  font-weight: 600;
  color: #262626;
  border-bottom: 1px solid #f0f0f0;
}

.custom-table .ant-table-tbody > tr:hover > td {
  background-color: #f5f5f5;
}

/* 表格单元格样式 */
.table-cell {
  padding: 12px 16px;
}

/* 状态标签样式增强 */
.status-tag {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

/* 操作按钮组样式 */
.action-group {
  display: flex;
  gap: 8px;
}

/* 弹窗样式优化 */
.custom-modal .ant-modal-header {
  background-color: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

.custom-modal .ant-modal-title {
  font-size: 18px;
  font-weight: 600;
  color: #262626;
}

.custom-modal .ant-modal-footer {
  border-top: 1px solid #f0f0f0;
}

/* 表单样式优化 */
.custom-form .ant-form-item {
  margin-bottom: 16px;
}

.custom-form .ant-form-item-label {
  font-weight: 500;
  color: #595959;
}

/* 详情信息区域样式 */
.detail-info {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #fafafa;
  border-radius: 6px;
}

.detail-info p {
  margin-bottom: 8px;
  line-height: 1.5;
}

.detail-info h3 {
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

/* 卡片列表样式 */
.card-list {
  margin-bottom: 24px;
}

.approval-card {
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.approval-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.card-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title span {
  font-weight: 500;
  color: #666;
}

.approval-card p {
  margin-bottom: 8px;
  line-height: 1.5;
  color: #333;
}

.approval-card strong {
  color: #262626;
  font-weight: 500;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 60px 0;
}

/* 分页容器样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}
</style>