<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="materialTypeFilter" placeholder="生产资料类型" style="width: 150px;">
          <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="certificationTypeFilter" placeholder="认证类型" style="width: 150px;">
          <a-select-option value="">全部</a-select-option>
          <a-select-option value="兽药GMP认证">兽药GMP认证</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="valid">有效</a-select-option>
          <a-select-option value="expired">过期</a-select-option>
          <a-select-option value="suspended">暂停</a-select-option>
          <a-select-option value="revoked">撤销</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="handleAddCertification">
          <span class="iconfont icon-tianjia"></span> 新增认证
        </a-button>
      </div>
    </a-card>
    
    <!-- 数据列表 -->
    <a-card>
      <a-table
        :columns="columns"
        :data-source="certificationsData"
        row-key="id"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'certificationStatus'">
            <div style="display: flex; align-items: center; gap: 8px;">
              <a-switch 
                :checked="record.certificationStatus === 'valid'"
                size="small"
                @change="(checked) => handleToggleStatus(record, checked)"
              />
              <span>{{ getStatusText(record.certificationStatus) }}</span>
            </div>
          </template>
          <template v-else-if="column.key === 'action'">
            <div style="display: flex; gap: 8px;">
              <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="handleDetail(record)">详情</a-button>
            </div>
          </template>
        </template>
      </a-table>
    </a-card>
    
    <!-- 新增/编辑表单 -->
    <a-modal
      v-model:open="isModalOpen"
      :title="currentCertification.id ? '编辑生资认证' : '新增生资认证'"
      @ok="handleSave"
      @cancel="handleCancel"
      :width="600"
      :confirm-loading="modalLoading"
    >
      <a-form
        :model="currentCertification"
        layout="vertical"
        :rules="formRules"
        ref="formRef"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="生产资料名称" name="materialName">
              <a-input v-model:value="currentCertification.materialName" placeholder="请输入生产资料名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="生产资料类型" name="materialType">
              <a-select v-model:value="currentCertification.materialType" 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-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="生产厂商" name="manufacturer">
              <a-input v-model:value="currentCertification.manufacturer" placeholder="请输入生产厂商" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="认证编号" name="certificationNumber">
              <a-input v-model:value="currentCertification.certificationNumber" placeholder="请输入认证编号" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="认证类型" name="certificationType">
              <a-select v-model:value="currentCertification.certificationType" placeholder="请选择认证类型">
                <a-select-option value="兽药GMP认证">兽药GMP认证</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-col>
          <a-col :span="12">
            <a-form-item label="认证机构" name="certificationAuthority">
              <a-input v-model:value="currentCertification.certificationAuthority" placeholder="请输入认证机构" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="发证日期" name="issueDate">
              <a-date-picker v-model:value="currentCertification.issueDate" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="有效期至" name="expiryDate">
              <a-date-picker v-model:value="currentCertification.expiryDate" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="产品描述" name="description">
          <a-textarea v-model:value="currentCertification.description" placeholder="请输入产品描述" :rows="3" />
        </a-form-item>
        
        <a-form-item label="技术规格" name="specifications">
          <a-textarea v-model:value="currentCertification.specifications" placeholder="请输入技术规格" :rows="2" />
        </a-form-item>
        
        <a-form-item label="适用范围" name="applicableScope">
          <a-textarea v-model:value="currentCertification.applicableScope" placeholder="请输入适用范围" :rows="2" />
        </a-form-item>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="联系人" name="contactPerson">
              <a-input v-model:value="currentCertification.contactPerson" placeholder="请输入联系人" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="联系电话" name="contactPhone">
              <a-input v-model:value="currentCertification.contactPhone" placeholder="请输入联系电话" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="备注" name="remarks">
          <a-textarea v-model:value="currentCertification.remarks" placeholder="请输入备注" :rows="2" />
        </a-form-item>
      </a-form>
    </a-modal>
    
    <!-- 详情查看 -->
    <a-modal
      v-model:open="isDetailModalOpen"
      title="生资认证详情"
      :footer="null"
      :width="600"
    >
      <a-descriptions :column="2" bordered>
        <a-descriptions-item label="生产资料名称">{{ detailData.materialName }}</a-descriptions-item>
        <a-descriptions-item label="生产资料类型">{{ detailData.materialType }}</a-descriptions-item>
        <a-descriptions-item label="生产厂商">{{ detailData.manufacturer }}</a-descriptions-item>
        <a-descriptions-item label="认证编号">{{ detailData.certificationNumber }}</a-descriptions-item>
        <a-descriptions-item label="认证类型">{{ detailData.certificationType }}</a-descriptions-item>
        <a-descriptions-item label="认证机构">{{ detailData.certificationAuthority }}</a-descriptions-item>
        <a-descriptions-item label="发证日期">{{ detailData.issueDate }}</a-descriptions-item>
        <a-descriptions-item label="有效期至">{{ detailData.expiryDate }}</a-descriptions-item>
        <a-descriptions-item label="认证状态">
          <a-tag :color="getStatusColor(detailData.certificationStatus)">
            {{ getStatusText(detailData.certificationStatus) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="联系人">{{ detailData.contactPerson }}</a-descriptions-item>
        <a-descriptions-item label="联系电话">{{ detailData.contactPhone }}</a-descriptions-item>
        <a-descriptions-item label="产品描述" :span="2">{{ detailData.description }}</a-descriptions-item>
        <a-descriptions-item label="技术规格" :span="2">{{ detailData.specifications }}</a-descriptions-item>
        <a-descriptions-item label="适用范围" :span="2">{{ detailData.applicableScope }}</a-descriptions-item>
        <a-descriptions-item label="备注" :span="2">{{ detailData.remarks }}</a-descriptions-item>
      </a-descriptions>
    </a-modal>
  </div>
</template>

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

// 搜索条件
const searchKeyword = ref('')
const materialTypeFilter = ref('')
const certificationTypeFilter = ref('')
const statusFilter = ref('')

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

// 模态框状态
const isModalOpen = ref(false)
const isDetailModalOpen = ref(false)
const modalLoading = ref(false)

// 表单引用
const formRef = ref(null)

// 当前编辑的认证
const currentCertification = reactive({
  id: '',
  materialName: '',
  materialType: '',
  manufacturer: '',
  certificationNumber: '',
  certificationType: '',
  certificationAuthority: '',
  issueDate: null,
  expiryDate: null,
  certificationStatus: 'valid',
  description: '',
  specifications: '',
  applicableScope: '',
  contactPerson: '',
  contactPhone: '',
  remarks: ''
})

// 详情数据
const detailData = reactive({})

// 表单验证规则
const formRules = {
  materialName: [
    { required: true, message: '请输入生产资料名称', trigger: 'blur' }
  ],
  materialType: [
    { required: true, message: '请选择生产资料类型', trigger: 'change' }
  ],
  manufacturer: [
    { required: true, message: '请输入生产厂商', trigger: 'blur' }
  ],
  certificationNumber: [
    { required: true, message: '请输入认证编号', trigger: 'blur' }
  ],
  certificationType: [
    { required: true, message: '请选择认证类型', trigger: 'change' }
  ],
  certificationAuthority: [
    { required: true, message: '请输入认证机构', trigger: 'blur' }
  ],
  issueDate: [
    { required: true, message: '请选择发证日期', trigger: 'change' }
  ],
  expiryDate: [
    { required: true, message: '请选择有效期至', trigger: 'change' }
  ]
}

// 认证列表数据
const certificationsData = ref([])
const loading = ref(false)

// 表格列定义
const columns = [
  {
    title: '生产资料名称',
    dataIndex: 'materialName',
    key: 'materialName',
    width: 150
  },
  {
    title: '生产资料类型',
    dataIndex: 'materialType',
    key: 'materialType',
    width: 120
  },
  {
    title: '生产厂商',
    dataIndex: 'manufacturer',
    key: 'manufacturer',
    width: 150
  },
  {
    title: '认证编号',
    dataIndex: 'certificationNumber',
    key: 'certificationNumber',
    width: 120
  },
  {
    title: '认证类型',
    dataIndex: 'certificationType',
    key: 'certificationType',
    width: 120
  },
  {
    title: '认证机构',
    dataIndex: 'certificationAuthority',
    key: 'certificationAuthority',
    width: 150
  },
  {
    title: '发证日期',
    dataIndex: 'issueDate',
    key: 'issueDate',
    width: 100
  },
  {
    title: '有效期至',
    dataIndex: 'expiryDate',
    key: 'expiryDate',
    width: 100
  },
  {
    title: '认证状态',
    dataIndex: 'certificationStatus',
    key: 'certificationStatus',
    width: 100
  },
  {
    title: '更新时间',
    dataIndex: 'updatedAt',
    key: 'updatedAt',
    width: 150
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right'
  }
]

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'valid': '有效',
    'expired': '过期',
    'suspended': '暂停',
    'revoked': '撤销'
  }
  return statusMap[status] || status
}

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

