<template>
  <div class="hardware-management">
    <div class="page-header">
      <h1>硬件管理</h1>
      <p>管理和监控银行硬件设备状态</p>
    </div>

    <div class="content">
      <!-- 设备概览 -->
      <div class="overview-section">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-card>
              <a-statistic
                title="设备总数"
                :value="hardwareStats.total"
                :value-style="{ color: '#1890ff' }"
              />
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card>
              <a-statistic
                title="在线设备"
                :value="hardwareStats.online"
                :value-style="{ color: '#52c41a' }"
              />
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card>
              <a-statistic
                title="离线设备"
                :value="hardwareStats.offline"
                :value-style="{ color: '#ff4d4f' }"
              />
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card>
              <a-statistic
                title="故障设备"
                :value="hardwareStats.fault"
                :value-style="{ color: '#faad14' }"
              />
            </a-card>
          </a-col>
        </a-row>
      </div>

      <!-- 搜索和筛选 -->
      <div class="search-section">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-input-search
              v-model:value="searchText"
              placeholder="搜索设备名称或编号"
              enter-button="搜索"
              @search="handleSearch"
            />
          </a-col>
          <a-col :span="4">
            <a-select
              v-model:value="statusFilter"
              placeholder="设备状态"
              allow-clear
              @change="handleFilter"
            >
              <a-select-option value="online">在线</a-select-option>
              <a-select-option value="offline">离线</a-select-option>
              <a-select-option value="fault">故障</a-select-option>
              <a-select-option value="maintenance">维护中</a-select-option>
            </a-select>
          </a-col>
          <a-col :span="4">
            <a-select
              v-model:value="typeFilter"
              placeholder="设备类型"
              allow-clear
              @change="handleFilter"
            >
              <a-select-option value="atm">ATM机</a-select-option>
              <a-select-option value="pos">POS机</a-select-option>
              <a-select-option value="server">服务器</a-select-option>
              <a-select-option value="network">网络设备</a-select-option>
              <a-select-option value="printer">打印机</a-select-option>
            </a-select>
          </a-col>
          <a-col :span="4">
            <a-select
              v-model:value="locationFilter"
              placeholder="设备位置"
              allow-clear
              @change="handleFilter"
            >
              <a-select-option value="branch1">总行</a-select-option>
              <a-select-option value="branch2">分行</a-select-option>
              <a-select-option value="branch3">支行</a-select-option>
            </a-select>
          </a-col>
          <a-col :span="6">
            <a-space>
              <a-button type="primary" @click="handleAddDevice">
                <PlusOutlined />
                添加设备
              </a-button>
              <a-button @click="handleRefresh">
                <ReloadOutlined />
                刷新
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </div>

      <!-- 设备列表 -->
      <div class="table-section">
        <a-table
          :columns="columns"
          :data-source="filteredDevices"
          :pagination="pagination"
          :loading="loading"
          row-key="id"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'status'">
              <a-tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'type'">
              <a-tag :color="getTypeColor(record.type)">
                {{ getTypeText(record.type) }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'location'">
              {{ getLocationText(record.location) }}
            </template>
            <template v-else-if="column.key === 'lastCheckTime'">
              {{ record.lastCheckTime || '未检查' }}
            </template>
            <template v-else-if="column.key === 'action'">
              <a-space>
                <a-button type="link" size="small" @click="handleView(record)">
                  查看
                </a-button>
                <a-button type="link" size="small" @click="handleEdit(record)">
                  编辑
                </a-button>
                <a-button type="link" size="small" @click="handleCheck(record)">
                  检查
                </a-button>
                <a-button type="link" size="small" @click="handleMaintenance(record)">
                  维护
                </a-button>
              </a-space>
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <!-- 设备详情模态框 -->
    <a-modal
      v-model:open="detailModalVisible"
      title="设备详情"
      width="800px"
      :footer="null"
    >
      <div v-if="selectedDevice" class="device-detail">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="设备名称">
            {{ selectedDevice.name }}
          </a-descriptions-item>
          <a-descriptions-item label="设备编号">
            {{ selectedDevice.deviceNumber }}
          </a-descriptions-item>
          <a-descriptions-item label="设备类型">
            <a-tag :color="getTypeColor(selectedDevice.type)">
              {{ getTypeText(selectedDevice.type) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="设备状态">
            <a-tag :color="getStatusColor(selectedDevice.status)">
              {{ getStatusText(selectedDevice.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="设备位置">
            {{ getLocationText(selectedDevice.location) }}
          </a-descriptions-item>
          <a-descriptions-item label="IP地址">
            {{ selectedDevice.ipAddress }}
          </a-descriptions-item>
          <a-descriptions-item label="MAC地址">
            {{ selectedDevice.macAddress }}
          </a-descriptions-item>
          <a-descriptions-item label="序列号">
            {{ selectedDevice.serialNumber }}
          </a-descriptions-item>
          <a-descriptions-item label="购买日期">
            {{ selectedDevice.purchaseDate }}
          </a-descriptions-item>
          <a-descriptions-item label="保修期至">
            {{ selectedDevice.warrantyDate }}
          </a-descriptions-item>
          <a-descriptions-item label="最后检查时间">
            {{ selectedDevice.lastCheckTime || '未检查' }}
          </a-descriptions-item>
          <a-descriptions-item label="负责人">
            {{ selectedDevice.manager }}
          </a-descriptions-item>
          <a-descriptions-item label="设备描述" :span="2">
            {{ selectedDevice.description }}
          </a-descriptions-item>
        </a-descriptions>

        <!-- 设备监控数据 -->
        <div class="device-monitoring" v-if="selectedDevice.monitoring">
          <h4>监控数据</h4>
          <a-row :gutter="16">
            <a-col :span="8">
              <a-statistic
                title="CPU使用率"
                :value="selectedDevice.monitoring.cpuUsage"
                suffix="%"
                :value-style="{ color: selectedDevice.monitoring.cpuUsage > 80 ? '#ff4d4f' : '#52c41a' }"
              />
            </a-col>
            <a-col :span="8">
              <a-statistic
                title="内存使用率"
                :value="selectedDevice.monitoring.memoryUsage"
                suffix="%"
                :value-style="{ color: selectedDevice.monitoring.memoryUsage > 80 ? '#ff4d4f' : '#52c41a' }"
              />
            </a-col>
            <a-col :span="8">
              <a-statistic
                title="磁盘使用率"
                :value="selectedDevice.monitoring.diskUsage"
                suffix="%"
                :value-style="{ color: selectedDevice.monitoring.diskUsage > 80 ? '#ff4d4f' : '#52c41a' }"
              />
            </a-col>
          </a-row>
        </div>

        <!-- 设备历史 -->
        <div class="device-history" v-if="selectedDevice.history">
          <h4>设备历史</h4>
          <a-timeline>
            <a-timeline-item
              v-for="record in selectedDevice.history"
              :key="record.id"
              :color="getHistoryColor(record.action)"
            >
              <div class="history-item">
                <div class="history-header">
                  <span class="history-action">{{ getHistoryActionText(record.action) }}</span>
                  <span class="history-time">{{ record.time }}</span>
                </div>
                <div class="history-user">操作人：{{ record.operator }}</div>
                <div class="history-comment" v-if="record.comment">
                  备注：{{ record.comment }}
                </div>
              </div>
            </a-timeline-item>
          </a-timeline>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, ReloadOutlined } from '@ant-design/icons-vue'

// 响应式数据
const loading = ref(false)
const searchText = ref('')
const statusFilter = ref(undefined)
const typeFilter = ref(undefined)
const locationFilter = ref(undefined)
const detailModalVisible = ref(false)
const selectedDevice = ref(null)

// 硬件统计
const hardwareStats = ref({
  total: 156,
  online: 142,
  offline: 8,
  fault: 6
})

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
})

// 表格列配置
const columns = [
  {
    title: '设备名称',
    dataIndex: 'name',
    key: 'name',
    width: 150
  },
  {
    title: '设备编号',
    dataIndex: 'deviceNumber',
    key: 'deviceNumber',
    width: 120
  },
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
    width: 100
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '位置',
    dataIndex: 'location',
    key: 'location',
    width: 100
  },
  {
    title: 'IP地址',
    dataIndex: 'ipAddress',
    key: 'ipAddress',
    width: 120
  },
  {
    title: '负责人',
    dataIndex: 'manager',
    key: 'manager',
    width: 100
  },
  {
    title: '最后检查',
    dataIndex: 'lastCheckTime',
    key: 'lastCheckTime',
    width: 150
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
]

// 模拟设备数据
const devices = ref([
  {
    id: 1,
    name: 'ATM-001',
    deviceNumber: 'ATM-202401180001',
    type: 'atm',
    status: 'online',
    location: 'branch1',
    ipAddress: '192.168.1.101',
    macAddress: '00:1B:44:11:3A:B7',
    serialNumber: 'SN123456789',
    purchaseDate: '2023-01-15',
    warrantyDate: '2026-01-15',
    lastCheckTime: '2024-01-18 09:30:00',
    manager: '张三',
    description: '大堂ATM机，支持存取款和转账功能',
    monitoring: {
      cpuUsage: 45,
      memoryUsage: 60,
      diskUsage: 35
    },
    history: [
      {
        id: 1,
        action: 'install',
        operator: '技术部',
        time: '2023-01-15 10:00:00',
        comment: '设备安装完成'
      },
      {
        id: 2,
        action: 'check',
        operator: '张三',
        time: '2024-01-18 09:30:00',
        comment: '日常检查，设备运行正常'
      }
    ]
  },
  {
    id: 2,
    name: 'POS-001',
    deviceNumber: 'POS-202401180002',
    type: 'pos',
    status: 'offline',
    location: 'branch2',
    ipAddress: '192.168.2.101',
    macAddress: '00:1B:44:11:3A:B8',
    serialNumber: 'SN123456790',
    purchaseDate: '2023-03-20',
    warrantyDate: '2026-03-20',
    lastCheckTime: '2024-01-17 16:30:00',
    manager: '李四',
    description: '收银台POS机，支持刷卡和扫码支付',
    monitoring: null,
    history: [
      {
        id: 1,
        action: 'install',
        operator: '技术部',
        time: '2023-03-20 14:00:00',
        comment: '设备安装完成'
      },
      {
        id: 2,
        action: 'offline',
        operator: '系统',
        time: '2024-01-18 08:00:00',
        comment: '设备离线'
      }
    ]
  },
  {
    id: 3,
    name: 'SERVER-001',
    deviceNumber: 'SRV-202401180003',
    type: 'server',
    status: 'fault',
    location: 'branch1',
    ipAddress: '192.168.1.10',
    macAddress: '00:1B:44:11:3A:B9',
    serialNumber: 'SN123456791',
    purchaseDate: '2022-12-01',
    warrantyDate: '2025-12-01',
    lastCheckTime: '2024-01-18 08:15:00',
    manager: '王五',
    description: '核心业务服务器，运行银行核心系统',
    monitoring: {
      cpuUsage: 95,
      memoryUsage: 98,
      diskUsage: 85
    },
    history: [
      {
        id: 1,
        action: 'install',
        operator: '技术部',
        time: '2022-12-01 09:00:00',
        comment: '服务器安装完成'
      },
      {
        id: 2,
        action: 'fault',
        operator: '系统',
        time: '2024-01-18 08:15:00',
        comment: '服务器故障，CPU使用率过高'
      }
    ]
  }
])

// 计算属性
const filteredDevices = computed(() => {
  let result = devices.value

  if (searchText.value) {
    result = result.filter(device =>
      device.name.toLowerCase().includes(searchText.value.toLowerCase()) ||
      device.deviceNumber.toLowerCase().includes(searchText.value.toLowerCase())
    )
  }

  if (statusFilter.value) {
    result = result.filter(device => device.status === statusFilter.value)
  }

  if (typeFilter.value) {
    result = result.filter(device => device.type === typeFilter.value)
  }

  if (locationFilter.value) {
    result = result.filter(device => device.location === locationFilter.value)
  }

  return result
})

// 方法
const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const handleFilter = () => {
  // 筛选逻辑已在计算属性中处理
}

const handleTableChange = (pag) => {
  pagination.value.current = pag.current
  pagination.value.pageSize = pag.pageSize
}

const handleAddDevice = () => {
  message.info('添加设备功能开发中...')
}

const handleRefresh = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    message.success('数据已刷新')
  }, 1000)
}

