<template>
  <div>
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
      <h1>设备管理</h1>
      <a-space>
        <a-button @click="exportDevices" :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="searchDeviceName"
        :options="deviceNameOptions"
        placeholder="请选择或输入设备名称进行搜索"
        style="width: 300px;"
        :filter-option="false"
        @search="handleSearchInput"
        @press-enter="searchDevices"
      />
      <a-button type="primary" @click="searchDevices" :loading="searchLoading">
        <template #icon><SearchOutlined /></template>
        查询
      </a-button>
      <a-button @click="resetSearch" :disabled="!isSearching">
        重置
      </a-button>
    </div>
    
    <a-table 
      :columns="columns" 
      :data-source="devices" 
      :loading="loading"
      :pagination="{ pageSize: 10 }"
      row-key="id"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'id'">
          {{ record.id }}
        </template>
        <template v-else-if="column.dataIndex === 'name'">
          {{ record.name }}
        </template>
        <template v-else-if="column.dataIndex === 'type'">
          <a-tag color="blue">{{ getTypeText(record.type) }}</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 === 'last_maintenance'">
          {{ formatDate(record.last_maintenance) }}
        </template>
        <template v-else-if="column.dataIndex === 'installation_date'">
          {{ formatDate(record.installation_date) }}
        </template>
        <template v-else-if="column.dataIndex === 'action'">
          <a-button type="link" @click="editDevice(record)">编辑</a-button>
          <a-popconfirm
            title="确定要删除这个设备吗？"
            @confirm="deleteDevice(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"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        layout="vertical"
      >
        <a-form-item label="设备名称" name="name">
          <a-input v-model:value="formData.name" placeholder="请输入设备名称" />
        </a-form-item>
        <a-form-item label="设备类型" name="type">
          <a-select v-model:value="formData.type" placeholder="请选择设备类型" @change="handleTypeChange">
            <a-select-option value="sensor">传感器</a-select-option>
            <a-select-option value="camera">摄像头</a-select-option>
            <a-select-option value="feeder">喂食器</a-select-option>
            <a-select-option value="monitor">监控器</a-select-option>
            <a-select-option value="controller">控制器</a-select-option>
            <a-select-option value="other">其他</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-if="showCustomTypeInput" label="自定义设备类型" name="customType">
          <a-input 
            v-model:value="formData.customType" 
            placeholder="请输入自定义设备类型"
          />
        </a-form-item>
        <a-form-item label="设备状态" name="status">
          <a-select v-model:value="formData.status" placeholder="请选择设备状态">
            <a-select-option value="online">在线</a-select-option>
            <a-select-option value="offline">离线</a-select-option>
            <a-select-option value="maintenance">维护中</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="所属农场" name="farm_id">
          <a-select 
            v-model:value="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="installation_date">
          <a-date-picker 
            v-model:value="formData.installation_date" 
            placeholder="请选择安装日期"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="最后维护时间" name="last_maintenance">
          <a-date-picker 
            v-model:value="formData.last_maintenance" 
            placeholder="请选择最后维护时间"
            style="width: 100%"
          />
        </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 devices = ref([])
const farms = ref([])
const loading = ref(false)
const farmsLoading = ref(false)
const modalVisible = ref(false)
const submitLoading = ref(false)
const isEdit = ref(false)
const formRef = ref()

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

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

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  type: '',
  status: 'offline',
  farm_id: null,
  installation_date: null,
  last_maintenance: null,
  customType: '' // 自定义设备类型
})

// 控制是否显示自定义输入框
const showCustomTypeInput = ref(false)

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
  customType: [{ 
    required: () => formData.type === 'other', 
    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: 'name',
    key: 'name'
  },
  {
    title: '设备类型',
    dataIndex: 'type',
    key: 'type',
    width: 120
  },
  {
    title: '设备状态',
    dataIndex: 'status',
    key: 'status',
    width: 120
  },
  {
    title: '所属农场',
    dataIndex: 'farm_name',
    key: 'farm_name',
    width: 150
  },
  {
    title: '安装日期',
    dataIndex: 'installation_date',
    key: 'installation_date',
    width: 120
  },
  {
    title: '最后维护',
    dataIndex: 'last_maintenance',
    key: 'last_maintenance',
    width: 120
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 150
  }
]