// 获取认证列表
const fetchCertifications = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      materialName: searchKeyword.value,
      materialType: materialTypeFilter.value,
      certificationType: certificationTypeFilter.value,
      certificationStatus: statusFilter.value
    }
    
    const response = await productionMaterialCertificationApi.getCertifications(params)
    if (response.code === 200) {
      certificationsData.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 handleSearch = () => {
  pagination.current = 1
  fetchCertifications()
}

// 重置
const handleReset = () => {
  searchKeyword.value = ''
  materialTypeFilter.value = ''
  certificationTypeFilter.value = ''
  statusFilter.value = ''
  pagination.current = 1
  fetchCertifications()
}

// 表格变化
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchCertifications()
}

// 新增认证
const handleAddCertification = () => {
  Object.assign(currentCertification, {
    id: '',
    materialName: '',
    materialType: '',
    manufacturer: '',
    certificationNumber: '',
    certificationType: '',
    certificationAuthority: '',
    issueDate: null,
    expiryDate: null,
    certificationStatus: 'valid',
    description: '',
    specifications: '',
    applicableScope: '',
    contactPerson: '',
    contactPhone: '',
    remarks: ''
  })
  isModalOpen.value = true
}

// 编辑认证
const handleEdit = (record) => {
  Object.assign(currentCertification, {
    ...record,
    issueDate: record.issueDate ? dayjs(record.issueDate) : null,
    expiryDate: record.expiryDate ? dayjs(record.expiryDate) : null
  })
  isModalOpen.value = true
}

