<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="foot_and_mouth_disease">口蹄疫疫苗</a-select-option>
          <a-select-option value="bovine_tuberculosis">牛结核病疫苗</a-select-option>
          <a-select-option value="brucellosis">布鲁氏菌病疫苗</a-select-option>
          <a-select-option value="rabies">狂犬病疫苗</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="valid">有效</a-select-option>
          <a-select-option value="expired">过期</a-select-option>
          <a-select-option value="low_stock">库存不足</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" danger @click="handleAddVaccine">
          <span class="iconfont icon-tianjia"></span> 新增疫苗
        </a-button>
      </div>
    </a-card>
    
    <!-- 数据列表 -->
    <a-card>
      <a-table
        :columns="columns"
        :data-source="vaccinesData"
        :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>
            <a-button size="small" @click="handleBatchIn(record.id)">入库</a-button>
            <a-button size="small" @click="handleBatchOut(record.id)">出库</a-button>
          </div>
        </template>
      </a-table>
    </a-card>
    
    <!-- 新增/编辑疫苗模态框 -->
    <a-modal
      v-model:open="isAddEditModalOpen"
      :title="isEditing ? '编辑疫苗信息' : '新增疫苗信息'"
      :footer="null"
      :width="600"
    >
      <a-form
        :model="currentVaccine"
        layout="vertical"
      >
        <a-form-item label="疫苗名称"
                     :rules="[{ required: true, message: '请输入疫苗名称' }]">
          <a-input v-model:value="currentVaccine.name" placeholder="请输入疫苗名称" />
        </a-form-item>
        
        <a-form-item label="疫苗类型"
                     :rules="[{ required: true, message: '请选择疫苗类型' }]">
          <a-select v-model:value="currentVaccine.type" placeholder="请选择疫苗类型">
            <a-select-option value="foot_and_mouth_disease">口蹄疫疫苗</a-select-option>
            <a-select-option value="bovine_tuberculosis">牛结核病疫苗</a-select-option>
            <a-select-option value="brucellosis">布鲁氏菌病疫苗</a-select-option>
            <a-select-option value="rabies">狂犬病疫苗</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="currentVaccine.manufacturer" placeholder="请输入生产厂商" />
        </a-form-item>
        
        <a-form-item label="批准文号"
                     :rules="[{ required: true, message: '请输入批准文号' }]">
          <a-input v-model:value="currentVaccine.approvalNumber" placeholder="请输入批准文号" />
        </a-form-item>
        
        <a-form-item label="规格"
                     :rules="[{ required: true, message: '请输入规格' }]">
          <a-input v-model:value="currentVaccine.specification" placeholder="请输入规格" />
        </a-form-item>
        
        <a-form-item label="单价（元）"
                     :rules="[
                       { required: true, message: '请输入单价' },
                       { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的金额格式' }
                     ]">
          <a-input-number v-model:value="currentVaccine.price" min="0" precision="2" placeholder="请输入单价" />
        </a-form-item>
        
        <a-form-item label="有效期（天）"
                     :rules="[
                       { required: true, message: '请输入有效期' },
                       { type: 'number', min: 1, message: '有效期至少为1天' }
                     ]">
          <a-input-number v-model:value="currentVaccine.validDays" min="1" placeholder="请输入有效期（天）" />
        </a-form-item>
        
        <a-form-item label="储存条件"
                     :rules="[{ required: true, message: '请输入储存条件' }]">
          <a-input v-model:value="currentVaccine.storageCondition" placeholder="请输入储存条件" />
        </a-form-item>
        
        <a-form-item label="备注">
          <a-input.TextArea v-model:value="currentVaccine.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="300"
    >
      <div v-if="viewVaccine">
        <div style="display: flex; flex-direction: column; gap: 12px;">
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <span style="color: #8c8c8c; min-width: 80px;">疫苗名称：</span>
            <span>{{ viewVaccine.name }}</span>
          </div>
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <span style="color: #8c8c8c; min-width: 80px;">疫苗类型：</span>
            <span>{{ getTypeText(viewVaccine.type) }}</span>
          </div>
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <span style="color: #8c8c8c; min-width: 80px;">生产厂商：</span>
            <span>{{ viewVaccine.manufacturer }}</span>
          </div>
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <span style="color: #8c8c8c; min-width: 80px;">批准文号：</span>
            <span>{{ viewVaccine.approvalNumber }}</span>
          </div>
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <span style="color: #8c8c8c; min-width: 80px;">规格：</span>
            <span>{{ viewVaccine.specification }}</span>
          </div>
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <span style="color: #8c8c8c; min-width: 80px;">单价：</span>
            <span>￥{{ viewVaccine.price }}</span>
          </div>
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <span style="color: #8c8c8c; min-width: 80px;">有效期：</span>
            <span>{{ viewVaccine.validDays }} 天</span>
          </div>
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <span style="color: #8c8c8c; min-width: 80px;">储存条件：</span>
            <span>{{ viewVaccine.storageCondition }}</span>
          </div>
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <span style="color: #8c8c8c; min-width: 80px;">库存数量：</span>
            <span>{{ viewVaccine.stockCount }}</span>
          </div>
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <span style="color: #8c8c8c; min-width: 80px;">状态：</span>
            <a-tag :color="getStatusColor(viewVaccine.status)">{{ getStatusText(viewVaccine.status) }}</a-tag>
          </div>
          <div style="display: flex; flex-direction: column; gap: 4px; margin-top: 8px;">
            <span style="color: #8c8c8c;">备注：</span>
            <span>{{ viewVaccine.notes || '-' }}</span>
          </div>
        </div>
      </div>
      
      <div style="display: flex; justify-content: flex-end; margin-top: 24px;">
        <a-button @click="handleCloseView">关闭</a-button>
      </div>
    </a-modal>
    
    <!-- 批量入库模态框 -->
    <a-modal
      v-model:open="isInModalOpen"
      title="疫苗入库"
      :footer="null"
      width={350}
    >
      <a-form
        :model="batchInForm"
        layout="vertical"
      >
        <a-form-item label="疫苗名称">
          <p>{{ viewVaccine?.name || '' }}</p>
        </a-form-item>
        
        <a-form-item label="入库数量"
                     :rules="[
                       { required: true, message: '请输入入库数量' },
                       { type: 'number', min: 1, message: '入库数量至少为1' }
                     ]">
          <a-input-number v-model:value="batchInForm.count" min="1" placeholder="请输入入库数量" />
        </a-form-item>
        
        <a-form-item label="入库批次号"
                     :rules="[{ required: true, message: '请输入入库批次号' }]">
          <a-input v-model:value="batchInForm.batchNumber" placeholder="请输入入库批次号" />
        </a-form-item>
        
        <a-form-item label="入库日期"
                     :rules="[{ required: true, message: '请选择入库日期' }]">
          <a-date-picker
            v-model:value="batchInForm.inDate"
            style="width: 100%;"
            format="YYYY-MM-DD"
          />
        </a-form-item>
      </a-form>
      
      <div style="display: flex; justify-content: flex-end; gap: 12px; margin-top: 24px;">
        <a-button @click="handleCloseInModal">取消</a-button>
        <a-button type="primary" @click="handleConfirmIn">确认入库</a-button>
      </div>
    </a-modal>
    
    <!-- 批量出库模态框 -->
    <a-modal
      v-model:open="isOutModalOpen"
      title="疫苗出库"
      :footer="null"
      width={350}
    >
      <a-form
        :model="batchOutForm"
        layout="vertical"
      >
        <a-form-item label="疫苗名称">
          <p>{{ viewVaccine?.name || '' }}</p>
        </a-form-item>
        
        <a-form-item label="当前库存">
          <p>{{ viewVaccine?.stockCount || 0 }}</p>
        </a-form-item>
        
        <a-form-item label="出库数量"
                     :rules="[
                       { required: true, message: '请输入出库数量' },
                       { type: 'number', min: 1, message: '出库数量至少为1' },
                       { 
                         validator: (_, value) => {
                           if (value > (viewVaccine?.stockCount || 0)) {
                             return Promise.reject(new Error('出库数量不能大于当前库存'))
                           }
                           return Promise.resolve()
                         }
                       }
                     ]">
          <a-input-number v-model:value="batchOutForm.count" min="1" :max="viewVaccine?.stockCount" placeholder="请输入出库数量" />
        </a-form-item>
        
        <a-form-item label="出库用途"
                     :rules="[{ required: true, message: '请输入出库用途' }]">
          <a-input v-model:value="batchOutForm.purpose" placeholder="请输入出库用途" />
        </a-form-item>
        
        <a-form-item label="出库日期"
                     :rules="[{ required: true, message: '请选择出库日期' }]">
          <a-date-picker
            v-model:value="batchOutForm.outDate"
            style="width: 100%;"
            format="YYYY-MM-DD"
          />
        </a-form-item>
      </a-form>
      
      <div style="display: flex; justify-content: flex-end; gap: 12px; margin-top: 24px;">
        <a-button @click="handleCloseOutModal">取消</a-button>
        <a-button type="primary" @click="handleConfirmOut">确认出库</a-button>
      </div>
    </a-modal>
  </div>
