<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="livestockFilter" placeholder="防疫畜别" style="width: 120px;">
          <a-select-option value="">全部</a-select-option>
          <a-select-option value="牛">牛</a-select-option>
          <a-select-option value="羊">羊</a-select-option>
          <a-select-option value="猪">猪</a-select-option>
          <a-select-option value="鸡">鸡</a-select-option>
          <a-select-option value="犬">犬</a-select-option>
        </a-select>
        
        <a-select v-model:value="diseaseFilter" placeholder="疫病类别" style="width: 120px;">
          <a-select-option value="">全部</a-select-option>
          <a-select-option value="口蹄疫">口蹄疫</a-select-option>
          <a-select-option value="布鲁氏菌病">布鲁氏菌病</a-select-option>
          <a-select-option value="猪瘟">猪瘟</a-select-option>
          <a-select-option value="禽流感">禽流感</a-select-option>
          <a-select-option value="狂犬病">狂犬病</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="active">启用</a-select-option>
          <a-select-option value="inactive">禁用</a-select-option>
        </a-select>
        
        <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" @click="handleAddActivity">
          <span class="iconfont icon-tianjia"></span> 新增活动
        </a-button>
      </div>
    </a-card>
    
    <!-- 数据列表 -->
    <a-card>
      <a-table
        :columns="columns"
        :data-source="activitiesData"
        :pagination="pagination"
        :loading="loading"
        row-key="id"
        :row-selection="{ selectedRowKeys, onChange: onSelectChange }"
        :scroll="{ x: 1200 }"
        @change="handleTableChange"
      >
      </a-table>
    </a-card>
    
    <!-- 新增/编辑活动模态框 -->
    <a-modal
      v-model:open="isAddEditModalOpen"
      :title="isEditing ? '编辑防疫活动' : '新增防疫活动'"
      :footer="null"
      :width="600"
    >
      <a-form
        :model="currentActivity"
        layout="vertical"
      >
        <a-form-item label="活动名称"
                     :rules="[{ required: true, message: '请输入活动名称' }]">
          <a-input v-model:value="currentActivity.activityName" placeholder="请输入活动名称" />
        </a-form-item>
        
        <a-form-item label="防疫畜别"
                     :rules="[{ required: true, message: '请选择防疫畜别' }]">
          <a-select v-model:value="currentActivity.livestockCategory" placeholder="请选择防疫畜别">
            <a-select-option value="牛">牛</a-select-option>
            <a-select-option value="羊">羊</a-select-option>
            <a-select-option value="猪">猪</a-select-option>
            <a-select-option value="鸡">鸡</a-select-option>
            <a-select-option value="犬">犬</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="疫病类别"
                     :rules="[{ required: true, message: '请选择疫病类别' }]">
          <a-select v-model:value="currentActivity.diseaseCategory" placeholder="请选择疫病类别">
            <a-select-option value="口蹄疫">口蹄疫</a-select-option>
            <a-select-option value="布鲁氏菌病">布鲁氏菌病</a-select-option>
            <a-select-option value="猪瘟">猪瘟</a-select-option>
            <a-select-option value="禽流感">禽流感</a-select-option>
            <a-select-option value="狂犬病">狂犬病</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="使用疫苗"
                     :rules="[{ required: true, message: '请输入使用疫苗' }]">
          <a-input v-model:value="currentActivity.vaccineUsed" placeholder="请输入使用疫苗" />
        </a-form-item>
        
        <a-form-item label="疫苗批次"
                     :rules="[{ required: true, message: '请输入疫苗批次' }]">
          <a-input v-model:value="currentActivity.vaccineBatch" placeholder="请输入疫苗批次" />
        </a-form-item>
        
        <a-form-item label="防疫日期"
                     :rules="[{ required: true, message: '请输入防疫日期' }]">
          <a-input v-model:value="currentActivity.preventionDate" placeholder="请输入防疫日期，如：2023-04-01至2023-08-01" />
        </a-form-item>
        
        <a-form-item label="活动状态">
          <a-radio-group v-model:value="currentActivity.activityStatus">
            <a-radio value="active">启用</a-radio>
            <a-radio value="inactive">禁用</a-radio>
          </a-radio-group>
        </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>
    
  </div>
</template>