// 查看详情
const handleDetail = (record) => {
  Object.assign(detailData, record)
  isDetailModalOpen.value = true
}

// 删除认证
const handleDelete = async (id) => {
  try {
    const response = await productionMaterialCertificationApi.deleteCertification(id)
    if (response.code === 200) {
      message.success('删除成功')
      fetchCertifications()
    } else {
      message.error(response.message || '删除失败')
    }
  } catch (error) {
    console.error('删除认证失败:', error)
    message.error('删除失败')
  }
}

// 切换状态
const handleToggleStatus = async (record, checked) => {
  try {
    const status = checked ? 'valid' : 'suspended'
    const response = await productionMaterialCertificationApi.toggleCertificationStatus(record.id, status)
    if (response.code === 200) {
      message.success('状态更新成功')
      fetchCertifications()
    } else {
      message.error(response.message || '状态更新失败')
    }
  } catch (error) {
    console.error('切换状态失败:', error)
    message.error('状态更新失败')
  }
}

// 保存认证
const handleSave = async () => {
  try {
    await formRef.value.validate()
    modalLoading.value = true
    
    const data = {
      ...currentCertification,
      issueDate: currentCertification.issueDate ? currentCertification.issueDate.format('YYYY-MM-DD') : null,
      expiryDate: currentCertification.expiryDate ? currentCertification.expiryDate.format('YYYY-MM-DD') : null
    }
    
    let response
    if (currentCertification.id) {
      response = await productionMaterialCertificationApi.updateCertification(currentCertification.id, data)
    } else {
      response = await productionMaterialCertificationApi.createCertification(data)
    }
    
    if (response.code === 200 || response.code === 201) {
      message.success(currentCertification.id ? '更新成功' : '创建成功')
      isModalOpen.value = false
      fetchCertifications()
    } else {
      message.error(response.message || '保存失败')
    }
  } catch (error) {
    console.error('保存认证失败:', error)
    message.error('保存失败')
  } finally {
    modalLoading.value = false
  }
}

// 取消
const handleCancel = () => {
  isModalOpen.value = false
}

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

<style scoped>
:deep(.ant-modal-content) {
  border-radius: 8px;
}

:deep(.ant-modal-header) {
  border-radius: 8px 8px 0 0;
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.ant-modal-body) {
  padding: 24px;
}

:deep(.ant-form-item-label > label) {
  font-weight: 500;
  color: #262626;
}

:deep(.ant-btn-primary) {
  background-color: #1890ff;
  border-color: #1890ff;
  border-radius: 6px;
}

:deep(.ant-btn-primary:hover) {
  background-color: #40a9ff;
  border-color: #40a9ff;
}

:deep(.ant-btn-dangerous) {
  background-color: #ff4d4f;
  border-color: #ff4d4f;
  border-radius: 6px;
}

:deep(.ant-btn-dangerous:hover) {
  background-color: #ff7875;
  border-color: #ff7875;
}

:deep(.ant-btn) {
  border-radius: 6px;
}

:deep(.ant-input) {
  border-radius: 6px;
}

:deep(.ant-select-selector) {
  border-radius: 6px;
}

:deep(.ant-picker) {
  border-radius: 6px;
}
</style>
