<template>
  <div class="epidemic-agency-container">
    <div class="header">
      <h1>防疫机构管理</h1>
    </div>
    
    <!-- 搜索和操作栏 -->
    <div class="filter-section">
      <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="center">防疫中心</a-select-option>
          <a-select-option value="station">防疫站</a-select-option>
          <a-select-option value="clinic">诊疗所</a-select-option>
        </a-select>
        
        <a-select v-model:value="levelFilter" placeholder="机构级别" style="width: 120px;">
          <a-select-option value="">全部</a-select-option>
          <a-select-option value="provincial">省级</a-select-option>
          <a-select-option value="municipal">市级</a-select-option>
          <a-select-option value="county">县级</a-select-option>
          <a-select-option value="township">乡镇级</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="handleAdd">
          <span class="iconfont icon-tianjia"></span> 新增机构
        </a-button>
      </div>
    </div>
    
    <!-- 机构列表 -->
    <div class="table-card">
      <a-table
        :columns="columns"
        :data-source="agenciesData"
        :pagination="pagination"
        row-key="id"
        :row-selection="{ selectedRowKeys, onChange: onSelectChange }"
        :scroll="{ x: 'max-content' }"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <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>
        </template>
      </a-table>
    </div>
    
    <!-- 新增/编辑机构模态框 -->
    <a-modal
      v-model:open="isAddEditModalOpen"
      :title="isEdit ? '编辑防疫机构' : '新增防疫机构'"
      :footer="null"
      width="600px"
      class="custom-modal"
    >
      <a-form
        :model="currentAgency"
        layout="vertical"
        ref="formRef"
      >
        <a-form-item label="机构名称" name="name" :rules="[{ required: true, message: '请输入机构名称' }]">
          <a-input v-model:value="currentAgency.name" placeholder="请输入机构名称" />
        </a-form-item>
        
        <!-- <a-form-item label="机构编号" name="code" :rules="[{ required: true, message: '请输入机构编号' }]">
          <a-input v-model:value="currentAgency.code" placeholder="请输入机构编号" />
        </a-form-item> -->
        
        <a-form-item label="机构类型" name="type" :rules="[{ required: true, message: '请选择机构类型' }]">
          <a-select v-model:value="currentAgency.type" placeholder="请选择机构类型">
            <a-select-option value="center">防疫中心</a-select-option>
            <a-select-option value="station">防疫站</a-select-option>
            <a-select-option value="clinic">诊疗所</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="机构级别" name="level" :rules="[{ required: true, message: '请选择机构级别' }]">
          <a-select v-model:value="currentAgency.level" placeholder="请选择机构级别">
            <a-select-option value="provincial">省级</a-select-option>
            <a-select-option value="municipal">市级</a-select-option>
            <a-select-option value="county">县级</a-select-option>
            <a-select-option value="township">乡镇级</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="负责人" name="manager" :rules="[{ required: true, message: '请输入负责人姓名' }]">
          <a-input v-model:value="currentAgency.manager" placeholder="请输入负责人姓名" />
        </a-form-item>

        <a-form-item label="邮箱" name="email" :rules="[{ required: false, message: '请输入邮箱地址' }]">
          <a-input v-model:value="currentAgency.email" placeholder="请输入邮箱地址" />
        </a-form-item>

        <a-form-item label="状态" name="status" :rules="[{ required: true, message: '请选择状态' }]">
          <a-select v-model:value="currentAgency.status" placeholder="请选择状态">
            <a-select-option value="active">活跃</a-select-option>
            <a-select-option value="inactive">非活跃</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="联系电话" name="phone" :rules="[{ required: true, message: '请输入联系电话' }]">
          <a-input v-model:value="currentAgency.phone" placeholder="请输入联系电话" />
        </a-form-item>
        
        <a-form-item label="成立时间" name="establishmentDate" :rules="[{ required: true, message: '请选择成立时间' }]">
          <a-input v-model:value="currentAgency.establishmentDate" type="date" placeholder="请选择成立时间" />
        </a-form-item>
        
        <a-form-item label="地址" name="address" :rules="[{ required: true, message: '请输入机构地址' }]">
          <textarea v-model="currentAgency.address" placeholder="请输入机构地址" rows="3" style="width: 100%; padding: 8px; border: 1px solid #d9d9d9; border-radius: 2px; resize: vertical;"></textarea>
        </a-form-item>
        
        <a-form-item label="防疫范围" name="epidemicScope" :rules="[{ required: true, message: '请输入防疫范围' }]">
          <textarea v-model="currentAgency.epidemicScope" placeholder="请输入防疫范围" rows="3" style="width: 100%; padding: 8px; border: 1px solid #d9d9d9; border-radius: 2px; resize: vertical;"></textarea>
        </a-form-item>
        
        <a-form-item label="备注" name="remarks" :rules="[]">
          <textarea v-model="currentAgency.remarks" placeholder="请输入备注信息" rows="2" style="width: 100%; padding: 8px; border: 1px solid #d9d9d9; border-radius: 2px; resize: vertical;"></textarea>
        </a-form-item>
        
        <div style="text-align: right;">
          <a-button @click="isAddEditModalOpen = false" style="margin-right: 16px;">取消</a-button>
          <a-button type="primary" @click="handleSave">保存</a-button>
        </div>
      </a-form>
    </a-modal>
    
    <!-- 查看机构详情模态框 -->
    <a-modal
      v-model:open="isViewModalOpen"
      title="查看防疫机构详情"
      :footer="null"
      class="custom-modal"
    >
      <div v-if="viewAgency">
        <div style="margin-bottom: 16px;">
          <span style="font-weight: bold; width: 120px; display: inline-block;">机构名称：</span>
          <span>{{ viewAgency.name }}</span>
        </div>
        <div style="margin-bottom: 16px;">
          <span style="font-weight: bold; width: 120px; display: inline-block;">机构编号：</span>
          <span>{{ viewAgency.code }}</span>
        </div>
        <div style="margin-bottom: 16px;">
          <span style="font-weight: bold; width: 120px; display: inline-block;">机构类型：</span>
          <span>{{ getTypeText(viewAgency.type) }}</span>
        </div>
        <div style="margin-bottom: 16px;">
          <span style="font-weight: bold; width: 120px; display: inline-block;">机构级别：</span>
          <span>{{ getLevelText(viewAgency.level) }}</span>
        </div>
        <div style="margin-bottom: 16px;">
          <span style="font-weight: bold; width: 120px; display: inline-block;">负责人：</span>
          <span>{{ viewAgency.manager }}</span>
        </div>
        <div style="margin-bottom: 16px;">
          <span style="font-weight: bold; width: 120px; display: inline-block;">联系电话：</span>
          <span>{{ viewAgency.phone }}</span>
        </div>
        <div style="margin-bottom: 16px;">
          <span style="font-weight: bold; width: 120px; display: inline-block;">地址：</span>
          <span>{{ viewAgency.address }}</span>
        </div>
        <div style="margin-bottom: 16px;">
          <span style="font-weight: bold; width: 120px; display: inline-block;">防疫范围：</span>
          <span>{{ viewAgency.epidemicScope }}</span>
        </div>
        <div style="margin-bottom: 16px;">
          <span style="font-weight: bold; width: 120px; display: inline-block;">成立时间：</span>
          <span>{{ viewAgency.establishmentDate }}</span>
        </div>
        <div v-if="viewAgency.remarks">
          <span style="font-weight: bold; width: 120px; display: inline-block;">备注：</span>
          <span>{{ viewAgency.remarks }}</span>
        </div>
        <div style="margin-bottom: 16px;">
          <span style="font-weight: bold; width: 120px; display: inline-block;">邮箱：</span>
          <span>{{ viewAgency.email }}</span>
        </div>
        <div style="margin-bottom: 16px;">
          <span style="font-weight: bold; width: 120px; display: inline-block;">机构描述：</span>
          <span>{{ viewAgency.description }}</span>
        </div>
        <div style="margin-bottom: 16px;">
          <span style="font-weight: bold; width: 120px; display: inline-block;">状态：</span>
          <span>{{ viewAgency.status === 'active' ? '活跃' : '非活跃' }}</span>
        </div>
      </div>
      <div style="text-align: right; margin-top: 24px;">
        <a-button @click="isViewModalOpen = false">关闭</a-button>
      </div>
    </a-modal>
  </div>
