<template>
  <div>
    <div style="display: flex; justify-content: space-between; margin-bottom: 16px;">
      <div>
        <a-button type="primary" @click="handleAddFarmer">新增养殖监管</a-button>
        <a-button style="margin-left: 8px;" @click="handleExport">导出表格</a-button>
      </div>
      <div>
        <a-input-search
          placeholder="请输入账号、姓名、养殖场名称"
          style="width: 200px; margin-right: 8px;"
          v-model:value="searchKeyword"
          @search="handleSearch"
        />
        <a-select
          placeholder="养殖场类型"
          style="width: 120px; margin-right: 8px;"
          v-model:value="farmTypeFilter"
          @change="handleSearch"
        >
          <a-select-option value="">全部</a-select-option>
          <a-select-option v-for="type in farmTypes" :key="type.value" :value="type.value">{{ type.label }}</a-select-option>
        </a-select>
        <a-select
          placeholder="养殖种类"
          style="width: 120px;"
          v-model:value="animalTypeFilter"
          @change="handleSearch"
        >
          <a-select-option value="">全部</a-select-option>
          <a-select-option v-for="type in animalTypes" :key="type.value" :value="type.value">{{ type.label }}</a-select-option>
        </a-select>
      </div>
    </div>
    
    <!-- 养殖户列表 -->
    <a-table
      :columns="columns"
      :data-source="farmersData"
      :pagination="pagination"
      row-key="id"
      :scroll="{ x: 'max-content' }"
      @change="handleTableChange"
      :loading="loading"
    >
        <!-- 状态列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status_value)">{{ record.status }}</a-tag>
          </template>
          <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>
    
    <!-- 新增/编辑养殖户对话框 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form :model="formData" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="账号" name="account" :rules="[{ required: true, message: '请输入账号' }]">
          <a-input v-model:value="formData.account" placeholder="请输入账号" />
        </a-form-item>
        <a-form-item label="账号昵称" name="nickname" :rules="[{ required: true, message: '请输入账号昵称' }]">
          <a-input v-model:value="formData.nickname" placeholder="请输入账号昵称" />
        </a-form-item>
        <a-form-item label="真实姓名" name="real_name" :rules="[{ required: true, message: '请输入真实姓名' }]">
          <a-input v-model:value="formData.real_name" placeholder="请输入真实姓名" />
        </a-form-item>
        <a-form-item label="养殖场名称" name="farm_name" :rules="[{ required: true, message: '请输入养殖场名称' }]">
          <a-input v-model:value="formData.farm_name" placeholder="请输入养殖场名称" />
        </a-form-item>
        <a-form-item label="养殖场类型" name="farm_type" :rules="[{ required: true, message: '请选择养殖场类型' }]">
          <a-select v-model:value="formData.farm_type" placeholder="请选择养殖场类型">
            <a-select-option v-for="type in farmTypes" :key="type.value" :value="type.value">{{ type.label }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="养殖种类" name="animal_type" :rules="[{ required: true, message: '请选择养殖种类' }]">
          <a-select v-model:value="formData.animal_type" placeholder="请选择养殖种类">
            <a-select-option v-for="type in animalTypes" :key="type.value" :value="type.value">{{ type.label }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="养殖数量" name="animal_count" :rules="[{ required: true, message: '请输入养殖数量' }, { type: 'number', min: 0 }]">
          <a-input-number v-model:value="formData.animal_count" :min="0" placeholder="请输入养殖数量" />
        </a-form-item>
        <a-form-item label="养殖场地址" name="address" :rules="[{ required: true, message: '请输入养殖场地址' }]">
          <a-input v-model:value="formData.address" placeholder="请输入养殖场地址" />
        </a-form-item>
        <a-form-item label="状态" name="status" :rules="[{ required: true, message: '请选择状态' }]">
          <a-select v-model:value="formData.status" placeholder="请选择状态">
            <a-select-option value="active">正常</a-select-option>
            <a-select-option value="inactive">暂停</a-select-option>
            <a-select-option value="closed">关闭</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
    
    <!-- 查看详情对话框 -->
    <a-modal
      v-model:visible="viewModalVisible"
      title="养殖户详情"
      @cancel="handleViewCancel"
    >
      <div v-if="selectedFarmer">
        <p><strong>账号：</strong>{{ selectedFarmer.account }}</p>
        <p><strong>账号昵称：</strong>{{ selectedFarmer.nickname }}</p>
        <p><strong>真实姓名：</strong>{{ selectedFarmer.real_name }}</p>
        <p><strong>养殖场名称：</strong>{{ selectedFarmer.farm_name }}</p>
        <p><strong>养殖场类型：</strong>{{ selectedFarmer.farm_type }}</p>
        <p><strong>养殖种类：</strong>{{ selectedFarmer.animal_type }}</p>
        <p><strong>养殖数量：</strong>{{ selectedFarmer.animal_count }}</p>
        <p><strong>养殖场地址：</strong>{{ selectedFarmer.address }}</p>
        <p><strong>登记时间：</strong>{{ selectedFarmer.register_time }}</p>
        <p><strong>登记人：</strong>{{ selectedFarmer.registrar }}</p>
        <p><strong>状态：</strong><a-tag :color="getStatusColor(selectedFarmer.status_value)">{{ selectedFarmer.status }}</a-tag></p>
      </div>
    </a-modal>
  </div>
</template>

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

// 搜索条件
const searchKeyword = ref('')
const farmTypeFilter = ref('')
const animalTypeFilter = ref('')

// 加载状态
const loading = ref(false)

// 养殖类型和种类列表
const farmTypes = ref([])
const animalTypes = ref([])

// 表格列定义
const columns = [
  {
    title: '账号',
    dataIndex: 'account',
    key: 'account',
    width: 150
  },
  {
    title: '账号昵称',
    dataIndex: 'nickname',
    key: 'nickname',
    width: 150
  },
  {
    title: '真实姓名',
    dataIndex: 'real_name',
    key: 'real_name',
    width: 150
  },
  {
    title: '养殖场名称',
    dataIndex: 'farm_name',
    key: 'farm_name',
    width: 180
  },
  {
    title: '养殖场类型',
    dataIndex: 'farm_type',
    key: 'farm_type',
    width: 120
  },
  {
    title: '养殖种类',
    dataIndex: 'animal_type',
    key: 'animal_type',
    width: 120
  },
  {
    title: '数量',
    dataIndex: 'animal_count',
    key: 'animal_count',
    width: 100
  },
  {
    title: '养殖场地址',
    dataIndex: 'address',
    key: 'address',
    width: 250
  },
  {
    title: '登记时间',
    dataIndex: 'register_time',
    key: 'register_time',
    width: 150,
    sorter: (a, b) => new Date(a.register_time) - new Date(b.register_time)
  },
  {
    title: '登记人',
    dataIndex: 'registrar',
    key: 'registrar',
    width: 120
  },
  {
    title: '状态',
    key: 'status',
    width: 100
  },
  {
    title: '操作',
    key: 'action',
    fixed: 'right',
    width: 180
  }
]

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total) => `共 ${total} 条记录`,
  pageSizeOptions: ['10', '20', '50', '100']
})

