<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="vaccination">疫苗接种</a-select-option>
          <a-select-option value="disinfection">消毒</a-select-option>
          <a-select-option value="health_check">健康检查</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="completed">已完成</a-select-option>
          <a-select-option value="pending">待完成</a-select-option>
          <a-select-option value="failed">未通过</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="handleAddRecord">
          <span class="iconfont icon-tianjia"></span> 新增记录
        </a-button>
      </div>
    </a-card>
    
    <!-- 数据列表 -->
    <a-card>
      <a-table
        :columns="columns"
        :data-source="recordsData"
        :pagination="pagination"
        :loading="loading"
        row-key="id"
        :row-selection="{ selectedRowKeys, onChange: onSelectChange }"
        :scroll="{ x: 'max-content' }"
        @change="handleTableChange"
      >
        <!-- 状态列 -->
        <template #status="{ record }">
          <a-tag :color="getStatusColor(record.status)">{{ getStatusText(record.status) }}</a-tag>
        </template>
        
        <!-- 操作列 -->
        <template #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)">编辑</a-button>
            <a-button size="small" danger @click="handleDelete(record.id)">删除</a-button>
          </div>
        </template>
      </a-table>
    </a-card>
    
    <!-- 新增/编辑记录模态框 -->
    <a-modal
      v-model:open="isAddEditModalOpen"
      :title="isEditing ? '编辑防疫记录' : '新增防疫记录'"
      :footer="null"
      width={700}
    >
      <a-form
        :model="currentRecord"
        layout="vertical"
      >
        <a-form-item label="养殖场名称"
                     :rules="[{ required: true, message: '请输入养殖场名称' }]">
          <a-input v-model:value="currentRecord.farmName" placeholder="请输入养殖场名称" />
        </a-form-item>
        
        <a-form-item label="防疫类型"
                     :rules="[{ required: true, message: '请选择防疫类型' }]">
          <a-select v-model:value="currentRecord.type" placeholder="请选择防疫类型">
            <a-select-option value="vaccination">疫苗接种</a-select-option>
            <a-select-option value="disinfection">消毒</a-select-option>
            <a-select-option value="health_check">健康检查</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="currentRecord.epidemicStaff" placeholder="请输入防疫员姓名" />
        </a-form-item>
        
        <a-form-item label="联系电话"
                     :rules="[
                       { required: true, message: '请输入联系电话' },
                       { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
                     ]">
          <a-input v-model:value="currentRecord.phone" placeholder="请输入联系电话" />
        </a-form-item>
        
        <a-form-item label="防疫日期"
                     :rules="[{ required: true, message: '请选择防疫日期' }]">
          <a-date-picker
            v-model:value="currentRecord.epidemicDate"
            style="width: 100%;"
            format="YYYY-MM-DD"
          />
        </a-form-item>
        
        <a-form-item label="防疫数量" v-if="currentRecord.type === 'vaccination'"
                     :rules="[{ required: true, message: '请输入防疫数量', type: 'number' }]">
          <a-input-number v-model:value="currentRecord.count" min="0" placeholder="请输入防疫数量" />
        </a-form-item>
        
        <a-form-item label="使用疫苗" v-if="currentRecord.type === 'vaccination'"
                     :rules="[{ required: true, message: '请输入使用疫苗' }]">
          <a-input v-model:value="currentRecord.vaccineName" placeholder="请输入使用疫苗" />
        </a-form-item>
        
        <a-form-item label="防疫范围" v-if="currentRecord.type === 'disinfection'"
                     :rules="[{ required: true, message: '请输入防疫范围' }]">
          <a-input.TextArea v-model:value="currentRecord.area" placeholder="请输入防疫范围" rows={2} />
        </a-form-item>
        
        <a-form-item label="防疫药品" v-if="currentRecord.type === 'disinfection'"
                     :rules="[{ required: true, message: '请输入防疫药品' }]">
          <a-input v-model:value="currentRecord.disinfectant" placeholder="请输入防疫药品" />
        </a-form-item>
        
        <a-form-item label="检查结果" v-if="currentRecord.type === 'health_check'"
                     :rules="[{ required: true, message: '请输入检查结果' }]">
          <a-select v-model:value="currentRecord.healthResult" placeholder="请选择检查结果">
            <a-select-option value="normal">正常</a-select-option>
            <a-select-option value="abnormal">异常</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="防疫描述" v-if="currentRecord.type === 'other'"
                     :rules="[{ required: true, message: '请输入防疫描述' }]">
          <a-input.TextArea v-model:value="currentRecord.description" placeholder="请输入防疫描述" rows={3} />
        </a-form-item>
        
        <a-form-item label="备注">
          <a-input.TextArea v-model:value="currentRecord.notes" placeholder="请输入备注信息" rows={4} />
        </a-form-item>
        
        <a-form-item label="状态">
          <a-select v-model:value="currentRecord.status" placeholder="请选择状态">
            <a-select-option value="completed">已完成</a-select-option>
            <a-select-option value="pending">待完成</a-select-option>
            <a-select-option value="failed">未通过</a-select-option>
          </a-select>
        </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={700}
    >
      <div v-if="viewRecord">
        <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>{{ viewRecord.farmName }}</p>
            </div>
            <div>
              <p style="color: #8c8c8c; margin-bottom: 4px;">防疫类型</p>
              <p>{{ getTypeText(viewRecord.type) }}</p>
            </div>
            <div>
              <p style="color: #8c8c8c; margin-bottom: 4px;">防疫员</p>
              <p>{{ viewRecord.epidemicStaff }}</p>
            </div>
            <div>
              <p style="color: #8c8c8c; margin-bottom: 4px;">联系电话</p>
              <p>{{ viewRecord.phone }}</p>
            </div>
            <div>
              <p style="color: #8c8c8c; margin-bottom: 4px;">防疫日期</p>
              <p>{{ formatDate(viewRecord.epidemicDate) }}</p>
            </div>
            <div>
              <p style="color: #8c8c8c; margin-bottom: 4px;">状态</p>
              <p><a-tag :color="getStatusColor(viewRecord.status)">{{ getStatusText(viewRecord.status) }}</a-tag></p>
            </div>
          </div>
        </div>
        
        <div style="margin-bottom: 16px;">
          <h3 style="margin-bottom: 8px;">详细信息</h3>
          <div v-if="viewRecord.type === 'vaccination'">
            <p style="color: #8c8c8c; margin-bottom: 4px;">防疫数量</p>
            <p>{{ viewRecord.count }} 头/只</p>
            <p style="color: #8c8c8c; margin-bottom: 4px; margin-top: 8px;">使用疫苗</p>
            <p>{{ viewRecord.vaccineName }}</p>
          </div>
          <div v-else-if="viewRecord.type === 'disinfection'">
            <p style="color: #8c8c8c; margin-bottom: 4px;">防疫范围</p>
            <p>{{ viewRecord.area }}</p>
            <p style="color: #8c8c8c; margin-bottom: 4px; margin-top: 8px;">防疫药品</p>
            <p>{{ viewRecord.disinfectant }}</p>
          </div>
          <div v-else-if="viewRecord.type === 'health_check'">
            <p style="color: #8c8c8c; margin-bottom: 4px;">检查结果</p>
            <p>{{ viewRecord.healthResult === 'normal' ? '正常' : '异常' }}</p>
          </div>
          <div v-else-if="viewRecord.type === 'other'">
            <p style="color: #8c8c8c; margin-bottom: 4px;">防疫描述</p>
            <p>{{ viewRecord.description }}</p>
          </div>
          <div style="margin-top: 12px;">
            <p style="color: #8c8c8c; margin-bottom: 4px;">备注</p>
            <p>{{ viewRecord.notes || '-' }}</p>
          </div>
        </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, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import api from '@/utils/api'

