<template>
  <div class="pen-management-container">
    <!-- 页面标题和操作栏 -->
    <div class="page-header">
      <h2 class="page-title">栏舍设置</h2>
      <div class="header-actions">
        <a-button @click="exportData" class="add-button">
          <template #icon>
            <ExportOutlined />
          </template>
          导出数据
        </a-button>
        <a-button type="primary" @click="showAddModal" class="add-button">
          <template #icon>
            <PlusOutlined />
          </template>
          新增栏舍
        </a-button>
        <div class="search-container">
          <a-input
            v-model="searchKeyword"
            placeholder="请输入栏舍名、类型、负责人等关键词"
            class="search-input"
            @pressEnter="handleSearch"
            @input="(e) => { console.log('搜索输入框输入:', e.target.value); searchKeyword = e.target.value; }"
            @change="(e) => { console.log('搜索输入框变化:', e.target.value); searchKeyword = e.target.value; }"
            allowClear
          />
          <a-button type="primary" @click="handleSearch" class="search-button">
            <template #icon>
              <SearchOutlined />
            </template>
            搜索
          </a-button>
          <a-button @click="handleClearSearch" class="clear-button">
            清空
          </a-button>
        </div>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
   
      <a-table
        :columns="columns"
        :data-source="filteredData"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        class="pen-table"
      >
        <!-- 状态列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-switch
              :checked="record.status"
              @change="(checked) => { record.status = checked; handleStatusChange(record) }"
              :checked-children="'开启'"
              :un-checked-children="'关闭'"
            />
          </template>
          <!-- 操作列 -->
          <template v-else-if="column.key === 'actions'">
            <a-space>
              <a-button type="link" @click="handleEdit(record)" class="action-btn">
                编辑
              </a-button>
              <a-button type="link" danger @click="handleDelete(record)" class="action-btn">
                删除
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 新增/编辑栏舍模态框 -->
    <a-modal
      :open="modalVisible"
      @update:open="(val) => modalVisible = val"
      :title="isEdit ? '编辑栏舍' : '新增栏舍'"
      @ok="handleSubmit"
      @cancel="handleCancel"
      :confirm-loading="submitting"
      width="600px"
    >
      <a-form
        :model="formData"
        :rules="formRules"
        ref="formRef"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="栏舍名" name="name" required>
              <a-input 
                v-model:value="formData.name" 
                placeholder="请输入栏舍名"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="动物类型" name="animal_type" required>
              <a-select 
                v-model:value="formData.animal_type" 
                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="pen_type">
              <a-input 
                v-model:value="formData.pen_type" 
                placeholder="请输入栏舍类型"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="负责人" name="responsible" required>
              <a-input 
                v-model:value="formData.responsible" 
                placeholder="请输入负责人"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="容量" name="capacity" required>
              <a-input-number
                v-model:value="formData.capacity"
                :min="1"
                :max="10000"
                placeholder="请输入容量"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="状态" name="status">
              <a-switch
                v-model:checked="formData.status"
                :checked-children="'开启'"
                :un-checked-children="'关闭'"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="备注" name="description">
          <a-textarea
            v-model:value="formData.description"
            placeholder="请输入备注信息"
            :rows="3"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { PlusOutlined, SearchOutlined, ExportOutlined } from '@ant-design/icons-vue'
import { api } from '../utils/api'
import { ExportUtils } from '../utils/exportUtils'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const modalVisible = ref(false)
const isEdit = ref(false)
const searchKeyword = ref('')
const formRef = ref(null)

// 表格列配置
const columns = [
  {
    title: '栏舍名',
    dataIndex: 'name',
    key: 'name',
    width: 120,
  },
  {
    title: '动物类型',
    dataIndex: 'animal_type',
    key: 'animal_type',
    width: 100,
  },
  {
    title: '栏舍类型',
    dataIndex: 'pen_type',
    key: 'pen_type',
    width: 120,
  },
  {
    title: '负责人',
    dataIndex: 'responsible',
    key: 'responsible',
    width: 100,
  },
  {
    title: '容量',
    dataIndex: 'capacity',
    key: 'capacity',
    width: 80,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '创建人',
    dataIndex: 'creator',
    key: 'creator',
    width: 100,
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 150,
  },
  {
    title: '操作',
    key: 'actions',
    width: 120,
    fixed: 'right',
  },
]

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
  onChange: async (page, pageSize) => {
    pagination.current = page
    pagination.pageSize = pageSize
    await loadPenData()
  },
  onShowSizeChange: async (current, size) => {
    pagination.current = 1
    pagination.pageSize = size
    await loadPenData()
  }
})

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  animal_type: '',
  pen_type: '',
  responsible: '',
  capacity: 1,
  status: true,
  description: '',
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入栏舍名', trigger: 'blur' },
    { min: 1, max: 50, message: '栏舍名长度应在1-50个字符之间', trigger: 'blur' }
  ],
  animal_type: [
    { required: true, message: '请选择动物类型', trigger: 'change' }
  ],
  responsible: [
    { required: true, message: '请输入负责人', trigger: 'blur' },
    { min: 1, max: 20, message: '负责人姓名长度应在1-20个字符之间', trigger: 'blur' }
  ],
  capacity: [
    { required: true, message: '请输入容量', trigger: 'blur' },
    { type: 'number', min: 1, max: 10000, message: '容量应在1-10000之间', trigger: 'blur' }
  ]
}

