<template>
  <div class="smart-anklet-container">
    <div class="page-header">
      <h2>
        <a-icon type="radar-chart" style="margin-right: 8px;" />
        智能脚环管理
      </h2>
      <p>管理和监控智能脚环设备，实时监测动物运动和健康数据</p>
    </div>

    <!-- 操作栏 -->
    <div class="action-bar">
      <a-space>
        <a-button type="primary" @click="showAddModal">
          <template #icon>
            <PlusOutlined />
          </template>
          添加脚环
        </a-button>
        <a-button @click="refreshData">
          <template #icon>
            <ReloadOutlined />
          </template>
          刷新
        </a-button>
        <a-button @click="exportData">
          <template #icon>
            <ExportOutlined />
          </template>
          导出数据
        </a-button>
      </a-space>
    </div>

    <!-- 统计卡片 -->
    <!-- <a-row :gutter="16" class="stats-row">
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="总数量"
            :value="stats.total"
            :value-style="{ color: '#1890ff' }"
          />
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="活跃设备"
            :value="stats.active"
            :value-style="{ color: '#52c41a' }"
          />
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="待机设备"
            :value="stats.standby"
            :value-style="{ color: '#faad14' }"
          />
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="故障设备"
            :value="stats.fault"
            :value-style="{ color: '#f5222d' }"
          />
        </a-card>
      </a-col>
    </a-row> -->

    <!-- 数据表格 -->
    <a-card title="脚环设备列表" class="table-card">
      <a-table
        :columns="columns"
        :data-source="anklets"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'stepCount'">
            <a-statistic
              :value="record.stepCount"
              suffix="步"
              :value-style="{ fontSize: '14px' }"
            />
          </template>
          <template v-else-if="column.dataIndex === 'heartRate'">
            <span :style="{ color: getHeartRateColor(record.heartRate) }">
              {{ record.heartRate }} BPM
            </span>
          </template>
          <template v-else-if="column.dataIndex === 'temperature'">
            <span :style="{ color: getTemperatureColor(record.temperature) }">
              {{ record.temperature }}°C
            </span>
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="viewDetail(record)">
                详情
              </a-button>
              <a-button type="link" size="small" @click="viewChart(record)">
                图表
              </a-button>
              <a-button type="link" size="small" @click="editAnklet(record)">
                编辑
              </a-button>
              <a-popconfirm
                title="确定要删除这个脚环吗？"
                @confirm="deleteAnklet(record.id)"
                ok-text="确定"
                cancel-text="取消"
              >
                <a-button type="link" size="small" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 添加/编辑模态框 -->
    <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="deviceId">
          <a-input v-model:value="formData.deviceId" placeholder="请输入设备编号" />
        </a-form-item>
        <a-form-item label="动物ID" name="animalId">
          <a-select v-model:value="formData.animalId" placeholder="请选择关联动物">
            <a-select-option value="1">动物001</a-select-option>
            <a-select-option value="2">动物002</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="设备型号" name="model">
          <a-input v-model:value="formData.model" placeholder="请输入设备型号" />
        </a-form-item>
        <a-form-item label="监测频率" name="frequency">
          <a-select v-model:value="formData.frequency" placeholder="请选择监测频率">
            <a-select-option value="1">每分钟</a-select-option>
            <a-select-option value="5">每5分钟</a-select-option>
            <a-select-option value="15">每15分钟</a-select-option>
            <a-select-option value="60">每小时</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="安装日期" name="installDate">
          <a-date-picker v-model:value="formData.installDate" style="width: 100%" />
        </a-form-item>
        <a-form-item label="备注" name="notes">
          <a-textarea v-model:value="formData.notes" placeholder="请输入备注信息" />
        </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, ReloadOutlined, ExportOutlined } from '@ant-design/icons-vue'

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

// 统计数据
const stats = reactive({
  total: 0,
  active: 0,
  standby: 0,
  fault: 0
})

// 表格配置
const columns = [
  {
    title: '设备编号',
    dataIndex: 'deviceId',
    key: 'deviceId',
  },
  {
    title: '关联动物',
    dataIndex: 'animalName',
    key: 'animalName',
  },
  {
    title: '设备型号',
    dataIndex: 'model',
    key: 'model',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
  },
  {
    title: '步数',
    dataIndex: 'stepCount',
    key: 'stepCount',
  },
  {
    title: '心率',
    dataIndex: 'heartRate',
    key: 'heartRate',
  },
  {
    title: '体温',
    dataIndex: 'temperature',
    key: 'temperature',
  },
  {
    title: '最后更新',
    dataIndex: 'lastUpdate',
    key: 'lastUpdate',
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
  }
]

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
})

