<template>
  <div>
    <h1>检疫申报</h1>
    
    <!-- 搜索和操作栏 -->
    <a-card style="margin-bottom: 16px;">
      <div style="display: flex; flex-wrap: wrap; gap: 16px; align-items: center;">
        <a-input v-model:value="searchKeyword" placeholder="输入申报单位或货主姓名" style="width: 250px;">
          <template #prefix>
            <span class="iconfont icon-sousuo"></span>
          </template>
        </a-input>
        
        <a-select v-model:value="typeFilter" placeholder="检疫类型" style="width: 120px;">
          <a-select-option value="">全部</a-select-option>
          <a-select-option value="animal">动物检疫</a-select-option>
          <a-select-option value="product">动物产品检疫</a-select-option>
          <a-select-option value="transport">运输检疫</a-select-option>
          <a-select-option value="slaughter">屠宰检疫</a-select-option>
          <a-select-option value="other">其他检疫</a-select-option>
        </a-select>
        
        <a-select v-model:value="statusFilter" placeholder="状态" style="width: 120px;">
          <a-select-option value="">全部</a-select-option>
          <a-select-option value="pending">待审核</a-select-option>
          <a-select-option value="approved">已通过</a-select-option>
          <a-select-option value="rejected">已驳回</a-select-option>
          <a-select-option value="cancelled">已取消</a-select-option>
        </a-select>
        
        <a-range-picker
          v-model:value="dateRange"
          style="width: 300px;"
          format="YYYY-MM-DD"
          :placeholder="['开始日期', '结束日期']"
        />
        
        <a-button type="primary" @click="handleSearch" style="margin-left: auto;">
          <span class="iconfont icon-sousuo"></span> 搜索
        </a-button>
        
        <a-button type="default" @click="handleReset">重置</a-button>
        
        <a-button type="primary" danger @click="handleAddDeclaration">
          <span class="iconfont icon-tianjia"></span> 新增申报
        </a-button>
      </div>
    </a-card>
    
    <!-- 数据列表 -->
    <a-card>
      <a-table
        :columns="columns"
        :data-source="declarationsData"
        :pagination="pagination"
        row-key="id"
        :row-selection="{ selectedRowKeys, onChange: onSelectChange }"
        :scroll="{ x: 'max-content' }"
      >
        <!-- 状态列 -->
        <template #bodyCell:status="{ record }">
          <a-tag :color="getStatusColor(record.status)">{{ getStatusText(record.status) }}</a-tag>
        </template>
        
        <!-- 操作列 -->
        <template #bodyCell:action="{ record }">
          <div style="display: flex; gap: 8px;">
            <a-button size="small" @click="handleView(record)">查看</a-button>
            <a-button size="small" type="primary" @click="handleEdit(record)" v-if="record.status === 'pending'">编辑</a-button>
            <a-button size="small" danger @click="handleDelete(record.id)" v-if="record.status === 'pending'">删除</a-button>
            <a-button size="small" @click="handleCancelDeclaration(record.id)" v-if="record.status === 'pending'">取消</a-button>
            <a-button size="small" @click="handlePrint(record.id)" v-if="record.status === 'approved'">打印</a-button>
          </div>
        </template>
      </a-table>
    </a-card>
    
    <!-- 新增/编辑申报模态框 -->
    <a-modal
      v-model:open="isAddEditModalOpen"
      :title="isEditing ? '编辑检疫申报' : '新增检疫申报'"
      :footer="null"
      width={800}
    >
      <a-form
        :model="currentDeclaration"
        layout="vertical"
      >
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
          <a-form-item label="申报单位"
                       :rules="[{ required: true, message: '请输入申报单位' }]">
            <a-input v-model:value="currentDeclaration.declarationUnit" placeholder="请输入申报单位" />
          </a-form-item>
          
          <a-form-item label="联系人"
                       :rules="[{ required: true, message: '请输入联系人' }]">
            <a-input v-model:value="currentDeclaration.contactPerson" placeholder="请输入联系人" />
          </a-form-item>
          
          <a-form-item label="联系电话"
                       :rules="[
                         { required: true, message: '请输入联系电话' },
                         { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
                       ]">
            <a-input v-model:value="currentDeclaration.phone" placeholder="请输入联系电话" />
          </a-form-item>
          
          <a-form-item label="检疫类型"
                       :rules="[{ required: true, message: '请选择检疫类型' }]">
            <a-select v-model:value="currentDeclaration.type" placeholder="请选择检疫类型">
              <a-select-option value="animal">动物检疫</a-select-option>
              <a-select-option value="product">动物产品检疫</a-select-option>
              <a-select-option value="transport">运输检疫</a-select-option>
              <a-select-option value="slaughter">屠宰检疫</a-select-option>
              <a-select-option value="other">其他检疫</a-select-option>
            </a-select>
          </a-form-item>
          
          <a-form-item label="检疫对象"
                       :rules="[{ required: true, message: '请输入检疫对象' }]">
            <a-input v-model:value="currentDeclaration.object" placeholder="请输入检疫对象（如：牛、猪肉等）" />
          </a-form-item>
          
          <a-form-item label="数量"
                       :rules="[
                         { required: true, message: '请输入数量' },
                         { type: 'number', min: 1, message: '数量至少为1' }
                       ]">
            <a-input-number v-model:value="currentDeclaration.quantity" min="1" placeholder="请输入数量" />
          </a-form-item>
          
          <a-form-item label="来源地"
                       :rules="[{ required: true, message: '请输入来源地' }]">
            <a-input v-model:value="currentDeclaration.sourcePlace" placeholder="请输入来源地" />
          </a-form-item>
          
          <a-form-item label="目的地"
                       :rules="[{ required: true, message: '请输入目的地' }]">
            <a-input v-model:value="currentDeclaration.destination" placeholder="请输入目的地" />
          </a-form-item>
          
          <a-form-item label="运输工具"
                       :rules="[{ required: true, message: '请输入运输工具' }]" v-if="currentDeclaration.type === 'transport'">
            <a-input v-model:value="currentDeclaration.transportTool" placeholder="请输入运输工具（如：货车、船舶等）" />
          </a-form-item>
          
          <a-form-item label="车牌号" v-if="currentDeclaration.type === 'transport'">
            <a-input v-model:value="currentDeclaration.vehicleNumber" placeholder="请输入车牌号" />
          </a-form-item>
        </div>
        
        <a-form-item label="申报理由"
                     :rules="[{ required: true, message: '请输入申报理由' }]">
          <a-input.TextArea v-model:value="currentDeclaration.reason" placeholder="请输入申报理由" :rows="3" />
        </a-form-item>
        
        <a-form-item label="申报附件">
          <a-upload
            name="file"
            :multiple="true"
            :fileList="fileList"
            :before-upload="beforeUpload"
            @change="handleUploadChange"
          >
            <a-button>
              <span class="iconfont icon-upload"></span> 上传附件
            </a-button>
          </a-upload>
          <p style="color: #8c8c8c; margin-top: 8px;">支持jpg、png、pdf格式，单个文件不超过10MB</p>
        </a-form-item>
        
        <a-form-item label="备注">
          <a-input.TextArea v-model:value="currentDeclaration.notes" placeholder="请输入备注信息" :rows="3" />
        </a-form-item>
      </a-form>
      
      <div style="display: flex; justify-content: flex-end; gap: 12px; margin-top: 24px;">
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" @click="handleSave">保存</a-button>
      </div>
    </a-modal>
    
    <!-- 查看申报详情模态框 -->
    <a-modal
      v-model:open="isViewModalOpen"
      title="查看检疫申报详情"
      :footer="null"
      width={800}
    >
      <div v-if="viewDeclaration">
        <div style="margin-bottom: 16px;">
          <h3 style="margin-bottom: 8px;">基本信息</h3>
          <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
            <div>
              <p style="color: #8c8c8c; margin-bottom: 4px;">申报单位</p>
              <p>{{ viewDeclaration.declarationUnit }}</p>
            </div>
            <div>
              <p style="color: #8c8c8c; margin-bottom: 4px;">联系人</p>
              <p>{{ viewDeclaration.contactPerson }}</p>
            </div>
            <div>
              <p style="color: #8c8c8c; margin-bottom: 4px;">联系电话</p>
              <p>{{ viewDeclaration.phone }}</p>
            </div>
            <div>
              <p style="color: #8c8c8c; margin-bottom: 4px;">检疫类型</p>
              <p>{{ getTypeText(viewDeclaration.type) }}</p>
            </div>
            <div>
              <p style="color: #8c8c8c; margin-bottom: 4px;">检疫对象</p>
              <p>{{ viewDeclaration.object }}</p>
            </div>
            <div>
              <p style="color: #8c8c8c; margin-bottom: 4px;">数量</p>
              <p>{{ viewDeclaration.quantity }}</p>
            </div>
            <div>
              <p style="color: #8c8c8c; margin-bottom: 4px;">来源地</p>
              <p>{{ viewDeclaration.sourcePlace }}</p>
            </div>
            <div>
              <p style="color: #8c8c8c; margin-bottom: 4px;">目的地</p>
              <p>{{ viewDeclaration.destination }}</p>
            </div>
            <div v-if="viewDeclaration.transportTool">
              <p style="color: #8c8c8c; margin-bottom: 4px;">运输工具</p>
              <p>{{ viewDeclaration.transportTool }}</p>
            </div>
            <div v-if="viewDeclaration.vehicleNumber">
              <p style="color: #8c8c8c; margin-bottom: 4px;">车牌号</p>
              <p>{{ viewDeclaration.vehicleNumber }}</p>
            </div>
            <div>
              <p style="color: #8c8c8c; margin-bottom: 4px;">申报日期</p>
              <p>{{ viewDeclaration.declarationDate }}</p>
            </div>
            <div>
              <p style="color: #8c8c8c; margin-bottom: 4px;">状态</p>
              <p><a-tag :color="getStatusColor(viewDeclaration.status)">{{ getStatusText(viewDeclaration.status) }}</a-tag></p>
            </div>
          </div>
        </div>
        
        <div style="margin-bottom: 16px;">
          <h3 style="margin-bottom: 8px;">详细信息</h3>
          <div style="margin-bottom: 12px;">
            <p style="color: #8c8c8c; margin-bottom: 4px;">申报理由</p>
            <p>{{ viewDeclaration.reason || '-' }}</p>
          </div>
          
          <div v-if="viewDeclaration.files && viewDeclaration.files.length > 0" style="margin-bottom: 12px;">
            <p style="color: #8c8c8c; margin-bottom: 4px;">申报附件</p>
            <div style="display: flex; flex-wrap: wrap; gap: 12px;">
              <a-tag v-for="file in viewDeclaration.files" :key="file.id" color="blue" style="cursor: pointer;">
                {{ file.name }}
                <template #closeIcon>
                  <span class="iconfont icon-download"></span>
                </template>
              </a-tag>
            </div>
          </div>
          
          <div v-if="viewDeclaration.reviewComments">
            <p style="color: #8c8c8c; margin-bottom: 4px;">审核意见</p>
            <p>{{ viewDeclaration.reviewComments || '-' }}</p>
          </div>
        </div>
        
        <div>
          <h3 style="margin-bottom: 8px;">备注</h3>
          <p>{{ viewDeclaration.notes || '-' }}</p>
        </div>
      </div>
      
      <div style="display: flex; justify-content: flex-end; margin-top: 24px;">
        <a-button @click="handleCloseView">关闭</a-button>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { message } from 'ant-design-vue'