// 真实数据
const penData = ref([])

// 计算属性 - 过滤后的数据（暂时不使用前端过滤，使用API搜索）
const filteredData = computed(() => {
  return penData.value
})

// 数据加载方法
const loadPenData = async () => {
  try {
    loading.value = true
    console.log('开始加载栏舍数据...', {
      page: pagination.current,
      pageSize: pagination.pageSize,
      search: searchKeyword.value
    })
    
    const requestParams = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      search: searchKeyword.value
    }
    
    console.log('请求参数:', requestParams)
    console.log('搜索参数详情:', {
      search: searchKeyword.value,
      searchType: typeof searchKeyword.value,
      searchEmpty: !searchKeyword.value,
      searchTrimmed: searchKeyword.value?.trim()
    })
    
    const response = await api.pens.getList(requestParams)
    
    console.log('API响应:', response)
    
    if (response && response.success) {
      penData.value = response.data.list
      pagination.total = response.data.pagination.total
      console.log('栏舍数据加载成功:', penData.value)
    } else {
      console.error('API返回失败:', response)
      message.error('获取栏舍数据失败')
    }
  } catch (error) {
    console.error('加载栏舍数据失败:', error)
    message.error('加载栏舍数据失败')
  } finally {
    loading.value = false
  }
}

// 方法
const showAddModal = () => {
  isEdit.value = false
  resetForm()
  modalVisible.value = true
}

const handleEdit = async (record) => {
  console.log('=== 开始编辑栏舍 ===')
  console.log('点击编辑按钮，原始记录数据:', record)
  
  isEdit.value = true
  
  // 填充表单数据 - 使用直接赋值确保响应式更新
  formData.id = record.id || null
  formData.name = record.name || ''
  formData.animal_type = record.animal_type || ''
  formData.pen_type = record.pen_type || ''
  formData.responsible = record.responsible || ''
  formData.capacity = record.capacity || 0
  formData.status = record.status || false
  formData.description = record.description || ''
  
  console.log('编辑模式：表单数据已填充')
  console.log('formData对象:', formData)
  console.log('formData.name:', formData.name)
  console.log('formData.animal_type:', formData.animal_type)
  console.log('formData.pen_type:', formData.pen_type)
  console.log('formData.responsible:', formData.responsible)
  console.log('formData.capacity:', formData.capacity)
  console.log('formData.status:', formData.status)
  console.log('formData.description:', formData.description)
  
  // 打开模态框
  modalVisible.value = true
  
  // 等待模态框和表单渲染完成
  await nextTick()
  await new Promise(resolve => setTimeout(resolve, 200))
  
  console.log('编辑模态框已打开，表单应该已填充')
}

