<template>
  <div class="harmless-registration-container">
    <div class="page-header">
      <h1>无害化登记管理</h1>
    </div>
    
    <div class="content-wrapper">
      <!-- 工具栏 -->
      <div class="toolbar">
        <a-button type="primary" @click="handleAdd">新增无害化登记</a-button>
        <a-range-picker 
          style="width: 300px; margin-left: 16px;"
          @change="handleDateChange"
          v-model:value="dateRange"
        />
        <a-input-search 
          placeholder="搜索登记编号" 
          style="width: 300px; margin-left: 16px;"
          @search="handleSearch"
          v-model:value="searchKeyword"
        />
      </div>
      
      <!-- 数据表格 -->
      <a-table 
        :columns="columns" 
        :data-source="harmlessRegistrations" 
        row-key="id"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <template #column:action="{ record }">
          <a-space>
            <a-button type="link" @click="handleEdit(record)">编辑</a-button>
            <a-popconfirm
              title="确定要删除该无害化登记吗？"
              @confirm="handleDelete(record.id)"
            >
              <a-button type="link" danger>删除</a-button>
            </a-popconfirm>
            <a-button type="link" @click="handleDetail(record)">详情</a-button>
          </a-space>
        </template>
        <template #column:status="{ text }">
          <a-tag :color="getStatusColor(text)">
            {{ text }}
          </a-tag>
        </template>
      </a-table>
    </div>
    
    <!-- 新增/编辑表单 -->
    <a-modal
      v-model:open="isModalOpen"
      title="无害化登记信息"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form-model
        ref="formRef"
        :model="formData"
        :rules="formRules"
        layout="vertical"
      >
        <a-form-model-item label="登记编号" prop="registrationNumber">
          <a-input v-model="formData.registrationNumber" placeholder="请输入登记编号" />
        </a-form-model-item>
        <a-form-model-item label="动物类型" prop="animalType">
          <a-input v-model="formData.animalType" placeholder="请输入动物类型" />
        </a-form-model-item>
        <a-form-model-item label="数量" prop="quantity">
          <a-input-number v-model="formData.quantity" placeholder="请输入数量" min="1" />
        </a-form-model-item>
        <a-form-model-item label="原因" prop="reason">
          <a-input v-model="formData.reason" placeholder="请输入原因" />
        </a-form-model-item>
        <a-form-model-item label="处理方式" prop="processingMethod">
          <a-input v-model="formData.processingMethod" placeholder="请输入处理方式" />
        </a-form-model-item>
        <a-form-model-item label="处理场所" prop="processingPlace">
          <a-input v-model="formData.processingPlace" placeholder="请输入处理场所" />
        </a-form-model-item>
        <a-form-model-item label="处理日期" prop="processingDate">
          <a-date-picker v-model="formData.processingDate" placeholder="请选择处理日期" />
        </a-form-model-item>
        <a-form-model-item label="登记人" prop="registrant">
          <a-input v-model="formData.registrant" placeholder="请输入登记人" />
        </a-form-model-item>
        <a-form-model-item label="状态" prop="status">
          <a-select v-model="formData.status">
            <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-model-item>
      </a-form-model>
    </a-modal>
    
    <!-- 详情弹窗 -->
    <a-modal
      v-model:open="isDetailModalOpen"
      title="无害化登记详情"
      @cancel="handleDetailCancel"
    >
      <div class="detail-container">
        <div class="detail-row">
          <span class="detail-label">登记编号：</span>
          <span class="detail-value">{{ detailData.registrationNumber }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">动物类型：</span>
          <span class="detail-value">{{ detailData.animalType }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">数量：</span>
          <span class="detail-value">{{ detailData.quantity }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">原因：</span>
          <span class="detail-value">{{ detailData.reason }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">处理方式：</span>
          <span class="detail-value">{{ detailData.processingMethod }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">处理场所：</span>
          <span class="detail-value">{{ detailData.processingPlace }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">处理日期：</span>
          <span class="detail-value">{{ detailData.processingDate }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">登记人：</span>
          <span class="detail-value">{{ detailData.registrant }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">状态：</span>
          <span class="detail-value"><a-tag :color="getStatusColor(detailData.status)">
            {{ detailData.status }}
          </a-tag></span>
        </div>
        <div class="detail-row">
          <span class="detail-label">创建时间：</span>
          <span class="detail-value">{{ detailData.createTime }}</span>
        </div>
        <div class="detail-row">
          <span class="detail-label">更新时间：</span>
          <span class="detail-value">{{ detailData.updateTime }}</span>
        </div>
      </div>
    </a-modal>
  </div>
</template>

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

export default {
  setup() {
    // 数据列表
    const harmlessRegistrations = ref([])
    
    // 加载状态
    const loading = ref(false)
    
    // 搜索关键词
    const searchKeyword = ref('')
    
    // 日期范围
    const dateRange = ref([])
    
    // 分页配置
    const pagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: (total) => `共 ${total} 条记录`
    })
    
    // 模态框状态
    const isModalOpen = ref(false)
    const isDetailModalOpen = ref(false)
    
    // 表单引用
    const formRef = ref(null)
    
    // 表单数据
    const formData = reactive({
      id: '',
      registrationNumber: '',
      animalType: '',
      quantity: 1,
      reason: '',
      processingMethod: '',
      processingPlace: '',
      processingDate: null,
      registrant: '',
      status: '待处理'
    })
    
    // 详情数据
    const detailData = reactive({})
    
    // 表单验证规则
    const formRules = {
      registrationNumber: [
        { required: true, message: '请输入登记编号', trigger: 'blur' }
      ],
      animalType: [
        { required: true, message: '请输入动物类型', trigger: 'blur' }
      ],
      quantity: [
        { required: true, message: '请输入数量', trigger: 'blur' },
        { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
      ],
      reason: [
        { required: true, message: '请输入原因', trigger: 'blur' }
      ],
      processingMethod: [
        { required: true, message: '请输入处理方式', trigger: 'blur' }
      ],
      processingPlace: [
        { required: true, message: '请输入处理场所', trigger: 'blur' }
      ],
      processingDate: [
        { required: true, message: '请选择处理日期', trigger: 'change' }
      ],
      registrant: [
        { required: true, message: '请输入登记人', trigger: 'blur' }
      ]
    }
    
    // 表格列配置
    const columns = [
      {
        title: '登记编号',
        dataIndex: 'registrationNumber',
        key: 'registrationNumber'
      },
      {
        title: '动物类型',
        dataIndex: 'animalType',
        key: 'animalType'
      },
      {
        title: '数量',
        dataIndex: 'quantity',
        key: 'quantity'
      },
      {
        title: '原因',
        dataIndex: 'reason',
        key: 'reason'
      },
      {
        title: '处理方式',
        dataIndex: 'processingMethod',
        key: 'processingMethod'
      },
      {
        title: '处理场所',
        dataIndex: 'processingPlace',
        key: 'processingPlace'
      },
      {
        title: '处理日期',
        dataIndex: 'processingDate',
        key: 'processingDate'
      },
      {
        title: '登记人',
        dataIndex: 'registrant',
        key: 'registrant'
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        slots: { customRender: 'status' }
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime'
      },
      {
        title: '操作',
        key: 'action',
        slots: { customRender: 'action' }
      }
    ]
    
    // 根据状态获取标签颜色
    const getStatusColor = (status) => {
      const colorMap = {
        '待处理': 'orange',
        '处理中': 'blue',
        '已完成': 'green',
        '已取消': 'red'
      }
      return colorMap[status] || 'default'
    }
    
    // 获取无害化登记列表
    const fetchHarmlessRegistrations = async () => {
      loading.value = true
      try {
        const params = {
          page: pagination.current,
          pageSize: pagination.pageSize,
          keyword: searchKeyword.value,
          startDate: dateRange.value[0] ? dateRange.value[0].format('YYYY-MM-DD') : '',
          endDate: dateRange.value[1] ? dateRange.value[1].format('YYYY-MM-DD') : ''
        }
        const response = await api.harmlessRegistration.getList(params)
        if (response && response.data) {
          harmlessRegistrations.value = response.data.list || []
          pagination.total = response.data.total || 0
        } else {
          harmlessRegistrations.value = []
          pagination.total = 0
        }
      } catch (error) {
        message.error('获取无害化登记列表失败')
        console.error('获取无害化登记列表失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 处理搜索
    const handleSearch = async () => {
      pagination.current = 1
      await fetchHarmlessRegistrations()
    }
    
    // 处理日期范围变化
    const handleDateChange = async (dates) => {
      dateRange.value = dates
      pagination.current = 1
      await fetchHarmlessRegistrations()
    }
    
    // 处理表格变化
    const handleTableChange = async (paginationConfig) => {
      Object.assign(pagination, paginationConfig)
      await fetchHarmlessRegistrations()
    }
    
    // 处理新增
    const handleAdd = () => {
      // 重置表单
      Object.assign(formData, {
        id: '',
        registrationNumber: '',
        animalType: '',
        quantity: 1,
        reason: '',
        processingMethod: '',
        processingPlace: '',
        processingDate: null,
        registrant: '',
        status: '待处理'
      })
      if (formRef.value) {
        formRef.value.resetFields()
      }
      isModalOpen.value = true
    }
    
    // 处理编辑
    const handleEdit = async (record) => {
      try {
        const response = await api.harmlessRegistration.getDetail(record.id)
        if (response && response.data) {
          // 转换日期格式
          const data = { ...response.data }
          if (data.processingDate) {
            data.processingDate = new Date(data.processingDate)
          }
          Object.assign(formData, data)
          isModalOpen.value = true
        }
      } catch (error) {
        message.error('获取无害化登记详情失败')
        console.error('获取无害化登记详情失败:', error)
      }
    }
    
    // 处理删除
    const handleDelete = async (id) => {
      try {
        const response = await api.harmlessRegistration.delete(id)
        if (response && response.code === 200) {
          message.success('删除成功')
          await fetchHarmlessRegistrations()
        }
      } catch (error) {
        message.error('删除失败')
        console.error('删除失败:', error)
      }
    }
    
    // 处理查看详情
    const handleDetail = async (record) => {
      try {
        const response = await api.harmlessRegistration.getDetail(record.id)
        if (response && response.data) {
          Object.assign(detailData, response.data)
          isDetailModalOpen.value = true
        }
      } catch (error) {
        message.error('获取无害化登记详情失败')
        console.error('获取无害化登记详情失败:', error)
      }
    }
    
    // 表单提交
    const handleOk = async () => {
      if (!formRef.value) return
      try {
        await formRef.value.validate()
        // 格式化日期
        const submitData = { ...formData }
        if (submitData.processingDate) {
          submitData.processingDate = submitData.processingDate.format('YYYY-MM-DD')
        }
        
        let response
        if (submitData.id) {
          // 更新
          response = await api.harmlessRegistration.update(submitData.id, submitData)
        } else {
          // 新增
          response = await api.harmlessRegistration.create(submitData)
        }
        if (response && response.code === 200) {
          message.success(submitData.id ? '更新成功' : '新增成功')
          isModalOpen.value = false
          await fetchHarmlessRegistrations()
        }
      } catch (error) {
        if (error && error.errors && error.errors.length > 0) {
          message.error(error.errors[0].message)
        } else if (error && error.message) {
          message.error(error.message)
        } else {
          message.error(formData.id ? '更新失败' : '新增失败')
        }
        console.error(formData.id ? '更新失败:' : '新增失败:', error)
      }
    }
    
    // 取消表单
    const handleCancel = () => {
      isModalOpen.value = false
      if (formRef.value) {
        formRef.value.resetFields()
      }
    }
    
    // 取消详情
    const handleDetailCancel = () => {
      isDetailModalOpen.value = false
    }
    
    // 组件挂载时获取数据
    onMounted(async () => {
      await fetchHarmlessRegistrations()
    })
    
    return {
      harmlessRegistrations,
      loading,
      searchKeyword,
      dateRange,
      pagination,
      isModalOpen,
      isDetailModalOpen,
      formRef,
      formData,
      detailData,
      formRules,
      columns,
      getStatusColor,
      handleSearch,
      handleDateChange,
      handleTableChange,
      handleAdd,
      handleEdit,
      handleDelete,
      handleDetail,
      handleOk,
      handleCancel,
      handleDetailCancel
    }
  }
}
</script>

<style scoped>
.harmless-registration-container {
  padding: 24px;
  background: #fff;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
}

.toolbar {
  margin-bottom: 16px;
}

.content-wrapper {
  background: #fff;
  padding: 24px;
  border-radius: 2px;
}
</style>