<template>
  <div>
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
      <h1>养殖场管理</h1>
      <a-space>
        <a-button @click="exportFarms" :loading="exportLoading">
          <template #icon><ExportOutlined /></template>
          导出数据
        </a-button>
        <a-button type="primary" @click="showAddModal">
          <template #icon><PlusOutlined /></template>
          添加养殖场
        </a-button>
      </a-space>
    </div>
    
    <!-- 搜索区域 -->
    <div style="margin-bottom: 16px; display: flex; gap: 8px; align-items: center;">
      <a-auto-complete
        v-model:value="searchFarmName"
        :options="farmNameOptions"
        placeholder="请选择或输入养殖场名称进行搜索"
        style="width: 300px;"
        :filter-option="false"
        @search="handleSearchInput"
        @press-enter="searchFarms"
      />
      <a-button type="primary" @click="searchFarms" :loading="searchLoading">
        <template #icon><SearchOutlined /></template>
        查询
      </a-button>
      <a-button @click="resetSearch" :disabled="!isSearching">
        重置
      </a-button>
    </div>
    
    <a-table 
      :columns="columns" 
      :data-source="farms" 
      :loading="loading"
      :pagination="{ pageSize: 10 }"
      row-key="id"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'status'">
          <a-tag :color="record.status === 'active' ? 'green' : record.status === 'inactive' ? 'red' : 'orange'">
            {{ getStatusText(record.status) }}
          </a-tag>
        </template>
        <template v-else-if="column.dataIndex === 'created_at'">
          {{ formatDate(record.created_at) }}
        </template>
        <template v-else-if="column.dataIndex === 'action'">
          <a-button type="link" @click="editFarm(record)">编辑</a-button>
          <a-popconfirm
            title="确定要删除这个养殖场吗？"
            @confirm="deleteFarm(record.id)"
            ok-text="确定"
            cancel-text="取消"
          >
            <a-button type="link" danger>删除</a-button>
          </a-popconfirm>
        </template>
      </template>
    </a-table>

    <!-- 添加/编辑养殖场模态框 -->
    <a-modal
      v-model:open="modalVisible"
      :title="isEdit ? '编辑养殖场' : '添加养殖场'"
      @ok="handleSubmit"
      @cancel="handleCancel"
      :confirm-loading="submitLoading"
      width="800px"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        layout="vertical"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="养殖场名称" name="name">
              <a-input v-model:value="formData.name" placeholder="请输入养殖场名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="负责人" name="owner">
              <a-input v-model:value="formData.owner" placeholder="请输入负责人姓名" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="联系电话" name="phone">
              <a-input v-model:value="formData.phone" placeholder="请输入联系电话" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="状态" name="status">
              <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="maintenance">维护中</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="地址" name="address">
          <a-input v-model:value="formData.address" placeholder="请输入详细地址" />
        </a-form-item>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="经度" name="longitude">
              <a-input-number 
                v-model:value="formData.longitude" 
                placeholder="请输入经度 (-180 ~ 180)"
                :precision="6"
                :step="0.000001"
                :min="-180"
                :max="180"
                :string-mode="false"
                :controls="false"
                :parser="value => {
                  if (!value) return value;
                  // 移除非数字字符，保留小数点和负号
                  const cleaned = value.toString().replace(/[^\d.-]/g, '');
                  // 确保只有一个小数点和负号在开头
                  const parts = cleaned.split('.');
                  if (parts.length > 2) {
                    return parts[0] + '.' + parts.slice(1).join('');
                  }
                  return cleaned;
                }"
                :formatter="value => value"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="纬度" name="latitude">
              <a-input-number 
                v-model:value="formData.latitude" 
                placeholder="请输入纬度 (-90 ~ 90)"
                :precision="6"
                :step="0.000001"
                :min="-90"
                :max="90"
                :string-mode="false"
                :controls="false"
                :parser="value => {
                  if (!value) return value;
                  // 移除非数字字符，保留小数点和负号
                  const cleaned = value.toString().replace(/[^\d.-]/g, '');
                  // 确保只有一个小数点和负号在开头
                  const parts = cleaned.split('.');
                  if (parts.length > 2) {
                    return parts[0] + '.' + parts.slice(1).join('');
                  }
                  return cleaned;
                }"
                :formatter="value => value"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="占地面积(亩)" name="area">
              <a-input-number 
                v-model:value="formData.area" 
                placeholder="请输入占地面积"
                :min="0"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="养殖规模" name="capacity">
              <a-input-number 
                v-model:value="formData.capacity" 
                placeholder="请输入养殖规模"
                :min="0"
                style="width: 100%"
              />
            </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, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, SearchOutlined, ExportOutlined } from '@ant-design/icons-vue'