// 搜索条件
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 currentRecord = reactive({
  id: '',
  farmName: '',
  type: 'vaccination',
  epidemicStaff: '',
  phone: '',
  epidemicDate: null,
  count: 0,
  vaccineName: '',
  area: '',
  disinfectant: '',
  healthResult: 'normal',
  description: '',
  notes: '',
  status: 'completed',
  createdAt: ''
})

const viewRecord = ref(null)

// 记录列表数据
const recordsData = ref([])
const loading = ref(false)

// 表格列定义
const columns = [
  {
    title: '养殖场名称',
    dataIndex: 'farmName',
    key: 'farmName',
    ellipsis: true
  },
  {
    title: '防疫类型',
    dataIndex: 'type',
    key: 'type',
    width: 120,
    customRender: ({ text }) => getTypeText(text)
  },
  {
    title: '防疫员',
    dataIndex: 'epidemicStaff',
    key: 'epidemicStaff',
    width: 100
  },
  {
    title: '防疫日期',
    dataIndex: 'epidemicDate',
    key: 'epidemicDate',
    width: 120
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 80,
    slots: { customRender: 'status' }
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 120
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    slots: { customRender: 'action' }
  }
]

// 状态文本
const getStatusText = (status) => {
  const statusMap = {
    completed: '已完成',
    pending: '待完成',
    failed: '未通过'
  }
  return statusMap[status] || status
}