// 搜索条件
const searchKeyword = ref('')
const typeFilter = ref('')
const statusFilter = ref('')
const dateRange = ref([])

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
})

// 选中行
const selectedRowKeys = ref([])
const onSelectChange = (newSelectedRowKeys) => {
  selectedRowKeys.value = newSelectedRowKeys
}

// 模态框状态
const isAddEditModalOpen = ref(false)
const isViewModalOpen = ref(false)
const isEditing = ref(false)

// 当前编辑/查看的申报
const currentDeclaration = reactive({
  id: '',
  declarationUnit: '',
  contactPerson: '',
  phone: '',
  type: 'animal',
  object: '',
  quantity: 1,
  sourcePlace: '',
  destination: '',
  transportTool: '',
  vehicleNumber: '',
  reason: '',
  files: [],
  reviewComments: '',
  notes: '',
  status: 'pending',
  declarationDate: '',
  createdAt: ''
})

const viewDeclaration = ref(null)
const fileList = ref([])

// 申报列表数据（模拟数据）
const declarationsData = ref([
  {
    id: '1',
    declarationUnit: '郑州市金水区阳光养殖场',
    contactPerson: '张三',
    phone: '13812345678',
    type: 'animal',
    object: '牛',
    quantity: 150,
    sourcePlace: '郑州市金水区',
    destination: '河南省商丘市',
    transportTool: '货车',
    vehicleNumber: '豫A12345',
    reason: '牛只销售运输',
    files: [],
    reviewComments: '符合检疫要求，同意通过',
    notes: '',
    status: 'approved',
    declarationDate: '2023-10-01',
    createdAt: '2023-10-01'
  },
  {
    id: '2',
    declarationUnit: '新郑市绿源养殖场',
    contactPerson: '李四',
    phone: '13912345678',
    type: 'product',
    object: '牛肉',
    quantity: 500,
    sourcePlace: '新郑市',
    destination: '上海市',
    transportTool: '冷藏车',
    vehicleNumber: '豫A67890',
    reason: '牛肉产品销售',
    files: [],
    reviewComments: '',
    notes: '',
    status: 'pending',
    declarationDate: '2023-10-02',
    createdAt: '2023-10-02'
  },
  {
    id: '3',
    declarationUnit: '新密市祥和养殖场',
    contactPerson: '王五',
    phone: '13712345678',
    type: 'slaughter',
    object: '牛',
    quantity: 80,
    sourcePlace: '新密市',
    destination: '新密市肉类加工厂',
    transportTool: '货车',
    vehicleNumber: '豫A23456',
    reason: '牛只屠宰加工',
    files: [],
    reviewComments: '资料不全，需补充产地检疫证明',
    notes: '',
    status: 'rejected',
    declarationDate: '2023-10-03',
    createdAt: '2023-10-03'
  },
  {
    id: '4',
    declarationUnit: '登封市幸福养殖场',
    contactPerson: '赵六',
    phone: '13612345678',
    type: 'animal',
    object: '牛',
    quantity: 120,
    sourcePlace: '登封市',
    destination: '湖北省武汉市',
    transportTool: '货车',
    vehicleNumber: '豫A34567',
    reason: '牛只销售运输',
    files: [],
    reviewComments: '',
    notes: '',
    status: 'pending',
    declarationDate: '2023-10-04',
    createdAt: '2023-10-04'
  },
  {
    id: '5',
    declarationUnit: '中牟县希望养殖场',
    contactPerson: '钱七',
    phone: '13512345678',
    type: 'product',
    object: '牛奶',
    quantity: 2000,
    sourcePlace: '中牟县',
    destination: '河南省郑州市',
    transportTool: '冷藏车',
    vehicleNumber: '豫A45678',
    reason: '牛奶产品销售',
    files: [],
    reviewComments: '符合检疫要求，同意通过',
    notes: '',
    status: 'approved',
    declarationDate: '2023-10-05',
    createdAt: '2023-10-05'
  },
  {
    id: '6',
    declarationUnit: '荥阳市快乐养殖场',
    contactPerson: '孙八',
    phone: '13412345678',
    type: 'transport',
    object: '牛',
    quantity: 90,
    sourcePlace: '荥阳市',
    destination: '山西省太原市',
    transportTool: '货车',
    vehicleNumber: '豫A56789',
    reason: '牛只跨区域调运',
    files: [],
    reviewComments: '',
    notes: '',
    status: 'pending',
    declarationDate: '2023-10-06',
    createdAt: '2023-10-06'
  },
  {
    id: '7',
    declarationUnit: '巩义市明星养殖场',
    contactPerson: '周九',
    phone: '13312345678',
    type: 'slaughter',
    object: '牛',
    quantity: 60,
    sourcePlace: '巩义市',
    destination: '巩义市屠宰场',
    transportTool: '货车',
    vehicleNumber: '豫A67890',
    reason: '牛只屠宰',
    files: [],
    reviewComments: '符合检疫要求，同意通过',
    notes: '',
    status: 'approved',
    declarationDate: '2023-10-07',
    createdAt: '2023-10-07'
  },
  {
    id: '8',
    declarationUnit: '惠济区温馨养殖场',
    contactPerson: '吴十',
    phone: '13212345678',
    type: 'other',
    object: '牛精液',
    quantity: 500,
    sourcePlace: '惠济区',
    destination: '全国各地',
    transportTool: '快递冷链',
    vehicleNumber: '',
    reason: '种牛精液销售',
    files: [],
    reviewComments: '',
    notes: '',
    status: 'pending',
    declarationDate: '2023-10-08',
    createdAt: '2023-10-08'
  },
  {
    id: '9',
    declarationUnit: '二七区红火养殖场',
    contactPerson: '郑十一',
    phone: '13112345678',
    type: 'animal',
    object: '牛',
    quantity: 100,
    sourcePlace: '二七区',
    destination: '江苏省南京市',
    transportTool: '货车',
    vehicleNumber: '豫A78901',
    reason: '牛只销售运输',
    files: [],
    reviewComments: '主动取消',
    notes: '',
    status: 'cancelled',
    declarationDate: '2023-10-09',
    createdAt: '2023-10-09'
  },
  {
    id: '10',
    declarationUnit: '中原区丰收养殖场',
    contactPerson: '王十二',
    phone: '13012345678',
    type: 'product',
    object: '牛肉制品',
    quantity: 300,
    sourcePlace: '中原区',
    destination: '广东省广州市',
    transportTool: '冷链物流',
    vehicleNumber: '豫A89012',
    reason: '牛肉制品销售',
    files: [],
    reviewComments: '',
    notes: '',
    status: 'pending',
    declarationDate: '2023-10-10',
    createdAt: '2023-10-10'
  }
])