import { ExportUtils } from '../utils/exportUtils'

// 响应式数据
const farms = ref([])
const loading = ref(false)
const modalVisible = ref(false)
const submitLoading = ref(false)
const isEdit = ref(false)
const formRef = ref()

// 搜索相关的响应式数据
const searchFarmName = ref('')
const searchLoading = ref(false)
const isSearching = ref(false)
const farmNameOptions = ref([])

// 导出相关
const exportLoading = ref(false)

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  owner: '',
  phone: '',
  address: '',
  longitude: undefined,
  latitude: undefined,
  area: undefined,
  capacity: undefined,
  status: 'active',
  description: ''
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入养殖场名称', trigger: 'blur' }],
  owner: [{ required: true, message: '请输入负责人姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
  longitude: [
    { validator: (rule, value) => {
      if (value === undefined || value === null || value === '') {
        return Promise.resolve(); // 允许为空
      }
      const num = parseFloat(value);
      if (isNaN(num)) {
        return Promise.reject('请输入有效的经度数值');
      }
      if (num < -180 || num > 180) {
        return Promise.reject('经度范围应在-180到180之间');
      }
      // 检查小数位数不超过6位
      const decimalPart = value.toString().split('.')[1];
      if (decimalPart && decimalPart.length > 6) {
        return Promise.reject('经度小数位数不能超过6位');
      }
      return Promise.resolve();
    }, trigger: 'blur' }
  ],
  latitude: [
    { validator: (rule, value) => {
      if (value === undefined || value === null || value === '') {
        return Promise.resolve(); // 允许为空
      }
      const num = parseFloat(value);
      if (isNaN(num)) {
        return Promise.reject('请输入有效的纬度数值');
      }
      if (num < -90 || num > 90) {
        return Promise.reject('纬度范围应在-90到90之间');
      }
      // 检查小数位数不超过6位
      const decimalPart = value.toString().split('.')[1];
      if (decimalPart && decimalPart.length > 6) {
        return Promise.reject('纬度小数位数不能超过6位');
      }
      return Promise.resolve();
    }, trigger: 'blur' }
  ],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  {
    title: '养殖场名称',
    dataIndex: 'name',
    key: 'name',
    width: 150
  },
  {
    title: '负责人',
    dataIndex: 'owner',
    key: 'owner',
    width: 100
  },
  {
    title: '联系电话',
    dataIndex: 'phone',
    key: 'phone',
    width: 120
  },
  {
    title: '地址',
    dataIndex: 'address',
    key: 'address',
    ellipsis: true
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 180
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 150
  }
]

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    active: '运营中',
    inactive: '已停用',
    maintenance: '维护中'
  }
  return statusMap[status] || status
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 获取养殖场列表
const fetchFarms = async () => {
  try {
    loading.value = true
    const { api } = await import('../utils/api')
    const response = await api.get('/farms')
    console.log('养殖场API响应:', response)
    
    // 检查响应格式
    if (response && response.success && Array.isArray(response.data)) {
      farms.value = response.data
    } else if (Array.isArray(response)) {
      // 兼容旧格式
      farms.value = response
    } else {
      farms.value = []
      console.warn('API返回数据格式异常:', response)
    }
  } catch (error) {
    console.error('获取养殖场列表失败:', error)
    message.error('获取养殖场列表失败')
    farms.value = []
  } finally {
    loading.value = false
  }
}