// 状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    completed: 'green',
    pending: 'orange',
    failed: 'red'
  }
  return colorMap[status] || 'default'
}

// 类型文本
const getTypeText = (type) => {
  const typeMap = {
    vaccination: '疫苗接种',
    disinfection: '消毒',
    health_check: '健康检查',
    other: '其他'
  }
  return typeMap[type] || type
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  if (typeof date === 'string') return date
  return date.toISOString().split('T')[0]
}

// 获取防疫记录列表
const fetchRecords = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      keyword: searchKeyword.value,
      type: typeFilter.value,
      status: statusFilter.value,
      startDate: dateRange.value?.[0]?.format('YYYY-MM-DD'),
      endDate: dateRange.value?.[1]?.format('YYYY-MM-DD')
    }
    
    const res = await api.epidemicRecord.getList(params)
    if (res.code === 200) {
      recordsData.value = res.data.list || []
      pagination.total = res.data.total || 0
    } else {
      message.error(res.message || '获取防疫记录列表失败')
    }
  } catch (error) {
    console.error('获取防疫记录列表失败:', error)
    message.error('获取防疫记录列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.current = 1
  fetchRecords()
}

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

// 新增记录
const handleAddRecord = () => {
  // 重置表单
  Object.assign(currentRecord, {
    id: '',
    farmName: '',
    type: 'vaccination',
    epidemicStaff: '',
    phone: '',
    epidemicDate: null,
    count: 0,
    vaccineName: '',
    area: '',
    disinfectant: '',
    healthResult: 'normal',
    description: '',
    notes: '',
    status: 'completed',
    createdAt: ''
  })
  isEditing.value = false
  isAddEditModalOpen.value = true
}

// 编辑记录
const handleEdit = (record) => {
  // 复制记录到当前编辑对象
  Object.assign(currentRecord, { ...record })
  isEditing.value = true
  isAddEditModalOpen.value = true
}

// 查看记录
const handleView = (record) => {
  viewRecord.value = { ...record }
  isViewModalOpen.value = true
}

// 删除记录
const handleDelete = async (id) => {
  try {
    const res = await api.epidemicRecord.delete(id)
    if (res.code === 200) {
      message.success('删除成功')
      await fetchRecords()
    } else {
      message.error(res.message || '删除失败')
    }
  } catch (error) {
    console.error('删除防疫记录失败:', error)
    message.error('删除失败')
  }
}

// 保存记录
const handleSave = async () => {
  try {
    // 准备提交数据
    const submitData = {
      farmName: currentRecord.farmName,
      type: currentRecord.type,
      epidemicStaff: currentRecord.epidemicStaff,
      phone: currentRecord.phone,
      epidemicDate: currentRecord.epidemicDate?.format('YYYY-MM-DD'),
      count: currentRecord.count || 0,
      vaccineName: currentRecord.vaccineName || '',
      area: currentRecord.area || '',
      disinfectant: currentRecord.disinfectant || '',
      healthResult: currentRecord.healthResult || '',
      description: currentRecord.description || '',
      notes: currentRecord.notes || '',
      status: currentRecord.status
    }
    
    let res
    if (isEditing.value) {
      // 更新现有记录
      res = await api.epidemicRecord.update(currentRecord.id, submitData)
    } else {
      // 添加新记录
      res = await api.epidemicRecord.create(submitData)
    }
    
    if (res.code === 200) {
      message.success(isEditing.value ? '更新成功' : '新增成功')
      isAddEditModalOpen.value = false
      await fetchRecords()
    } else {
      message.error(res.message || (isEditing.value ? '更新失败' : '新增失败'))
    }
  } catch (error) {
    console.error('保存防疫记录失败:', error)
    message.error(isEditing.value ? '更新失败' : '新增失败')
  }
}

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

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

// 分页变化处理
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchRecords()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchRecords()
})
</script>

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