<template>
  <div>
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
      <h1>预警管理</h1>
      <a-space>
        <a-button @click="exportAlerts" :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="searchAlertsByFarm"
      />
      <a-button type="primary" @click="searchAlertsByFarm" :loading="searchLoading">
        <template #icon><SearchOutlined /></template>
        查询
      </a-button>
      <a-button @click="resetSearch" :disabled="!isSearching">
        重置
      </a-button>
    </div>
    
    <a-table 
      :columns="columns" 
      :data-source="alerts" 
      :loading="loading"
      :pagination="{ pageSize: 10 }"
      row-key="id"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'type'">
          <a-tag color="blue">{{ getTypeText(record.type) }}</a-tag>
        </template>
        <template v-else-if="column.dataIndex === 'level'">
          <a-tag :color="getLevelColor(record.level)">
            {{ getLevelText(record.level) }}
          </a-tag>
        </template>
        <template v-else-if="column.dataIndex === 'status'">
          <a-tag :color="getStatusColor(record.status)">
            {{ getStatusText(record.status) }}
          </a-tag>
        </template>
        <template v-else-if="column.dataIndex === 'farm_name'">
          {{ getFarmName(record.farm_id) }}
        </template>
        <template v-else-if="column.dataIndex === 'device_name'">
          {{ getDeviceName(record.device_id) }}
        </template>
        <template v-else-if="column.dataIndex === 'resolved_at'">
          {{ formatDate(record.resolved_at) }}
        </template>
        <template v-else-if="column.dataIndex === 'created_at'">
          {{ formatDateTime(record.created_at) }}
        </template>
        <template v-else-if="column.dataIndex === 'action'">
          <a-button type="link" @click="editAlert(record)">编辑</a-button>
          <a-button 
            type="link" 
            @click="resolveAlert(record)"
            v-if="record.status !== 'resolved'"
          >
            解决
          </a-button>
          <a-popconfirm
            title="确定要删除这个预警吗？"
            @confirm="deleteAlert(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="600px"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        layout="vertical"
      >
        <a-form-item label="预警类型" name="type">
          <a-select v-model="formData.type" placeholder="请选择预警类型">
            <a-select-option value="temperature">温度异常</a-select-option>
            <a-select-option value="humidity">湿度异常</a-select-option>
            <a-select-option value="device_failure">设备故障</a-select-option>
            <a-select-option value="animal_health">动物健康</a-select-option>
            <a-select-option value="security">安全警报</a-select-option>
            <a-select-option value="maintenance">维护提醒</a-select-option>
            <a-select-option value="other">其他</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="预警级别" name="level">
          <a-select v-model="formData.level" placeholder="请选择预警级别">
            <a-select-option value="low">低</a-select-option>
            <a-select-option value="medium">中</a-select-option>
            <a-select-option value="high">高</a-select-option>
            <a-select-option value="critical">紧急</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="预警消息" name="message">
          <a-textarea 
            v-model:value="formData.message" 
            placeholder="请输入预警消息"
            :rows="3"
          />
        </a-form-item>
        <a-form-item label="预警状态" name="status">
          <a-select v-model="formData.status" placeholder="请选择预警状态">
            <a-select-option value="active">活跃</a-select-option>
            <a-select-option value="acknowledged">已确认</a-select-option>
            <a-select-option value="resolved">已解决</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="所属农场" name="farm_id">
          <a-select 
            v-model="formData.farm_id" 
            placeholder="请选择所属农场"
            :loading="farmsLoading"
          >
            <a-select-option 
              v-for="farm in farms" 
              :key="farm.id" 
              :value="farm.id"
            >
              {{ farm.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="关联设备" name="device_id">
          <a-select 
            v-model="formData.device_id" 
            placeholder="请选择关联设备（可选）"
            :loading="devicesLoading"
            allow-clear
          >
            <a-select-option 
              v-for="device in devices" 
              :key="device.id" 
              :value="device.id"
            >
              {{ device.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="解决备注" name="resolution_notes" v-if="formData.status === 'resolved'">
          <a-textarea 
            v-model:value="formData.resolution_notes" 
            placeholder="请输入解决备注"
            :rows="2"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 解决预警模态框 -->
    <a-modal
      v-model:open="resolveModalVisible"
      title="解决预警"
      @ok="handleResolve"
      @cancel="resolveModalVisible = false"
      :confirm-loading="resolveLoading"
    >
      <a-form layout="vertical">
        <a-form-item label="解决备注">
          <a-textarea 
            v-model:value="resolveNotes" 
            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 { api } from '../utils/api'
import { ExportUtils } from '../utils/exportUtils'
import dayjs from 'dayjs'

// 响应式数据
const alerts = ref([])
const farms = ref([])
const devices = ref([])
const loading = ref(false)
const farmsLoading = ref(false)
const devicesLoading = ref(false)
const modalVisible = ref(false)
const resolveModalVisible = ref(false)
const submitLoading = ref(false)
const resolveLoading = ref(false)
const isEdit = ref(false)
const formRef = ref()
const currentAlert = ref(null)
const resolveNotes = ref('')

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

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

// 表单数据
const formData = reactive({
  id: null,
  type: '',
  level: 'medium',
  message: '',
  status: 'active',
  farm_id: null,
  device_id: null,
  resolution_notes: ''
})

// 表单验证规则
const rules = {
  type: [{ required: true, message: '请选择预警类型', trigger: 'change' }],
  level: [{ required: true, message: '请选择预警级别', trigger: 'change' }],
  message: [{ required: true, message: '请输入预警消息', trigger: 'blur' }],
  status: [{ required: true, message: '请选择预警状态', trigger: 'change' }],
  farm_id: [{ required: true, message: '请选择所属农场', trigger: 'change' }]
}

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  {
    title: '预警类型',
    dataIndex: 'type',
    key: 'type',
    width: 120
  },
  {
    title: '级别',
    dataIndex: 'level',
    key: 'level',
    width: 80
  },
  {
    title: '预警消息',
    dataIndex: 'message',
    key: 'message',
    ellipsis: true,
    width: 200
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '所属农场',
    dataIndex: 'farm_name',
    key: 'farm_name',
    width: 120
  },
  {
    title: '关联设备',
    dataIndex: 'device_name',
    key: 'device_name',
    width: 120
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 150
  },
  {
    title: '解决时间',
    dataIndex: 'resolved_at',
    key: 'resolved_at',
    width: 120
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 180
  }
]

// 获取预警列表
const fetchAlerts = async () => {
  try {
    loading.value = true
    const token = localStorage.getItem('token')
    const response = await api.get('/alerts')
    if (response.success) {
      alerts.value = response.data
    } else {
      message.error('获取预警列表失败')
    }
  } catch (error) {
    console.error('获取预警列表失败:', error)
    if (error.response && error.response.status === 401) {
      message.error('登录已过期，请重新登录')
      setTimeout(() => {
        window.location.href = '/login'
      }, 2000)
    } else {
      message.error('获取预警列表失败: ' + (error.message || '未知错误'))
    }
  } finally {
    loading.value = false
  }
}

// 获取农场列表
const fetchFarms = async () => {
  try {
    farmsLoading.value = true
    const token = localStorage.getItem('token')
    const response = await api.get('/farms')
    if (response.success) {
      farms.value = response.data
    }
  } catch (error) {
    console.error('获取农场列表失败:', error)
  } finally {
    farmsLoading.value = false
  }
}

// 获取设备列表
const fetchDevices = async () => {
  try {
    devicesLoading.value = true
    const token = localStorage.getItem('token')
    const response = await api.get('/devices')
    if (response.success) {
      devices.value = response.data
    }
  } catch (error) {
    console.error('获取设备列表失败:', error)
  } finally {
    devicesLoading.value = false
  }
}

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

// 编辑预警
const editAlert = (record) => {
  isEdit.value = true
  // 逐个字段赋值，避免破坏响应式绑定
  formData.id = record.id
  formData.type = record.type
  formData.level = record.level
  formData.message = record.message
  formData.status = record.status
  formData.farm_id = record.farm_id
  formData.device_id = record.device_id
  formData.resolution_notes = record.resolution_notes || ''
  
  modalVisible.value = true
  fetchFarms()
  fetchDevices()
}

// 解决预警
const resolveAlert = (record) => {
  currentAlert.value = record
  resolveNotes.value = ''
  resolveModalVisible.value = true
}

// 处理解决预警
const handleResolve = async () => {
  try {
    resolveLoading.value = true
    const token = localStorage.getItem('token')
    const response = await api.put(`/alerts/${currentAlert.value.id}`, {
      status: 'resolved',
      resolved_at: new Date().toISOString(),
      resolution_notes: resolveNotes.value
    })
    
    if (response.success) {
      message.success('预警已解决')
      resolveModalVisible.value = false
      fetchAlerts()
    } else {
      message.error('解决预警失败')
    }
  } catch (error) {
    console.error('解决预警失败:', error)
    message.error('解决预警失败')
  } finally {
    resolveLoading.value = false
  }
}

// 删除预警
const deleteAlert = async (id) => {
  try {
    const token = localStorage.getItem('token')
    const response = await api.delete(`/alerts/${id}`)
    if (response.success) {
      message.success('删除成功')
      fetchAlerts()
    } else {
      message.error('删除失败')
    }
  } catch (error) {
    console.error('删除预警失败:', error)
    message.error('删除失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    const token = localStorage.getItem('token')
    const config = {
      headers: {
        Authorization: `Bearer ${token}`
      }
    }
    
    // 准备提交数据
    const submitData = { ...formData }
    // 如果是新增操作，移除id字段
    if (!isEdit.value) {
      delete submitData.id
    }
    
    let response
    if (isEdit.value) {
      response = await api.put(`/alerts/${formData.id}`, submitData)
    } else {
      response = await api.post('/alerts', submitData)
    }
    
    if (response.success) {
      message.success(isEdit.value ? '更新成功' : '创建成功')
      modalVisible.value = false
      fetchAlerts()
    } else {
      message.error(isEdit.value ? '更新失败' : '创建失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    message.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

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

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    type: '',
    level: 'medium',
    message: '',
    status: 'active',
    farm_id: null,
    device_id: null,
    resolution_notes: ''
  })
  formRef.value?.resetFields()
}

// 获取级别颜色
const getLevelColor = (level) => {
  const colors = {
    low: 'green',
    medium: 'orange',
    high: 'red',
    critical: 'purple'
  }
  return colors[level] || 'default'
}

// 获取类型文本
const getTypeText = (type) => {
  const texts = {
    temperature_alert: '温度异常',
    humidity_alert: '湿度异常',
    feed_alert: '饲料异常',
    health_alert: '健康异常',
    device_alert: '设备异常',
    temperature: '温度异常',
    humidity: '湿度异常',
    device_failure: '设备故障',
    animal_health: '动物健康',
    security: '安全警报',
    maintenance: '维护提醒',
    other: '其他'
  }
  return texts[type] || type
}

// 获取级别文本
const getLevelText = (level) => {
  const texts = {
    low: '低',
    medium: '中',
    high: '高',
    critical: '紧急'
  }
  return texts[level] || level
}

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

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    active: '活跃',
    acknowledged: '已确认',
    resolved: '已解决'
  }
  return texts[status] || status
}

// 获取农场名称
const getFarmName = (farmId) => {
  const farm = farms.value.find(f => f.id === farmId)
  return farm ? farm.name : `农场ID: ${farmId}`
}

// 获取设备名称
const getDeviceName = (deviceId) => {
  if (!deviceId) return '-'
  const device = devices.value.find(d => d.id === deviceId)
  return device ? device.name : `设备ID: ${deviceId}`
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return dayjs(date).format('YYYY-MM-DD')
}

// 格式化日期时间
const formatDateTime = (date) => {
  if (!date) return '-'
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}

// 根据养殖场搜索预警
const searchAlertsByFarm = async () => {
  if (!searchFarmName.value.trim()) {
    message.warning('请输入养殖场名称进行搜索')
    return
  }
  
  try {
    searchLoading.value = true
    const token = localStorage.getItem('token')
    const response = await api.get('/alerts/search', {
      params: { farmName: searchFarmName.value.trim() }
    })
    
    if (response.success) {
      alerts.value = response.data || []
      isSearching.value = true
      message.success(response.message || `找到 ${alerts.value.length} 个匹配的预警`)
    } else {
      alerts.value = []
      message.info('未找到匹配的预警')
    }
  } catch (error) {
    console.error('搜索预警失败:', error)
    message.error('搜索预警失败')
    alerts.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 exportAlerts = async () => {
  try {
    if (!alerts.value || alerts.value.length === 0) {
      message.warning('没有数据可导出')
      return
    }
    
    exportLoading.value = true
    message.loading('正在导出数据...', 0)
    
    const result = ExportUtils.exportAlertsData(alerts.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 = []
  fetchAlerts() // 重新加载全部预警
}

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

<style scoped>
/* 可以添加自定义样式 */
</style>