// 获取设备列表
const fetchDevices = async () => {
  try {
    loading.value = true
    const token = localStorage.getItem('token')
    const response = await api.get('/devices')
    if (response.success) {
      devices.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 handleTypeChange = (value) => {
  showCustomTypeInput.value = value === 'other'
  if (value !== 'other') {
    formData.customType = ''
  }
}

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

// 编辑设备
const editDevice = (record) => {
  isEdit.value = true
  const predefinedTypes = ['sensor', 'camera', 'feeder', 'monitor', 'controller']
  const isCustomType = !predefinedTypes.includes(record.type)
  
  // 逐个字段赋值，避免破坏响应式绑定
  formData.id = record.id
  formData.name = record.name
  formData.type = isCustomType ? 'other' : record.type
  formData.customType = isCustomType ? record.type : ''
  formData.status = record.status
  formData.farm_id = record.farm_id
  formData.installation_date = record.installation_date ? dayjs(record.installation_date) : null
  formData.last_maintenance = record.last_maintenance ? dayjs(record.last_maintenance) : null
  
  showCustomTypeInput.value = isCustomType
  modalVisible.value = true
  fetchFarms()
}

// 删除设备
const deleteDevice = async (id) => {
  try {
    const token = localStorage.getItem('token')
    const response = await api.delete(`/devices/${id}`)
    if (response.success) {
      message.success('删除成功')
      fetchDevices()
    } 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,
      type: formData.type === 'other' ? formData.customType : formData.type,
      installation_date: formData.installation_date ? formData.installation_date.format('YYYY-MM-DD') : null,
      last_maintenance: formData.last_maintenance ? formData.last_maintenance.format('YYYY-MM-DD') : null
    }
    // 移除customType字段，避免发送到后端
    delete submitData.customType
    
    // 如果是新增操作，移除id字段
    if (!isEdit.value) {
      delete submitData.id
    }
    
    let response
    if (isEdit.value) {
      response = await api.put(`/devices/${formData.id}`, submitData)
    } else {
      response = await api.post('/devices', submitData)
    }
    
    if (response.success) {
      message.success(isEdit.value ? '更新成功' : '创建成功')
      modalVisible.value = false
      fetchDevices()
    } 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,
    name: '',
    type: '',
    status: 'offline',
    farm_id: null,
    installation_date: null,
    last_maintenance: null,
    customType: ''
  })
  showCustomTypeInput.value = false
  formRef.value?.resetFields()
}

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

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    online: '在线',
    offline: '离线',
    maintenance: '维护中'
  }
  return texts[status] || status
}

// 获取类型文本
const getTypeText = (type) => {
  const texts = {
    temperature_sensor: '温度传感器',
    humidity_sensor: '湿度传感器',
    feed_dispenser: '饲料分配器',
    water_system: '水系统',
    ventilation_system: '通风系统',
    sensor: '传感器',
    camera: '摄像头',
    feeder: '喂食器',
    monitor: '监控器',
    controller: '控制器',
    other: '其他'
  }
  return texts[type] || type
}

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

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

// 搜索设备
const searchDevices = async () => {
  if (!searchDeviceName.value.trim()) {
    message.warning('请输入设备名称进行搜索')
    return
  }
  
  try {
    searchLoading.value = true
    const token = localStorage.getItem('token')
    const response = await api.get('/devices/search', {
      params: { name: searchDeviceName.value.trim() }
    })
    
    if (response.success) {
      devices.value = response.data || []
      isSearching.value = true
      message.success(response.message || `找到 ${devices.value.length} 个匹配的设备`)
    } else {
      devices.value = []
      message.info('未找到匹配的设备')
    }
  } catch (error) {
    console.error('搜索设备失败:', error)
    message.error('搜索设备失败')
    devices.value = []
  } finally {
    searchLoading.value = false
  }
}

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

// 重置搜索
const resetSearch = () => {
  searchDeviceName.value = ''
  isSearching.value = false
  deviceNameOptions.value = []
  fetchDevices() // 重新加载全部设备
}

// 更新设备名称选项（在数据加载后）
const updateDeviceNameOptions = () => {
  deviceNameOptions.value = devices.value.map(device => ({
    value: device.name,
    label: device.name
  }))
}

// 导出设备数据
const exportDevices = async () => {
  try {
    if (!devices.value || devices.value.length === 0) {
      message.warning('没有数据可导出')
      return
    }
    
    exportLoading.value = true
    message.loading('正在导出数据...', 0)
    
    const result = ExportUtils.exportDevicesData(devices.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
  }
}

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

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