</template>

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

// 搜索条件
const searchKeyword = ref('')
const typeFilter = ref('')
const levelFilter = ref('')

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

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

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

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

// 测试 TextArea 的变量
const testValue1 = ref('')
const testValue2 = ref('')

// 当前编辑/新增的机构
const currentAgency = reactive({
  name: '',
  code: '',
  type: 'station',
  level: 'county',
  manager: '',
  phone: '',
  address: '',
  epidemicScope: '',
  remarks: '',
  email: '',
  status: 'active',
  establishmentDate: '' // 添加成立时间字段
})

// 当前查看的机构
const viewAgency = ref(null)

// 机构列表数据
const agenciesData = ref([
  {
    id: '1',
    name: '银川市动物防疫中心',
    code: 'YCCE-001',
    type: 'center',
    level: 'city',
    manager: '张明',
    phone: '13800138001',
    address: '银川市金凤区黄河东路123号',
    epidemicScope: '银川市全域',
    establishmentDate: '2010-01-01',
    email: 'yc@example.com',
    description: '负责银川市动物防疫工作',
    status: 'active'
  },
  {
    id: '2',
    name: '金凤区防疫站',
    code: 'JFJY-001',
    type: 'station',
    level: 'district',
    manager: '李华',
    phone: '13800138002',
    address: '银川市金凤区北京中路45号',
    epidemicScope: '金凤区',
    establishmentDate: '2012-03-15',
    email: 'jf@example.com',
    description: '负责金凤区动物防疫工作',
    status: 'active'
  }
])