const handleDelete = (record) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除栏舍"${record.name}"吗？`,
    onOk: async () => {
      try {
        const response = await api.pens.delete(record.id)
        if (response.success) {
          message.success('删除成功')
          await loadPenData() // 重新加载数据
        } else {
          message.error('删除失败')
        }
      } catch (error) {
        console.error('删除栏舍失败:', error)
        message.error('删除失败')
      }
    }
  })
}

const handleStatusChange = async (record) => {
  try {
    const response = await api.pens.update(record.id, { status: record.status })
    if (response.success) {
      message.success(`栏舍"${record.name}"状态已${record.status ? '开启' : '关闭'}`)
    } else {
      message.error('状态更新失败')
      // 恢复原状态
      record.status = !record.status
    }
  } catch (error) {
    console.error('更新状态失败:', error)
    message.error('状态更新失败')
    // 恢复原状态
    record.status = !record.status
  }
}

const handleSearch = async () => {
  console.log('=== 开始搜索栏舍 ===')
  console.log('搜索关键词:', searchKeyword.value)
  console.log('搜索关键词类型:', typeof searchKeyword.value)
  console.log('搜索关键词长度:', searchKeyword.value?.length)
  console.log('搜索关键词是否为空:', !searchKeyword.value)
  console.log('搜索关键词去除空格后:', searchKeyword.value?.trim())
  
  // 确保搜索关键词正确传递
  const searchValue = searchKeyword.value?.trim() || ''
  console.log('实际使用的搜索值:', searchValue)
  
  pagination.current = 1 // 重置到第一页
  await loadPenData()
  
  console.log('=== 搜索完成 ===')
}

const handleClearSearch = async () => {
  console.log('=== 清空搜索 ===')
  searchKeyword.value = ''
  pagination.current = 1 // 重置到第一页
  await loadPenData()
  console.log('=== 搜索已清空 ===')
}

const handleSubmit = async () => {
  try {
    console.log('=== 开始提交栏舍数据 ===')
    console.log('当前表单数据:', formData)
    console.log('是否为编辑模式:', isEdit.value)
    
    await formRef.value.validate()
    submitting.value = true
    
    const submitData = {
      name: formData.name,
      animal_type: formData.animal_type,
      pen_type: formData.pen_type,
      responsible: formData.responsible,
      capacity: formData.capacity,
      status: formData.status,
      description: formData.description
    }
    
    console.log('准备提交的数据:', submitData)
    console.log('提交的字段详情:')
    console.log('- 栏舍名 (name):', submitData.name)
    console.log('- 动物类型 (animal_type):', submitData.animal_type)
    console.log('- 栏舍类型 (pen_type):', submitData.pen_type)
    console.log('- 负责人 (responsible):', submitData.responsible)
    console.log('- 容量 (capacity):', submitData.capacity, typeof submitData.capacity)
    console.log('- 状态 (status):', submitData.status, typeof submitData.status)
    console.log('- 描述 (description):', submitData.description)
    
    let response
    if (isEdit.value) {
      // 编辑
      console.log('执行编辑操作，栏舍ID:', formData.id)
      response = await api.pens.update(formData.id, submitData)
      console.log('编辑API响应:', response)
    } else {
      // 新增
      console.log('执行新增操作')
      response = await api.pens.create(submitData)
      console.log('新增API响应:', response)
    }
    
    if (response.success) {
      console.log('✅ 操作成功:', response.message)
      console.log('返回的数据:', response.data)
      message.success(isEdit.value ? '编辑成功' : '新增成功')
      modalVisible.value = false
      await loadPenData() // 重新加载数据
      console.log('数据已重新加载')
    } else {
      console.log('❌ 操作失败:', response.message)
      message.error(isEdit.value ? '编辑失败' : '新增失败')
    }
  } catch (error) {
    console.error('❌ 提交失败:', error)
    console.error('错误详情:', error.response?.data || error.message)
    message.error('操作失败')
  } finally {
    submitting.value = false
    console.log('=== 提交操作完成 ===')
  }
}

const handleCancel = () => {
  modalVisible.value = false
  resetForm()
}

const resetForm = () => {
  Object.assign(formData, {
    id: null,
    name: '',
    animal_type: '',
    pen_type: '',
    responsible: '',
    capacity: 1,
    status: true,
    description: '',
  })
  formRef.value?.resetFields()
}

// 生命周期
onMounted(async () => {
  console.log('PenManagement组件已挂载')
  // 初始化数据
  await loadPenData()
})

// 导出数据
const exportData = async () => {
  try {
    if (!penData.value || penData.value.length === 0) {
      message.warning('没有数据可导出')
      return
    }
    
    message.loading('正在导出数据...', 0)
    
    const result = ExportUtils.exportPenData(penData.value)
    
    if (result.success) {
      message.destroy()
      message.success(`导出成功！文件：${result.filename}`)
    } else {
      message.destroy()
      message.error(result.message)
    }
  } catch (error) {
    message.destroy()
    console.error('导出失败:', error)
    message.error('导出失败，请重试')
  }
}
</script>

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

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #262626;
  margin: 0;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.add-button {
  height: 40px;
  font-size: 14px;
  font-weight: 500;
}

.search-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-input {
  width: 300px;
  height: 40px;
}

.search-button {
  height: 40px;
}

.clear-button {
  height: 40px;
  color: #666;
  border-color: #d9d9d9;
}

.clear-button:hover {
  color: #1890ff;
  border-color: #1890ff;
}

.table-container {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.pen-table {
  font-size: 14px;
}

.action-btn {
  padding: 4px 8px;
  height: auto;
  font-size: 14px;
}

.action-btn:hover {
  background: #f5f5f5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .search-container {
    flex: 1;
  }
  
  .search-input {
    width: 100%;
  }
}

/* 表格样式优化 */
:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
  color: #262626;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background: #f5f5f5;
}

:deep(.ant-table-tbody > tr > td) {
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
}

/* 状态开关样式 */
:deep(.ant-switch-checked) {
  background-color: #1890ff;
}

/* 表单样式 */
:deep(.ant-form-item-label > label) {
  font-weight: 500;
  color: #262626;
}

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

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