</template>

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

// 搜索条件
const searchKeyword = ref('')
const typeFilter = ref('')
const statusFilter = 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 isInModalOpen = ref(false)
const isOutModalOpen = ref(false)
const isEditing = ref(false)

// 当前编辑/查看的疫苗
const currentVaccine = reactive({
  id: '',
  name: '',
  type: 'foot_and_mouth_disease',
  manufacturer: '',
  approvalNumber: '',
  specification: '',
  price: 0,
  validDays: 365,
  storageCondition: '',
  notes: '',
  stockCount: 0,
  status: 'valid',
  createdAt: ''
})

const viewVaccine = ref(null)

// 批量入库表单
const batchInForm = reactive({
  count: 1,
  batchNumber: '',
  inDate: new Date()
})

// 批量出库表单
const batchOutForm = reactive({
  count: 1,
  purpose: '',
  outDate: new Date()
})

// 疫苗列表数据
const vaccinesData = ref([])
const loading = ref(false)

// 表格列定义
const columns = [
  {
    title: '疫苗名称',
    dataIndex: 'name',
    key: 'name',
    ellipsis: true
  },
  {
    title: '疫苗类型',
    dataIndex: 'type',
    key: 'type',
    width: 120,
    customRender: ({ text }) => getTypeText(text)
  },
  {
    title: '生产厂商',
    dataIndex: 'manufacturer',
    key: 'manufacturer',
    ellipsis: true
  },
  {
    title: '规格',
    dataIndex: 'specification',
    key: 'specification',
    width: 100
  },
  {
    title: '单价(元)',
    dataIndex: 'price',
    key: 'price',
    width: 80,
    customRender: ({ text }) => `￥${text}`
  },
  {
    title: '库存数量',
    dataIndex: 'stockCount',
    key: 'stockCount',
    width: 80
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 80,
    slots: { customRender: 'status' }
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 120
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
    slots: { customRender: 'action' }
  }
]