// 显示添加模态框
const showAddModal = () => {
  isEdit.value = false
  resetForm()
  modalVisible.value = true
}

// 编辑养殖场
const editFarm = (record) => {
  isEdit.value = true
  // 解析location对象中的经纬度数据
  const longitude = record.location?.lng || undefined
  const latitude = record.location?.lat || undefined
  
  Object.assign(formData, {
    ...record,
    longitude,
    latitude,
    owner: record.contact || ''
  })
  modalVisible.value = true
}

// 删除养殖场
const deleteFarm = async (id) => {
  try {
    const { api } = await import('../utils/api')
    await api.delete(`/farms/${id}`)
    message.success('删除成功')
    fetchFarms()
  } catch (error) {
    console.error('删除养殖场失败:', error)
    message.error('删除失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    const submitData = { ...formData }
    
    const { api } = await import('../utils/api')
    if (isEdit.value) {
      await api.put(`/farms/${formData.id}`, submitData)
      message.success('更新成功')
    } else {
      await api.post('/farms', submitData)
      message.success('创建成功')
    }
    
    modalVisible.value = false
    fetchFarms()
  } catch (error) {
    console.error('提交失败:', error)
    message.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  modalVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    name: '',
    owner: '',
    phone: '',
    address: '',
    longitude: undefined,
    latitude: undefined,
    area: undefined,
    capacity: undefined,
    status: 'active',
    description: ''
  })
  formRef.value?.resetFields()
}

// 搜索养殖场
const searchFarms = async () => {
  if (!searchFarmName.value.trim()) {
    message.warning('请输入养殖场名称进行搜索')
    return
  }
  
  try {
    searchLoading.value = true
    const { api } = await import('../utils/api')
    const response = await api.get('/farms/search', {
      params: { name: searchFarmName.value.trim() }
    })
    
    if (Array.isArray(response)) {
      farms.value = response
      isSearching.value = true
      message.success(`找到 ${response.length} 个匹配的养殖场`)
    } else {
      farms.value = []
      message.info('未找到匹配的养殖场')
    }
  } catch (error) {
    console.error('搜索养殖场失败:', error)
    message.error('搜索养殖场失败')
    farms.value = []
  } finally {
    searchLoading.value = false
  }
}

// 处理搜索输入（为自动完成提供选项）
const handleSearchInput = (value) => {
  if (!value) {
    farmNameOptions.value = []
    return
  }
  
  // 从现有养殖场列表中筛选匹配的养殖场名称
  const matchingFarms = farms.value.filter(farm => 
    farm.name.toLowerCase().includes(value.toLowerCase())
  )
  
  farmNameOptions.value = matchingFarms.map(farm => ({
    value: farm.name,
    label: farm.name
  }))
}

// 更新养殖场名称选项（在数据加载后）
const updateFarmNameOptions = () => {
  farmNameOptions.value = farms.value.map(farm => ({
    value: farm.name,
    label: farm.name
  }))
}

// 导出农场数据
const exportFarms = async () => {
  try {
    if (!farms.value || farms.value.length === 0) {
      message.warning('没有数据可导出')
      return
    }
    
    exportLoading.value = true
    message.loading('正在导出数据...', 0)
    
    const result = ExportUtils.exportFarmsData(farms.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('导出失败，请重试')
  } finally {
    exportLoading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchFarmName.value = ''
  isSearching.value = false
  farmNameOptions.value = []
  fetchFarms() // 重新加载全部养殖场
}

// 组件挂载时获取数据
onMounted(() => {
  fetchFarms().then(() => {
    updateFarmNameOptions()
  })
})
</script>

<style scoped>
.ant-form-item {
  margin-bottom: 16px;
}
</style>