// 表格列定义
const columns = [
  {
    title: '机构名称',
    dataIndex: 'name',
    key: 'name',
    width: 200
  },
  {
    title: '机构类型',
    dataIndex: 'type',
    key: 'type'
  },
  {
    title: '负责人',
    dataIndex: 'director',
    key: 'director'
  },
  {
    title: '联系电话',
    dataIndex: 'phone',
    key: 'phone'
  },
  {
    title: '机构地址',
    dataIndex: 'address',
    key: 'address'
  },
  {
    title: '疫情防控范围',
    dataIndex: 'epidemicScope',
    key: 'epidemicScope'
  },
  {
    title: '成立时间',
    dataIndex: 'establishmentDate',
    key: 'establishmentDate'
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email'
  },
  {
    title: '机构描述',
    dataIndex: 'description',
    key: 'description'
  },
  { title: '状态', dataIndex: 'status', key: 'status', width: 80, customRender: ({ text }) => {
    return text === 'active' ? '活跃' : '非活跃'
  }},
  { title: '操作', key: 'action', width: 150, fixed: 'right' }
]

// 获取机构类型文本
const getTypeText = (type) => {
  const typeMap = {
    'center': '防疫中心',
    'station': '防疫站',
    'clinic': '诊疗所'
  }
  return typeMap[type] || type
}

// 获取机构级别文本
const getLevelText = (level) => {
  const levelMap = {
    'provincial': '省级',
    'municipal': '市级',
    'county': '县级',
    'township': '乡镇级'
  }
  return levelMap[level] || level
}

// 获取机构列表数据
const getAgenciesList = async () => {
  try {
    // message.info('开始获取机构列表...')
    const response = await api.epidemic.agencies.getList({
      keyword: searchKeyword.value,
      type: typeFilter.value,
      level: levelFilter.value,
      page: pagination.value.current,
      pageSize: pagination.value.pageSize
    })
    
    // 显示API响应信息
    // message.info(`API响应: ${response.success ? '成功' : '失败'}`)
    // if (response.data) {
    //   message.info(`数据长度: ${response.data.list ? response.data.list.length : 0}`)
    //   message.info(`总数: ${response.data.total || 0}`)
    // }
    
    // 判断响应是否成功（后端返回code:200表示成功）
    if (response.code === 200) {
      agenciesData.value = response.data.list || []
      pagination.value.total = response.data.total || 0
      message.success('获取机构列表成功')
    } else {
      message.error(response.message || '获取机构列表失败')
    }
  } catch (error) {
    console.error('获取机构列表失败:', error)
    message.error('获取机构列表失败，请稍后重试')
  }
}

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

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

// 处理表格分页变化
const handleTableChange = (paginationChange) => {
  pagination.value = paginationChange
  getAgenciesList()
}