// 状态文本
const getStatusText = (status) => {
  const statusMap = {
    valid: '有效',
    expired: '过期',
    low_stock: '库存不足'
  }
  return statusMap[status] || status
}

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

// 类型文本
const getTypeText = (type) => {
  const typeMap = {
    foot_and_mouth_disease: '口蹄疫疫苗',
    bovine_tuberculosis: '牛结核病疫苗',
    brucellosis: '布鲁氏菌病疫苗',
    rabies: '狂犬病疫苗',
    other: '其他疫苗'
  }
  return typeMap[type] || type
}

// 获取疫苗列表
const fetchVaccines = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      keyword: searchKeyword.value,
      type: typeFilter.value,
      status: statusFilter.value
    }
    
    const res = await api.vaccine.getList(params)
    if (res.code === 200) {
      vaccinesData.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
  fetchVaccines()
}

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

// 新增疫苗
const handleAddVaccine = () => {
  // 重置表单
  Object.assign(currentVaccine, {
    id: '',
    name: '',
    type: 'foot_and_mouth_disease',
    manufacturer: '',
    approvalNumber: '',
    specification: '',
    price: 0,
    validDays: 365,
    storageCondition: '',
    notes: '',
    stockCount: 0,
    status: 'valid',
    createdAt: ''
  })
  isEditing.value = false
  isAddEditModalOpen.value = true
}

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