// 养殖户数据
const farmersData = ref([])

// 对话框相关
const modalVisible = ref(false)
const modalTitle = ref('')
const editingId = ref(null)
const formData = reactive({
  account: '',
  nickname: '',
  real_name: '',
  farm_name: '',
  farm_type: '',
  animal_type: '',
  animal_count: 0,
  address: '',
  status: 'active'
})

// 查看详情相关
const viewModalVisible = ref(false)
const selectedFarmer = ref(null)

// 初始化数据
onMounted(() => {
  initData()
})

// 初始化数据
const initData = async () => {
  try {
    await Promise.all([
      fetchFarmers(),
      fetchFarmTypes(),
      fetchAnimalTypes()
    ])
  } catch (error) {
    message.error('初始化数据失败')
    console.error('初始化数据失败:', error)
  }
}

// 获取养殖户列表
const fetchFarmers = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      search: searchKeyword.value,
      farmType: farmTypeFilter.value,
      animalType: animalTypeFilter.value
    }
    
    const response = await api.government.farmers.getList(params)
    farmersData.value = response.data || []
    pagination.total = response.total || 0
  } catch (error) {
    message.error('获取养殖户列表失败')
    console.error('获取养殖户列表失败:', error)
    farmersData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 获取养殖类型列表
const fetchFarmTypes = async () => {
  try {
    const response = await api.government.farmTypes.getList()
    farmTypes.value = response
  } catch (error) {
    message.error('获取养殖类型列表失败')
    console.error('获取养殖类型列表失败:', error)
  }
}

// 获取养殖种类列表
const fetchAnimalTypes = async () => {
  try {
    const response = await api.government.animalTypes.getList()
    animalTypes.value = response
  } catch (error) {
    message.error('获取养殖种类列表失败')
    console.error('获取养殖种类列表失败:', error)
  }
}

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

// 处理表格分页、排序等变化
const handleTableChange = (paginationInfo) => {
  pagination.current = paginationInfo.current
  pagination.pageSize = paginationInfo.pageSize
  fetchFarmers()
}

// 处理导出
const handleExport = () => {
  message.success('数据导出中...')
  // 实际应用中这里应该调用导出API
}

// 处理添加养殖户
const handleAddFarmer = () => {
  modalTitle.value = '新增养殖户'
  editingId.value = null
  // 重置表单
  Object.keys(formData).forEach(key => {
    formData[key] = key === 'animal_count' ? 0 : key === 'status' ? 'active' : ''
  })
  modalVisible.value = true
}

// 处理编辑养殖户
const handleEdit = async (record) => {
  try {
    modalTitle.value = '编辑养殖户'
    editingId.value = record.id
    // 填充表单数据
    formData.account = record.account
    formData.nickname = record.nickname
    formData.real_name = record.real_name
    formData.farm_name = record.farm_name
    formData.farm_type = record.farm_type
    formData.animal_type = record.animal_type
    formData.animal_count = record.animal_count
    formData.address = record.address
    formData.status = record.status_value
    modalVisible.value = true
  } catch (error) {
    message.error('加载养殖户信息失败')
    console.error('加载养殖户信息失败:', error)
  }
}

// 处理查看详情
const handleView = (record) => {
  selectedFarmer.value = record
  viewModalVisible.value = true
}

// 处理删除养殖户
const handleDelete = (id) => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除该养殖户吗？',
    okText: '确定',
    cancelText: '取消',
    async onOk() {
      try {
        await api.government.farmers.delete(id)
        message.success('删除成功')
        fetchFarmers()
      } catch (error) {
        message.error('删除失败')
        console.error('删除养殖户失败:', error)
      }
    }
  })
}

// 处理对话框确定
const handleOk = async () => {
  try {
    if (editingId.value) {
      // 编辑养殖户
      await api.government.farmers.update(editingId.value, formData)
      message.success('更新成功')
    } else {
      // 新增养殖户
      await api.government.farmers.create(formData)
      message.success('创建成功')
    }
    modalVisible.value = false
    fetchFarmers()
  } catch (error) {
    message.error(editingId.value ? '更新失败' : '创建失败')
    console.error(editingId.value ? '更新养殖户失败:' : '创建养殖户失败:', error)
  }
}

// 处理对话框取消
const handleCancel = () => {
  modalVisible.value = false
}

// 处理查看详情对话框取消
const handleViewCancel = () => {
  viewModalVisible.value = false
  selectedFarmer.value = null
}

// 获取状态颜色
const getStatusColor = (status) => {
  const statusMap = {
    active: 'green',
    inactive: 'orange',
    closed: 'red'
  }
  return statusMap[status] || 'default'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    active: '正常',
    inactive: '暂停',
    closed: '关闭'
  }
  return statusMap[status] || '未知'
}
</script>

<style scoped>
.ant-table {
  margin-top: 16px;
}
</style>