// 表单数据
const formData = reactive({
  id: null,
  deviceId: '',
  animalId: '',
  model: '',
  frequency: '',
  installDate: null,
  notes: ''
})

// 表单验证规则
const rules = {
  deviceId: [
    { required: true, message: '请输入设备编号', trigger: 'blur' }
  ],
  animalId: [
    { required: true, message: '请选择关联动物', trigger: 'change' }
  ],
  model: [
    { required: true, message: '请输入设备型号', trigger: 'blur' }
  ],
  frequency: [
    { required: true, message: '请选择监测频率', trigger: 'change' }
  ]
}

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

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    'active': '活跃',
    'standby': '待机',
    'fault': '故障'
  }
  return texts[status] || '未知'
}

// 获取心率颜色
const getHeartRateColor = (heartRate) => {
  if (heartRate >= 60 && heartRate <= 100) return '#52c41a'
  if (heartRate > 100 || heartRate < 60) return '#faad14'
  return '#f5222d'
}

// 获取体温颜色
const getTemperatureColor = (temperature) => {
  if (temperature >= 38.0 && temperature <= 39.5) return '#52c41a'
  if (temperature > 39.5 || temperature < 38.0) return '#faad14'
  return '#f5222d'
}

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true
    
    // 构建查询参数
    const params = new URLSearchParams({
      page: pagination.current.toString(),
      limit: pagination.pageSize.toString(),
      _t: Date.now().toString()
    })
    
    // 添加搜索条件
    if (searchValue.value.trim()) {
      params.append('search', searchValue.value.trim())
    }
    
    // 调用API获取脚环数据
    const response = await fetch(`/api/smart-devices/public/anklets?${params}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    
    if (result.success) {
      anklets.value = result.data.list || []
      pagination.total = result.data.pagination?.total || 0
      
      // 更新统计数据
      if (result.data.stats) {
        stats.total = result.data.stats.total || 0
        stats.active = result.data.stats.active || 0
        stats.standby = result.data.stats.standby || 0
        stats.fault = result.data.stats.fault || 0
      } else {
        // 如果没有统计数据，从数据中计算
        stats.total = anklets.value.length
        stats.active = anklets.value.filter(item => item.status === 'active').length
        stats.standby = anklets.value.filter(item => item.status === 'standby').length
        stats.fault = anklets.value.filter(item => item.status === 'fault').length
      }
    } else {
      throw new Error(result.message || '获取脚环数据失败')
    }
    
  } catch (error) {
    console.error('获取数据失败:', error)
    message.error('获取数据失败: ' + error.message)
    anklets.value = []
    pagination.total = 0
    resetStats()
  } finally {
    loading.value = false
  }
}

// 重置统计信息
const resetStats = () => {
  stats.total = 0
  stats.active = 0
  stats.standby = 0
  stats.fault = 0
}

// 刷新数据
const refreshData = () => {
  fetchData()
  message.success('数据已刷新')
}

// 导出数据
const exportData = () => {
  message.info('导出功能开发中...')
}

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

// 编辑脚环
const editAnklet = (record) => {
  isEdit.value = true
  Object.assign(formData, {
    ...record,
    installDate: null
  })
  modalVisible.value = true
}

// 查看详情
const viewDetail = (record) => {
  message.info(`查看 ${record.deviceId} 的详细信息`)
}

// 查看图表
const viewChart = (record) => {
  message.info(`查看 ${record.deviceId} 的运动图表`)
}

// 删除脚环
const deleteAnklet = async (id) => {
  try {
    message.success('删除成功')
    fetchData()
  } catch (error) {
    console.error('删除失败:', error)
    message.error('删除失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    message.success(isEdit.value ? '更新成功' : '创建成功')
    modalVisible.value = false
    fetchData()
  } catch (error) {
    console.error('提交失败:', error)
    message.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

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

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    deviceId: '',
    animalId: '',
    model: '',
    frequency: '',
    installDate: null,
    notes: ''
  })
  formRef.value?.resetFields()
}

// 表格变化处理
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchData()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.smart-anklet-container {
  padding: 24px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #1890ff;
  display: flex;
  align-items: center;
}

.page-header p {
  color: #666;
  margin: 0;
}

.action-bar {
  margin-bottom: 16px;
}

.stats-row {
  margin-bottom: 24px;
}

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