// 表格列定义
const columns = [
  {
    title: '申报单位',
    dataIndex: 'declarationUnit',
    key: 'declarationUnit',
    ellipsis: true
  },
  {
    title: '联系人',
    dataIndex: 'contactPerson',
    key: 'contactPerson',
    width: 100
  },
  {
    title: '检疫类型',
    dataIndex: 'type',
    key: 'type',
    width: 120,
    customRender: ({ text }) => getTypeText(text)
  },
  {
    title: '检疫对象',
    dataIndex: 'object',
    key: 'object',
    width: 100
  },
  {
    title: '数量',
    dataIndex: 'quantity',
    key: 'quantity',
    width: 80
  },
  {
    title: '申报日期',
    dataIndex: 'declarationDate',
    key: 'declarationDate',
    width: 120
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 80,
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
    scopedSlots: { customRender: 'action' }
  }
]

// 状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已驳回',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

// 状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    pending: 'blue',
    approved: 'green',
    rejected: 'red',
    cancelled: 'default'
  }
  return colorMap[status] || 'default'
}

// 类型文本
const getTypeText = (type) => {
  const typeMap = {
    animal: '动物检疫',
    product: '动物产品检疫',
    transport: '运输检疫',
    slaughter: '屠宰检疫',
    other: '其他检疫'
  }
  return typeMap[type] || type
}