const handleView = (record) => {
  selectedDevice.value = record
  detailModalVisible.value = true
}

const handleEdit = (record) => {
  message.info(`编辑设备: ${record.name}`)
}

const handleCheck = (record) => {
  record.lastCheckTime = new Date().toLocaleString()
  record.history.push({
    id: Date.now(),
    action: 'check',
    operator: '当前用户',
    time: new Date().toLocaleString(),
    comment: '设备检查完成'
  })
  message.success('设备检查完成')
}

const handleMaintenance = (record) => {
  record.status = 'maintenance'
  record.history.push({
    id: Date.now(),
    action: 'maintenance',
    operator: '当前用户',
    time: new Date().toLocaleString(),
    comment: '设备进入维护状态'
  })
  message.success('设备已进入维护状态')
}

const getStatusColor = (status) => {
  const colors = {
    online: 'green',
    offline: 'red',
    fault: 'orange',
    maintenance: 'blue'
  }
  return colors[status] || 'default'
}

const getStatusText = (status) => {
  const texts = {
    online: '在线',
    offline: '离线',
    fault: '故障',
    maintenance: '维护中'
  }
  return texts[status] || status
}

const getTypeColor = (type) => {
  const colors = {
    atm: 'blue',
    pos: 'green',
    server: 'purple',
    network: 'orange',
    printer: 'cyan'
  }
  return colors[type] || 'default'
}

