<template>
  <div class="dashboard-container">
    <el-card shadow="never" class="main-card">
      <template #header>
        <div class="header-row">
          <div class="left-panel">
            <h2 class="sys-title">📡 光谱设备监控</h2>
            <div class="sys-status">
              <el-tag type="info" effect="plain" round size="small">
                <el-icon><Clock /></el-icon> 更新: {{ lastCheckTime || '...' }}
              </el-tag>
              <el-tag :type="roleTagType" effect="dark" round size="small" style="margin-left: 10px;">
                {{ roleDisplayName }}
                <span v-if="currentUsername">({{ currentUsername }})</span>
              </el-tag>
            </div>
          </div>

          <div class="header-actions">
            <el-button
                v-if="isAdmin"
                type="primary"
                plain
                icon="Avatar"
                @click="goToUserManagement"
            >
              用户管理
            </el-button>

            <el-button type="info" plain icon="Document" @click="openLogCenter(null)">
              日志中心
            </el-button>

            <el-button
                v-if="isAdmin"
                type="warning"
                plain
                icon="RefreshRight"
                :loading="runningTask"
                @click="runManualMonitor"
            >
              系统检测
            </el-button>

            <el-button circle icon="Refresh" :loading="loading" @click="fetchData" />

            <div class="divider-mobile"></div>

            <el-button type="danger" plain icon="SwitchButton" @click="handleLogout">
              退出
            </el-button>
          </div>
        </div>
      </template>

      <div class="status-summary">
        <el-tag color="#409EFF" effect="dark" class="legend-tag">修 (维修中)</el-tag>
        <el-tag color="#F56C6C" effect="dark" class="legend-tag">离线/>7天</el-tag>
        <el-tag color="#E6A23C" effect="dark" class="legend-tag">滞后1-7天</el-tag>
        <el-tag color="#FAC858" effect="dark" class="legend-tag" style="color: #333">滞后24h</el-tag>
        <el-tag color="#67C23A" effect="dark" class="legend-tag">正常</el-tag>
      </div>

      <div class="toolbar">
        <div class="filter-section">
          <el-radio-group v-model="filters.status" @change="fetchData" size="default">

            <el-radio-button label="all">全部</el-radio-button>

            <el-radio-button label="abnormal" class="red-radio">
              异常({{ summary.errorCount + summary.warningCount }})
            </el-radio-button>

            <el-radio-button label="maintenance" class="blue-radio">
              维修({{ summary.maintenanceCount }})
            </el-radio-button>

            <el-radio-button v-if="isAdmin" label="hidden" class="gray-radio">
              回收({{ summary.hiddenCount }})
            </el-radio-button>

          </el-radio-group>

          <el-input
              v-model="filters.keyword"
              placeholder="搜索设备名称..."
              class="search-input"
              prefix-icon="Search"
              clearable
          />
        </div>
      </div>

      <el-table
          :data="filteredData"
          border
          v-loading="loading"
          style="width: 100%; min-width: 950px;"
          :row-class-name="tableRowClassName"
          :height="tableHeight"
          :default-sort="{ prop: 'sortHours', order: 'descending' }"
      >
        <el-table-column label="状态" width="160" align="center" fixed="left">
          <template #default="{ row }">
            <el-tag v-if="row.is_hidden" color="#909399" effect="dark" style="border:none; color:#fff;">隐藏</el-tag>
            <el-tag
                v-else
                :color="row.statusColor"
                effect="dark"
                style="border:none; min-width: 60px;"
                :style="{ color: row.statusLabelColor || '#fff' }"
            >
              {{ row.statusLabel }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="设备名称 (点击看图)" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <div
                class="device-name-wrapper"
                :class="{ 'clickable-row': !row.is_hidden }"
                @click="handleDeviceClick(row)"
            >
              <span class="device-name" :class="{ 'text-deleted': row.is_hidden }">
                {{ formatDisplayName(row.name) }}
              </span>
              <el-icon v-if="!row.is_hidden" class="link-icon"><DataLine /></el-icon>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="安装地点" min-width="160">
          <template #default="{ row }">
            <div v-if="row.isEditingSite && canManageDevice" class="editing-cell">
              <el-input
                  v-model="row.tempSite"
                  size="small"
                  @blur="saveSite(row)"
                  @keyup.enter="saveSite(row)"
                  class="site-input-inner"
                  placeholder="输入后回车"
              />
            </div>
            <div v-else class="display-cell" @click="canManageDevice ? handleEditSite(row) : null" :style="{ cursor: canManageDevice ? 'pointer' : 'default' }">
              <span>{{ row.install_site || (canManageDevice ? '点击填写' : '-') }}</span>
              <el-icon v-if="canManageDevice" class="edit-icon"><EditPen /></el-icon>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="数据时效" width="220" prop="sortHours" sortable>
          <template #default="{ row }">
            <div style="font-size: 13px;"><el-icon><Clock /></el-icon> {{ row.latest_time || '--' }}</div>
            <div v-if="!row.is_maintaining && !row.is_hidden">
              <div v-if="row.status === 'offline' || row.status === '已离线'" class="status-text error-text">⚠️ 设备已离线</div>
              <div v-else-if="row.diffDays > 7" class="status-text error-text">⚠️ 严重滞后 {{ Math.floor(row.diffDays) }} 天</div>
              <div v-else-if="row.diffHours > 24" class="status-text warning-text">⚠️ 滞后 {{ Math.floor(row.diffDays) }} 天</div>
              <div v-else-if="!row.isToday" class="status-text slight-warning-text">⚠️ 昨日数据</div>
              <div v-else class="status-text success-text">✅ 数据最新</div>
            </div>
            <div v-else-if="row.is_maintaining" class="status-text maintenance-text">
              🛠️ 工程师介入中
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <div class="action-group">
              <template v-if="row.is_hidden">
                <el-button v-if="isAdmin" type="success" plain size="small" icon="RefreshLeft" @click="toggleHidden(row, false)">恢复</el-button>
              </template>

              <template v-else>
                <el-switch
                    v-if="canManageDevice"
                    v-model="row.is_maintaining"
                    inline-prompt
                    active-text="修"
                    inactive-text="行"
                    style="--el-switch-on-color: #409EFF; margin-right: 8px;"
                    :before-change="() => handleMaintenanceBeforeChange(row)"
                />

                <el-button type="primary" link icon="Edit" @click="openLogCenter(row)">日志</el-button>

                <el-popconfirm v-if="isAdmin" title="确定隐藏?" @confirm="toggleHidden(row, true)">
                  <template #reference>
                    <el-button type="danger" link icon="Delete">隐藏</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <DataMonitor ref="dataMonitorRef" />
    <MaintenanceLogs ref="maintenanceLogsRef" />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import request from '../utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Clock, DataLine, Document, Refresh, EditPen, Search, Edit, RefreshRight, Delete, RefreshLeft, SwitchButton, Avatar } from '@element-plus/icons-vue'

// 引入子组件
import DataMonitor from './DataMonitor.vue'
import MaintenanceLogs from './MaintenanceLogs.vue'

const router = useRouter()
const loading = ref(false)
const runningTask = ref(false)
const rawData = ref([])
const lastCheckTime = ref('')
const windowHeight = ref(window.innerHeight)
const windowWidth = ref(window.innerWidth)

// --- 🔐 权限状态管理 ---
const userRole = ref('')
const currentUsername = ref('')

const isAdmin = computed(() => userRole.value === 'admin')
const isEngineer = computed(() => userRole.value === 'engineer')
const isClient = computed(() => userRole.value === 'client')
const canManageDevice = computed(() => isAdmin.value || isEngineer.value)

const roleDisplayName = computed(() => {
  if (isAdmin.value) return '超级管理员'
  if (isEngineer.value) return '设备工程师'
  return '客户/浏览者'
})
const roleTagType = computed(() => {
  if (isAdmin.value) return 'danger'
  if (isEngineer.value) return 'warning'
  return 'info'
})

const tableHeight = computed(() => {
  const isMobile = windowWidth.value < 768
  const offset = isMobile ? 380 : 250
  return windowHeight.value - offset
})

const filters = reactive({ status: 'all', keyword: '' })

const dataMonitorRef = ref(null)
const maintenanceLogsRef = ref(null)

// 🟢 统计逻辑
const summary = computed(() => {
  const activeDevices = rawData.value.filter(r => !r.is_hidden)
  const errors = activeDevices.filter(r => r.statusType === 'error').length
  const warnings = activeDevices.filter(r => r.statusType === 'warning').length
  const maintenance = activeDevices.filter(r => r.is_maintaining).length
  const hidden = rawData.value.filter(r => r.is_hidden).length
  return { errorCount: errors, warningCount: warnings, hiddenCount: hidden, maintenanceCount: maintenance }
})

const goToUserManagement = () => { router.push('/user-management') }

const handleLogout = () => {
  ElMessageBox.confirm('确定退出系统吗？', '提示', { type: 'warning' }).then(() => {
    localStorage.clear()
    router.push('/')
    ElMessage.success('已安全退出')
  }).catch(() => {})
}

// -----------------------------------------------------
// 🟢 数据获取
// -----------------------------------------------------
const fetchData = async () => {
  loading.value = true
  try {
    const res = await request.get('/api/devices_overview')

    const backendList = res.data.data || res.data
    const now = new Date()

    let processedData = backendList.map(item => {
      const isHidden = item.is_hidden === true || item.is_hidden === 1
      let diffDays = 0, diffHours = 0, isToday = false, validTime = false

      if (item.latest_time && item.latest_time !== 'N/A') {
        const cleanDateStr = item.latest_time.toString().replace(/_/g, '-')
        const d = new Date(cleanDateStr)
        if (!isNaN(d.getTime())) {
          validTime = true
          const diffTime = now - d
          const safeDiff = diffTime > 0 ? diffTime : 0
          diffHours = safeDiff / (1000 * 60 * 60)
          diffDays = safeDiff / (1000 * 60 * 60 * 24)
          isToday = d.toDateString() === now.toDateString()
        }
      }

      // 排序优先级
      let sortHours = diffHours;
      if (item.is_maintaining) sortHours = Number.MAX_SAFE_INTEGER;
      else if (item.status === 'offline' || item.status === '已离线') sortHours = 1000000000;
      else if (!validTime) sortHours = 500000000;

      // 状态标签生成逻辑
      let statusColor = '#67C23A', statusLabel = '正常', statusType = 'normal', statusLabelColor = '#fff'

      if (item.is_maintaining) {
        statusColor = '#409EFF';
        statusType = 'maintenance';
        const mName = item.maintainer || '';
        statusLabel = mName ? `维修中 (${mName})` : '维修中';
      } else if ((item.status === 'offline' || item.status === '已离线') || (!validTime || diffDays > 7)) {
        statusLabel = '离线/滞后'; statusColor = '#F56C6C'; statusType = 'error';
      } else if (diffHours > 24) {
        statusColor = '#E6A23C'; statusLabel = '数据滞后'; statusType = 'warning';
      } else if (!isToday) {
        statusColor = '#FAC858'; statusLabel = '昨日数据'; statusType = 'slight-warning'; statusLabelColor = '#333';
      }

      return {
        ...item, is_hidden: isHidden, diffDays, diffHours, sortHours, isToday,
        statusColor, statusLabel, statusType, statusLabelColor, isEditingSite: false, tempSite: ''
      }
    })
    processedData.sort((a, b) => b.sortHours - a.sortHours)
    rawData.value = processedData
    lastCheckTime.value = new Date().toLocaleString()
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}

const handleDeviceClick = (row) => { if (!row.is_hidden && dataMonitorRef.value) dataMonitorRef.value.open(row) }

const openLogCenter = (row) => {
  if (maintenanceLogsRef.value) {
    maintenanceLogsRef.value.open(row ? { deviceName: row.name } : null)
  }
}

const runManualMonitor = async () => {
  if (!isAdmin.value) return ElMessage.warning('权限不足')
  runningTask.value = true
  try {
    const res = await request.post('/api/run_monitor')
    ElMessage.success(res.data.message || '任务启动')
    setTimeout(() => fetchData(), 3000)
  } catch (e) {
    ElMessage.warning('请求频繁或失败')
  } finally {
    setTimeout(() => { runningTask.value = false }, 1000)
  }
}

// 🟢 筛选逻辑
const filteredData = computed(() => {
  return rawData.value.filter(item => {
    // 1. 如果选的是“隐藏/回收站”，只显示隐藏设备
    if (filters.status === 'hidden') return item.is_hidden

    // 2. 对于其他选项，先排除隐藏设备
    if (item.is_hidden) return false

    // 3. 维修中筛选
    if (filters.status === 'maintenance') return item.is_maintaining

    // 4. 异常筛选 (包含离线、滞后、微滞后)
    if (filters.status === 'abnormal') return (item.statusType === 'error' || item.statusType === 'warning' || item.statusType === 'slight-warning')

    // 5. 全部
    return true
  }).filter(item => !filters.keyword || item.name.toLowerCase().includes(filters.keyword.toLowerCase()))
})

const handleEditSite = (row) => {
  if (!canManageDevice.value) {
    ElMessage.info('您没有修改权限')
    return
  }
  row.tempSite = row.install_site; row.isEditingSite = true
  nextTick(() => {
    const inputs = document.querySelectorAll('.site-input-inner input')
    if (inputs.length > 0) inputs[inputs.length - 1].focus()
  })
}

const saveSite = async (row) => {
  if (!row.isEditingSite) return
  const oldVal = row.install_site; row.install_site = row.tempSite; row.isEditingSite = false
  if (oldVal === row.tempSite) return
  try {
    await request.post('/api/update_site', { name: row.name, site: row.tempSite })
    ElMessage.success('已更新')
  } catch (e) { row.install_site = oldVal; ElMessage.error('更新失败') }
}

const handleMaintenanceBeforeChange = (row) => {
  if (!canManageDevice.value) return Promise.reject()

  return new Promise((resolve) => {
    const newVal = !row.is_maintaining
    const maintainerName = currentUsername.value || '工程师';

    request.post('/api/toggle_maintenance', {
      name: row.name,
      is_maintaining: newVal,
      maintainer: newVal ? maintainerName : null
    })
        .then(() => {
          row.is_maintaining = newVal;
          row.maintainer = newVal ? maintainerName : null;

          if (newVal) {
            row.statusColor = '#409EFF';
            row.statusLabel = `维修中 (${maintainerName})`;
            row.statusType = 'maintenance';
          } else {
            row.statusLabel = '更新中...';
          }

          ElMessage.success(newVal ? '已进入维修模式' : '已恢复');
          fetchData();
          resolve(true)
        })
        .catch(() => {
          ElMessage.error('操作失败');
          resolve(false)
        })
  })
}

const toggleHidden = async (row, targetState) => {
  if (!isAdmin.value) return
  try {
    await request.post('/api/toggle_hidden', { name: row.name, is_hidden: targetState })
    row.is_hidden = targetState; fetchData(); ElMessage.success(targetState ? '已隐藏' : '已恢复')
  } catch (e) { ElMessage.error('操作失败') }
}

const formatDisplayName = (name) => name ? name.toUpperCase().replace(/_/g, ' ') : ''
const tableRowClassName = ({ row }) => {
  if (row.is_hidden) return 'hidden-row'
  if (row.statusType === 'maintenance') return 'maintenance-row'
  if (row.statusType === 'error') return 'error-row'
  if (row.statusType === 'warning') return 'warning-row'
  return ''
}

const updateDimensions = () => {
  windowHeight.value = window.innerHeight
  windowWidth.value = window.innerWidth
}

onMounted(() => {
  userRole.value = localStorage.getItem('role') || 'client'
  currentUsername.value = localStorage.getItem('username') || ''
  fetchData()
  window.addEventListener('resize', updateDimensions)
})
onBeforeUnmount(() => window.removeEventListener('resize', updateDimensions))
</script>

<style scoped>
.dashboard-container { padding: 10px; background: #f5f7fa; min-height: 100vh; box-sizing: border-box; }
.main-card { border-radius: 8px; overflow: visible; }

.header-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}
.sys-title { margin: 0; font-size: 20px; color: #303133; font-weight: 700; white-space: nowrap; }
.left-panel { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.header-actions { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }

.status-summary { margin-bottom: 15px; display: flex; gap: 5px; flex-wrap: wrap; }
.legend-tag { font-weight: bold; border: none; font-size: 12px; }

.toolbar {
  background: #fff;
  padding: 10px;
  border-radius: 6px;
  margin-bottom: 10px;
  border: 1px solid #e4e7ed;
}
.filter-section {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}
.search-input { width: 220px; transition: width 0.3s; }

/* 🟢 自定义筛选按钮样式，增加辨识度 */
.red-radio :deep(.el-radio-button__inner) { color: #F56C6C; }
.red-radio.is-active :deep(.el-radio-button__inner) { background-color: #F56C6C; border-color: #F56C6C; color: #fff; box-shadow: -1px 0 0 0 #F56C6C; }

.blue-radio :deep(.el-radio-button__inner) { color: #409EFF; }
.blue-radio.is-active :deep(.el-radio-button__inner) { background-color: #409EFF; border-color: #409EFF; color: #fff; box-shadow: -1px 0 0 0 #409EFF; }

.gray-radio :deep(.el-radio-button__inner) { color: #909399; }
.gray-radio.is-active :deep(.el-radio-button__inner) { background-color: #909399; border-color: #909399; color: #fff; box-shadow: -1px 0 0 0 #909399; }

.device-name-wrapper { display: flex; align-items: center; gap: 5px; cursor: pointer; }
.device-name-wrapper:hover .device-name { color: #409EFF; text-decoration: underline; }
.device-name { font-weight: bold; font-size: 14px; color: #303133; }
.text-deleted { text-decoration: line-through; color: #999; }
.status-text { font-size: 12px; margin-top: 4px; font-weight: bold; }
.error-text { color: #F56C6C; }
.warning-text { color: #E6A23C; }
.success-text { color: #67C23A; }
.maintenance-text { color: #409EFF; font-weight: bold; }

.display-cell { padding: 4px 0; display: flex; align-items: center; justify-content: space-between; }
.edit-icon { color: #409EFF; margin-left: 5px; }

:deep(.error-row) { background-color: #fef0f0 !important; }
:deep(.warning-row) { background-color: #fdf6ec !important; }
:deep(.maintenance-row) { background-color: #f0f9ff !important; }
:deep(.hidden-row) { background-color: #f4f4f5 !important; color: #909399; }

@media screen and (max-width: 768px) {
  .dashboard-container { padding: 5px; }
  .left-panel { width: 100%; justify-content: space-between; margin-bottom: 5px; }
  .sys-title { font-size: 18px; }
  .header-actions { width: 100%; justify-content: space-between; }
  .header-actions .el-button { flex: 1; margin-left: 5px !important; margin-right: 5px !important; }
  .divider-mobile { width: 1px; height: 20px; background: #dcdfe6; margin: 0 5px; }
  .filter-section { justify-content: space-between; }
  .el-radio-group { width: 100%; display: flex; }
  .el-radio-button { flex: 1; }
  :deep(.el-radio-button__inner) { width: 100%; padding: 8px 0; }
  .search-input { width: 100%; margin-top: 5px; }
  .el-button [class*="el-icon"] + span { display: inline-block; }
}
</style>