// 上传前校验
const beforeUpload = (file) => {
  // 检查文件类型
  const isValidType = ['image/jpeg', 'image/png', 'application/pdf'].includes(file.type)
  if (!isValidType) {
    message.error('只能上传JPG、PNG、PDF格式的文件')
    return Upload.LIST_IGNORE
  }
  
  // 检查文件大小
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    message.error('文件大小不能超过10MB')
    return Upload.LIST_IGNORE
  }
  
  return true
}

// 上传变化处理
const handleUploadChange = ({ fileList: newFileList }) => {
  fileList.value = newFileList
}

// 搜索处理
const handleSearch = () => {
  // 在实际应用中，这里应该调用API获取数据
  pagination.current = 1
  // 模拟搜索效果
  message.success('搜索成功')
}

// 重置处理
const handleReset = () => {
  searchKeyword.value = ''
  typeFilter.value = ''
  statusFilter.value = ''
  dateRange.value = []
  pagination.current = 1
}

// 新增申报
const handleAddDeclaration = () => {
  // 重置表单
  Object.assign(currentDeclaration, {
    id: '',
    declarationUnit: '',
    contactPerson: '',
    phone: '',
    type: 'animal',
    object: '',
    quantity: 1,
    sourcePlace: '',
    destination: '',
    transportTool: '',
    vehicleNumber: '',
    reason: '',
    files: [],
    reviewComments: '',
    notes: '',
    status: 'pending',
    declarationDate: '',
    createdAt: ''
  })
  fileList.value = []
  isEditing.value = false
  isAddEditModalOpen.value = true
}