// 处理新增
const handleAdd = () => {
  isEdit.value = false
  // 重置表单数据
  Object.keys(currentAgency).forEach(key => {
    currentAgency[key] = ''
  })
  currentAgency.type = 'station'
  currentAgency.level = 'county'
  isAddEditModalOpen.value = true
}

// 处理编辑
const handleEdit = (record) => {
  isEdit.value = true
  // 复制记录数据到当前编辑对象
  Object.assign(currentAgency, JSON.parse(JSON.stringify(record)))
  isAddEditModalOpen.value = true
}

// 处理查看
const handleView = async (record) => {
  try {
    const response = await api.epidemic.agencies.getDetail(record.id)
    if (response.success) {
      viewAgency.value = response.data
      isViewModalOpen.value = true
    } else {
      message.error(response.message || '获取机构详情失败')
    }
  } catch (error) {
    console.error('获取机构详情失败:', error)
    message.error('获取机构详情失败，请稍后重试')
  }
}

// 处理删除
const handleDelete = async (id) => {
  // 显示确认对话框
  if (confirm('确定要删除该防疫机构吗？')) {
    try {
      const response = await api.epidemic.agencies.delete(id)
      if (response.success) {
        message.success('删除成功')
        getAgenciesList()
      } else {
        message.error(response.message || '删除失败')
      }
    } catch (error) {
      console.error('删除机构失败:', error)
      message.error('删除机构失败，请稍后重试')
    }
  }
}

// 处理保存
const handleSave = async () => {
  if (formRef.value) {
    formRef.value.validate().then(async () => {
      try {
        let response
        // 创建提交数据对象，进行字段映射
        const submitData = {
          ...currentAgency,
          director: currentAgency.manager, // 将manager映射为director
          establishmentDate: currentAgency.establishmentDate || new Date().toISOString().split('T')[0] // 确保有成立时间
        }
        
        if (isEdit.value) {
          // 编辑现有记录
          response = await api.epidemic.agencies.update(currentAgency.id, submitData)
        } else {
          // 新增记录
          response = await api.epidemic.agencies.create(submitData)
        }
        if (response.success) {
          isAddEditModalOpen.value = false
          message.success(isEdit.value ? '编辑成功' : '新增成功')
          getAgenciesList()
        } else {
          message.error(response.message || (isEdit.value ? '编辑失败' : '新增失败'))
        }
      } catch (error) {
        console.error('保存机构信息失败:', error)
        message.error('保存失败，请稍后重试')
      }
    }).catch(errorInfo => {
      console.log('表单验证失败:', errorInfo)
    })
  }
}

// 组件挂载时初始化
onMounted(() => {
  getAgenciesList()
})
</script>

<style scoped>
/* 容器样式 */
.epidemic-agency-container {
  padding: 24px;
  /* background-color: #f0f2f5; */
  min-height: 100vh;
}

/* 页面标题 */
.header {
  margin-bottom: 16px;
}

.header h1 {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 0;
}

/* 过滤器和搜索区域样式 */
.filter-section {
  margin-bottom: 16px;
  background-color: #fff;
  padding: 16px;
  border-radius: 6px;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03);
}

/* 表格卡片样式 */
.table-card {
  background-color: #fff;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03);
  padding: 16px;
}

/* 表格样式优化 */
.custom-table {
  border-radius: 6px;
  overflow: hidden;
}

.custom-table .ant-table-thead > tr > th {
  background-color: #fafafa;
  font-weight: 600;
  color: #262626;
  border-bottom: 1px solid #f0f0f0;
}

.custom-table .ant-table-tbody > tr:hover > td {
  background-color: #f5f5f5;
}

/* 表格单元格样式 */
.table-cell {
  padding: 12px 16px;
}

/* 操作按钮组样式 */
.action-group {
  display: flex;
  gap: 8px;
}

/* 弹窗样式优化 */
.custom-modal .ant-modal-header {
  background-color: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

.custom-modal .ant-modal-title {
  font-size: 18px;
  font-weight: 600;
  color: #262626;
}

.custom-modal .ant-modal-footer {
  border-top: 1px solid #f0f0f0;
}

/* 表单样式优化 */
.custom-form .ant-form-item {
  margin-bottom: 16px;
}

.custom-form .ant-form-item-label {
  font-weight: 500;
  color: #595959;
}
</style>