// 查看疫苗
const handleView = (record) => {
  viewVaccine.value = { ...record }
  isViewModalOpen.value = true
}

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

// 保存疫苗
const handleSave = async () => {
  try {
    let res
    if (isEditing.value) {
      res = await api.vaccine.update(currentVaccine.id, currentVaccine)
    } else {
      res = await api.vaccine.create(currentVaccine)
    }
    
    if (res.code === 200) {
      isAddEditModalOpen.value = false
      message.success(isEditing.value ? '更新成功' : '新增成功')
      await fetchVaccines()
    } 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 handleBatchIn = (id) => {
  // 找到对应的疫苗
  const vaccine = vaccinesData.value.find(item => item.id === id)
  if (vaccine) {
    viewVaccine.value = { ...vaccine }
    // 重置入库表单
    Object.assign(batchInForm, {
      count: 1,
      batchNumber: '',
      inDate: new Date()
    })
    isInModalOpen.value = true
  }
}

// 确认入库
const handleConfirmIn = async () => {
  try {
    if (viewVaccine.value) {
      const res = await api.vaccine.stockIn(viewVaccine.value.id, {
        count: batchInForm.count,
        batchNumber: batchInForm.batchNumber,
        inDate: batchInForm.inDate
      })
      
      if (res.code === 200) {
        message.success('疫苗入库成功')
        await fetchVaccines()
      } else {
        message.error(res.message || '入库失败')
      }
    }
  } catch (error) {
    console.error('疫苗入库失败:', error)
    message.error('入库失败')
  } finally {
    isInModalOpen.value = false
  }
}

// 关闭入库模态框
const handleCloseInModal = () => {
  isInModalOpen.value = false
}

// 批量出库
const handleBatchOut = (id) => {
  // 找到对应的疫苗
  const vaccine = vaccinesData.value.find(item => item.id === id)
  if (vaccine && vaccine.stockCount > 0) {
    viewVaccine.value = { ...vaccine }
    // 重置出库表单
    Object.assign(batchOutForm, {
      count: 1,
      purpose: '',
      outDate: new Date()
    })
    isOutModalOpen.value = true
  } else {
    message.error('疫苗库存不足，无法出库')
  }
}

// 确认出库
const handleConfirmOut = async () => {
  try {
    if (viewVaccine.value && batchOutForm.count <= viewVaccine.value.stockCount) {
      const res = await api.vaccine.stockOut(viewVaccine.value.id, {
        count: batchOutForm.count,
        purpose: batchOutForm.purpose,
        outDate: batchOutForm.outDate
      })
      
      if (res.code === 200) {
        message.success('疫苗出库成功')
        await fetchVaccines()
      } else {
        message.error(res.message || '出库失败')
      }
    }
  } catch (error) {
    console.error('疫苗出库失败:', error)
    message.error('出库失败')
  } finally {
    isOutModalOpen.value = false
  }
}

// 关闭出库模态框
const handleCloseOutModal = () => {
  isOutModalOpen.value = false
}

// 表格变化处理
const handleTableChange = (paginationInfo) => {
  pagination.current = paginationInfo.current
  pagination.pageSize = paginationInfo.pageSize
  fetchVaccines()
}

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

<style scoped>
  h1 {
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 20px;
    color: #333;
  }
  
  /* 控制弹窗宽度 */
  :deep(.ant-modal) {
    max-width: 300px !important;
  }
  
  :deep(.ant-modal-content) {
    max-width: 300px !important;
  }
</style>