// 编辑申报
const handleEdit = (record) => {
  // 复制记录到当前编辑对象
  Object.assign(currentDeclaration, { ...record })
  // 设置文件列表
  if (record.files && record.files.length > 0) {
    fileList.value = record.files.map(file => ({
      uid: file.id,
      name: file.name,
      status: 'done',
      url: file.url
    }))
  } else {
    fileList.value = []
  }
  isEditing.value = true
  isAddEditModalOpen.value = true
}

// 查看申报
const handleView = (record) => {
  viewDeclaration.value = { ...record }
  isViewModalOpen.value = true
}

// 删除申报
const handleDelete = (id) => {
  // 在实际应用中，这里应该调用API删除数据
  const index = declarationsData.value.findIndex(item => item.id === id)
  if (index !== -1) {
    declarationsData.value.splice(index, 1)
    message.success('删除成功')
  }
}

// 保存申报
const handleSave = () => {
  // 在实际应用中，这里应该调用API保存数据
  
  // 处理文件列表
  currentDeclaration.files = fileList.value.map(file => ({
    id: file.uid || Date.now().toString(),
    name: file.name,
    url: file.url
  }))
  
  if (isEditing.value) {
    // 更新现有申报
    const index = declarationsData.value.findIndex(item => item.id === currentDeclaration.id)
    if (index !== -1) {
      declarationsData.value[index] = { ...currentDeclaration }
    }
  } else {
    // 添加新申报
    const newDeclaration = {
      ...currentDeclaration,
      id: Date.now().toString(),
      declarationDate: new Date().toISOString().split('T')[0],
      createdAt: new Date().toISOString().split('T')[0]
    }
    declarationsData.value.unshift(newDeclaration)
  }
  isAddEditModalOpen.value = false
  message.success(isEditing.value ? '更新成功' : '新增成功')
}

// 取消操作
const handleCancel = () => {
  isAddEditModalOpen.value = false
}

// 关闭查看模态框
const handleCloseView = () => {
  isViewModalOpen.value = false
}

// 取消申报
const handleCancelDeclaration = (id) => {
  // 在实际应用中，这里应该调用API更新申报状态
  const index = declarationsData.value.findIndex(item => item.id === id)
  if (index !== -1) {
    declarationsData.value[index].status = 'cancelled'
    declarationsData.value[index].reviewComments = '申请人主动取消'
    message.success('申报已取消')
  }
}

// 打印申报单
const handlePrint = (id) => {
  // 在实际应用中，这里应该调用API获取打印数据
  message.success('打印功能待实现')
}
</script>

<style scoped>
  h1 {
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 20px;
    color: #333;
  }
</style>