<script setup>
import { ref, reactive, computed, h, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import epidemicActivityApi from '@/utils/epidemicActivityApi'

// 搜索条件
const searchKeyword = ref('')
const livestockFilter = ref('')
const diseaseFilter = ref('')
const statusFilter = ref('')

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

// 加载状态
const loading = ref(false)

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

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

// 当前编辑的活动
const currentActivity = reactive({
  id: '',
  activityName: '',
  livestockCategory: '',
  diseaseCategory: '',
  vaccineUsed: '',
  vaccineBatch: '',
  preventionDate: '',
  activityStatus: 'active'
})


// 活动列表数据
const activitiesData = ref([])

// 表格列定义
const columns = [
  {
    title: '活动名称',
    dataIndex: 'activityName',
    key: 'activityName',
    width: 100,
    ellipsis: true
  },
  {
    title: '防疫畜别',
    dataIndex: 'livestockCategory',
    key: 'livestockCategory',
    width: 80
  },
  {
    title: '疫病类别',
    dataIndex: 'diseaseCategory',
    key: 'diseaseCategory',
    width: 100
  },
  {
    title: '使用疫苗',
    dataIndex: 'vaccineUsed',
    key: 'vaccineUsed',
    width: 150,
    ellipsis: true
  },
  {
    title: '疫苗批次',
    dataIndex: 'vaccineBatch',
    key: 'vaccineBatch',
    width: 100
  },
  {
    title: '防疫日期',
    dataIndex: 'preventionDate',
    key: 'preventionDate',
    width: 200
  },
  {
    title: '活动状态',
    dataIndex: 'activityStatus',
    key: 'activityStatus',
    width: 100,
    customRender: ({ record }) => {
      return {
        children: [
          h('div', { style: 'display: flex; align-items: center; gap: 8px;' }, [
            h('a-switch', {
              checked: record.activityStatus === 'active',
              size: 'small',
              onChange: (checked) => handleToggleStatus(record, checked)
            }),
            h('span', record.activityStatus === 'active' ? '启用' : '禁用')
          ])
        ]
      }
    }
  },
  {
    title: '更新时间',
    dataIndex: 'updatedAt',
    key: 'updatedAt',
    width: 150
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
    fixed: 'right',
    customRender: ({ record }) => {
      return {
        children: [
          h('div', { style: 'display: flex; gap: 8px;' }, [
            h('a-button', {
              size: 'small',
              type: 'primary',
              onClick: () => handleEdit(record)
            }, '编辑'),
            h('a-button', {
              size: 'small',
              danger: true,
              onClick: () => handleDelete(record.id)
            }, '删除')
          ])
        ]
      }
    }
  }
]

// 获取防疫活动列表
const fetchActivities = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      activityName: searchKeyword.value,
      livestockCategory: livestockFilter.value,
      diseaseCategory: diseaseFilter.value,
      activityStatus: statusFilter.value
    }
    
    const response = await epidemicActivityApi.getActivities(params)
    if (response.code === 200) {
      activitiesData.value = response.data.list
      pagination.total = response.data.total
    } else {
      message.error(response.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取防疫活动列表失败:', error)
    message.error('获取数据失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 切换活动状态
const handleToggleStatus = async (record, checked) => {
  try {
    const newStatus = checked ? 'active' : 'inactive'
    const response = await epidemicActivityApi.toggleActivityStatus(record.id)
    if (response.code === 200) {
      record.activityStatus = newStatus
      message.success(`活动状态已${newStatus === 'active' ? '启用' : '禁用'}`)
    } else {
      message.error(response.message || '状态更新失败')
    }
  } catch (error) {
    console.error('切换状态失败:', error)
    message.error('状态更新失败')
  }
}

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

// 重置处理
const handleReset = () => {
  searchKeyword.value = ''
  livestockFilter.value = ''
  diseaseFilter.value = ''
  statusFilter.value = ''
  pagination.current = 1
  fetchActivities()
}

// 新增活动
const handleAddActivity = () => {
  // 重置表单
  Object.assign(currentActivity, {
    id: '',
    activityName: '',
    livestockCategory: '',
    diseaseCategory: '',
    vaccineUsed: '',
    vaccineBatch: '',
    preventionDate: '',
    activityStatus: 'active'
  })
  isEditing.value = false
  isAddEditModalOpen.value = true
}

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

// 删除活动
const handleDelete = async (id) => {
  try {
    const response = await epidemicActivityApi.deleteActivity(id)
    if (response.code === 200) {
      message.success('删除成功')
      fetchActivities() // 重新加载数据
    } else {
      message.error(response.message || '删除失败')
    }
  } catch (error) {
    console.error('删除活动失败:', error)
    message.error('删除失败')
  }
}

// 保存活动
const handleSave = async () => {
  try {
    let response
    if (isEditing.value) {
      // 更新现有活动
      response = await epidemicActivityApi.updateActivity(currentActivity.id, currentActivity)
    } else {
      // 添加新活动
      response = await epidemicActivityApi.createActivity(currentActivity)
    }
    
    if (response.code === 200 || response.code === 201) {
      message.success(isEditing.value ? '更新成功' : '新增成功')
      isAddEditModalOpen.value = false
      fetchActivities() // 重新加载数据
    } else {
      message.error(response.message || '保存失败')
    }
  } catch (error) {
    console.error('保存活动失败:', error)
    message.error('保存失败')
  }
}

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

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

// 组件挂载时加载数据
onMounted(() => {
  fetchActivities()
})
</script>

<style scoped>
  h1 {
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 20px;
    color: #333;
  }
  
  /* 弹窗样式优化 */
  :deep(.ant-modal) {
    max-width: 600px;
  }
  
  :deep(.ant-modal-content) {
    border-radius: 8px;
  }
  
  :deep(.ant-modal-header) {
    border-bottom: 1px solid #f0f0f0;
    padding: 16px 24px;
  }
  
  :deep(.ant-modal-title) {
    font-size: 16px;
    font-weight: 600;
    color: #262626;
  }
  
  :deep(.ant-modal-body) {
    padding: 24px;
  }
  
  :deep(.ant-form-item-label) {
    font-weight: 500;
    color: #262626;
  }
  
  :deep(.ant-input),
  :deep(.ant-select-selector) {
    border-radius: 6px;
  }
  
  :deep(.ant-radio-group) {
    display: flex;
    gap: 16px;
  }
  
  :deep(.ant-radio-wrapper) {
    margin-right: 0;
  }
  
  /* 按钮样式优化 */
  :deep(.ant-btn) {
    border-radius: 6px;
    font-weight: 500;
    height: 32px;
    padding: 4px 15px;
  }
  
  :deep(.ant-btn-primary) {
    background-color: #1890ff;
    border-color: #1890ff;
  }
  
  :deep(.ant-btn-primary:hover) {
    background-color: #40a9ff;
    border-color: #40a9ff;
  }
  
  :deep(.ant-btn:not(.ant-btn-primary)) {
    color: #595959;
    border-color: #d9d9d9;
  }
  
  :deep(.ant-btn:not(.ant-btn-primary):hover) {
    color: #1890ff;
    border-color: #1890ff;
  }
</style>