const getTypeText = (type) => {
  const texts = {
    atm: 'ATM机',
    pos: 'POS机',
    server: '服务器',
    network: '网络设备',
    printer: '打印机'
  }
  return texts[type] || type
}

const getLocationText = (location) => {
  const texts = {
    branch1: '总行',
    branch2: '分行',
    branch3: '支行'
  }
  return texts[location] || location
}

const getHistoryColor = (action) => {
  const colors = {
    install: 'blue',
    check: 'green',
    maintenance: 'orange',
    fault: 'red',
    offline: 'red'
  }
  return colors[action] || 'default'
}

const getHistoryActionText = (action) => {
  const texts = {
    install: '设备安装',
    check: '设备检查',
    maintenance: '设备维护',
    fault: '设备故障',
    offline: '设备离线'
  }
  return texts[action] || action
}

// 生命周期
onMounted(() => {
  pagination.value.total = devices.value.length
})
</script>

<style scoped>
.hardware-management {
  padding: 24px;
}

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

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.content {
  background: #fff;
  border-radius: 8px;
  padding: 24px;
}

.overview-section {
  margin-bottom: 24px;
}

.search-section {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.table-section {
  margin-top: 16px;
}

.device-detail {
  padding: 16px 0;
}

.device-monitoring {
  margin-top: 24px;
  padding: 16px;
  background: #f5f5f5;
  border-radius: 8px;
}

.device-monitoring h4 {
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
}

.device-history {
  margin-top: 24px;
}

.device-history h4 {
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
}

.history-item {
  padding: 8px 0;
}

.history-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
}

.history-action {
  font-weight: 600;
}

.history-time {
  color: #999;
  font-size: 12px;
}

.history-user {
  color: #666;
  font-size: 12px;
  margin-bottom: 4px;
}

.history-comment {
  color: #333;
  font-size: 12px;
  background: #f5f5f5;
  padding: 8px;
  border-radius: 4px;
}
</style>
