<script setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Setting,
  EditPen,
  DataBoard,
  Histogram,
  Box,
  HomeFilled,
  Fold,
  Expand,
  Bell,
  UserFilled,
  WarningFilled,
  Warning,
  SwitchButton,
  UploadFilled,
} from '@element-plus/icons-vue'

import LoginView from './views/LoginView.vue'
import SystemOverview from './views/SystemOverview.vue'
import ProjectConfig from './views/ProjectConfig.vue'
import DataEntry from './views/DataEntry.vue'
import RecordManage from './views/RecordManage.vue'
import AnalysisCenter from './views/AnalysisCenter.vue'
import EquipmentLedger from './views/EquipmentLedger.vue'
import UserManage from './views/UserManage.vue'
import ExcelImportCenter from './views/ExcelImportCenter.vue'

const sidebarCollapsed = ref(false)
const activeMenu = ref('system-overview')
const isAuthenticated = ref(Boolean(localStorage.getItem('precision_auth_token')))

const menuGroups = [
  {
    items: [
      { key: 'system-overview', label: '系统主页', icon: HomeFilled, component: SystemOverview, desc: '汇总整机、部件、指标与近期测试状态。' },
      { key: 'data-entry', label: '数据录入', icon: EditPen, component: DataEntry, desc: '按整机或部件录入测定数据并归档。' },
      { key: 'equipment-ledger', label: '设备台账', icon: Box, component: EquipmentLedger, desc: '统一管理整机与部件资产、详情与指标绑定。' },
    ],
  },
  {
    items: [
      { key: 'record-manage', label: '数据管理', icon: DataBoard, component: RecordManage, desc: '查看、筛选与清理历史测试记录。' },
      { key: 'analysis-center', label: '数据分析', icon: Histogram, component: AnalysisCenter, desc: '执行整机或部件精度保持性综合评估。' },
    ],
  },
  {
    items: [
      { key: 'project-config', label: '参数设置', icon: Setting, component: ProjectConfig, desc: '维护设备、指标字典与判定阈值配置。' },
      { key: 'excel-import', label: 'Excel 导入', icon: UploadFilled, component: ExcelImportCenter, desc: '用于系统初始化和跨表批量数据维护。' },
    ],
  },
  {
    items: [
      { key: 'user-manage', label: '账户密码', icon: UserFilled, component: UserManage, desc: '管理系统账号、角色状态与基础资料。' },
    ],
  },
]

const userProfile = reactive({
  id: Number(localStorage.getItem('precision_user_id') || 1),
  name: localStorage.getItem('precision_user_name') || '管理员',
  role: localStorage.getItem('precision_user_role') || '系统管理员',
})
const isAdmin = computed(() => ['系统管理员', '管理员', 'admin'].includes(userProfile.role))
const visibleMenuGroups = computed(() =>
  menuGroups
    .map((group) => ({
      items: group.items.filter((item) => (['user-manage', 'excel-import'].includes(item.key) ? isAdmin.value : true)),
    }))
    .filter((group) => group.items.length),
)
const flatMenus = computed(() => visibleMenuGroups.value.flatMap((group) => group.items))
const currentMenu = computed(() => flatMenus.value.find((item) => item.key === activeMenu.value) || flatMenus.value[0])
const currentComponent = computed(() => currentMenu.value.component)

const notifications = ref([])
const notificationPopoverVisible = ref(false)
const showNotificationDialog = ref(false)
const currentNotification = ref(null)
const userDialogVisible = ref(false)

const unreadCount = computed(() => notifications.value.filter((item) => !item.read).length)

const handleMenuSelect = (key) => {
  activeMenu.value = key
}

const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
}

const defaultNotifications = [
  {
    id: 1,
    title: '系统状态通知',
    content: '精度保持性评估系统已切换为统一工作空间风格，当前运行正常。',
    type: 'notice',
    read: false,
    created_at: '2026-05-18 09:00:00',
  },
  {
    id: 2,
    title: '分析任务提醒',
    content: '可直接按整机或部件选择设备并执行评估，不再需要先选项目。',
    type: 'warning',
    read: false,
    created_at: '2026-05-18 09:10:00',
  },
]

const loadNotifications = async () => {
  try {
    const response = await fetch('/api/announcements?limit=20')
    if (!response.ok) throw new Error('load notifications failed')
    const result = await response.json()
    const source = Array.isArray(result?.data) ? result.data : Array.isArray(result) ? result : []
    notifications.value = source.map((item, index) => ({
      id: item.id ?? index + 1,
      title: item.title || '系统通知',
      content: item.content || '',
      type: item.type || 'notice',
      read: false,
      created_at: item.created_at || new Date().toLocaleString('zh-CN'),
    }))
    if (!notifications.value.length) {
      notifications.value = defaultNotifications.map((item) => ({ ...item }))
    }
  } catch (error) {
    notifications.value = defaultNotifications.map((item) => ({ ...item }))
  }
}

const clearNotifications = () => {
  notifications.value.forEach((item) => {
    item.read = true
  })
}

const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  if (Number.isNaN(date.getTime())) return time
  return date.toLocaleString('zh-CN')
}

const viewNotification = (item) => {
  item.read = true
  notificationPopoverVisible.value = false
  currentNotification.value = item
  showNotificationDialog.value = true
}

const getNotificationType = (type) => {
  const map = { fault: 'danger', warning: 'warning', notice: 'info' }
  return map[type] || 'info'
}

const getNotificationTypeName = (type) => {
  const map = { fault: '故障', warning: '预警', notice: '通知' }
  return map[type] || '通知'
}

const showUserDialog = () => {
  if (!isAdmin.value) {
    ElMessage.info('普通用户仅支持查看与分析，不能修改账号信息')
    return
  }
  handleMenuSelect('user-manage')
}

const saveUserProfile = () => {
  const normalizedRole = userProfile.role === '管理员' ? 'admin' : userProfile.role === '普通用户' ? 'user' : userProfile.role
  fetch(`/api/users/${userProfile.id}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      username: userProfile.name,
      real_name: userProfile.name,
      role: normalizedRole,
      is_active: true,
    }),
  })
    .then(async (response) => {
      const data = await response.json()
      if (data.status !== 'success') {
        throw new Error(data.message || '保存失败')
      }
      localStorage.setItem('precision_user_id', String(userProfile.id))
      localStorage.setItem('precision_user_name', userProfile.name)
      localStorage.setItem('precision_user_role', userProfile.role)
      userDialogVisible.value = false
      ElMessage.success('账号信息已更新')
    })
    .catch((error) => {
      ElMessage.error(error.message || '账号信息保存失败')
    })
}

const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      localStorage.removeItem('precision_auth_token')
      localStorage.removeItem('precision_user_name')
      localStorage.removeItem('precision_user_role')
      localStorage.removeItem('precision_user_id')
      userProfile.id = 1
      userProfile.name = '管理员'
      userProfile.role = '系统管理员'
      isAuthenticated.value = false
      ElMessage.success('已退出登录')
    })
    .catch(() => {})
}

const handleLoginSuccess = () => {
  isAuthenticated.value = true
  activeMenu.value = 'system-overview'
  userProfile.id = Number(localStorage.getItem('precision_user_id') || 1)
  userProfile.name = localStorage.getItem('precision_user_name') || '管理员'
  userProfile.role = localStorage.getItem('precision_user_role') || '系统管理员'
  loadNotifications()
  fetch(`/api/users/${userProfile.id}`)
    .then(async (response) => {
      if (!response.ok) return
      const data = await response.json()
      if (data.status === 'success' && data.data) {
        userProfile.name = data.data.real_name || data.data.username
        userProfile.role = data.data.role === 'admin' ? '管理员' : '普通用户'
      }
    })
    .catch(() => {})
}

onMounted(() => {
  window.addEventListener('precision-auth-expired', () => {
    isAuthenticated.value = false
    ElMessage.warning('登录已过期，请重新登录')
  })
  if (!isAuthenticated.value) return
  loadNotifications()
  userProfile.id = Number(localStorage.getItem('precision_user_id') || 1)
  userProfile.name = localStorage.getItem('precision_user_name') || '管理员'
  userProfile.role = localStorage.getItem('precision_user_role') || '系统管理员'
  fetch(`/api/users/${userProfile.id}`)
    .then(async (response) => {
      if (!response.ok) return
      const data = await response.json()
      if (data.status === 'success' && data.data) {
        userProfile.name = data.data.real_name || data.data.username
        userProfile.role = data.data.role === 'admin' ? '管理员' : '普通用户'
      }
    })
    .catch(() => {})
})
</script>

<template>
  <LoginView v-if="!isAuthenticated" @login-success="handleLoginSuccess" />

  <div v-else class="app-layout">
    <aside class="sidebar" :class="{ collapsed: sidebarCollapsed }">
      <div class="sidebar-shell">
        <div class="logo">
          <div class="logo-badge">AR</div>
          <div v-if="!sidebarCollapsed" class="logo-copy">
            <div class="logo-title">数控机床中试验证阶段精度保持性综合评价系统</div>
            <div class="logo-subtitle">Accuracy Retention Workspace</div>
          </div>
        </div>

      <div class="menu-groups">
          <div v-for="(group, index) in visibleMenuGroups" :key="index" class="menu-group">
            <el-menu :default-active="activeMenu" :collapse="sidebarCollapsed" @select="handleMenuSelect">
              <el-menu-item v-for="item in group.items" :key="item.key" :index="item.key">
                <el-icon><component :is="item.icon" /></el-icon>
                <template #title>{{ item.label }}</template>
              </el-menu-item>
            </el-menu>
          </div>
        </div>

        <div class="sidebar-footer">
          <button class="sidebar-toggle" type="button" @click="toggleSidebar">
            <el-icon><component :is="sidebarCollapsed ? Expand : Fold" /></el-icon>
          </button>
        </div>
      </div>
    </aside>

    <div class="main-container">
      <header class="topbar">
        <div class="topbar-left">
          <div class="eyebrow">数控机床中试验证阶段精度保持性综合评价系统</div>
          <h1 class="page-title">{{ currentMenu.label }}</h1>
          <p class="page-description">{{ currentMenu.desc }}</p>
        </div>
        <div class="topbar-right">
          <div class="status-chip">
            <span class="status-dot"></span>
            <span>系统在线</span>
          </div>

          <el-popover v-model:visible="notificationPopoverVisible" placement="bottom-end" :width="380" trigger="click" popper-class="notification-popover">
            <template #reference>
              <div class="icon-button">
                <el-badge :value="unreadCount" :hidden="unreadCount === 0" class="notification-badge">
                  <el-icon class="notification-icon"><Bell /></el-icon>
                </el-badge>
              </div>
            </template>
            <div class="notification-panel">
              <div class="panel-header">
                <span class="title">通知中心</span>
                <el-button v-if="notifications.length" type="primary" text size="small" @click="clearNotifications">
                  全部已读
                </el-button>
              </div>
              <div v-if="notifications.length" class="notification-list">
                <div
                  v-for="item in notifications"
                  :key="item.id"
                  class="notification-item"
                  :class="{ unread: !item.read }"
                  @click="viewNotification(item)"
                >
                  <div class="item-icon" :class="item.type">
                    <el-icon v-if="item.type === 'fault'"><WarningFilled /></el-icon>
                    <el-icon v-else-if="item.type === 'warning'"><Warning /></el-icon>
                    <el-icon v-else><Bell /></el-icon>
                  </div>
                  <div class="item-content">
                    <div class="item-title">{{ item.title }}</div>
                    <div class="item-desc">{{ item.content }}</div>
                    <div class="item-time">{{ formatTime(item.created_at) }}</div>
                  </div>
                </div>
              </div>
              <el-empty v-else description="暂无通知" :image-size="60" />
            </div>
          </el-popover>

          <el-dialog
            v-model="showNotificationDialog"
            :title="currentNotification?.title || '通知详情'"
            width="500px"
            align-center
            destroy-on-close
            append-to-body
            class="notification-detail-dialog reliability-dialog"
          >
            <div v-if="currentNotification" class="notification-detail">
              <div class="detail-header">
                <el-tag :type="getNotificationType(currentNotification.type)" size="small">
                  {{ getNotificationTypeName(currentNotification.type) }}
                </el-tag>
                <span class="detail-time">{{ formatTime(currentNotification.created_at) }}</span>
              </div>
              <div class="detail-content">
                {{ currentNotification.content }}
              </div>
            </div>
          </el-dialog>

          <el-popover placement="bottom-end" :width="220" trigger="click">
            <template #reference>
              <div class="user-info">
                <el-avatar :size="38" class="user-avatar">
                  <el-icon :size="18"><UserFilled /></el-icon>
                </el-avatar>
                <div class="user-copy">
                  <span class="user-name">{{ userProfile.name }}</span>
                  <span class="user-role">{{ userProfile.role }}</span>
                </div>
              </div>
            </template>
            <div class="user-panel">
              <div class="user-header">
                <el-avatar :size="40" class="user-avatar">
                  <el-icon :size="20"><UserFilled /></el-icon>
                </el-avatar>
                <div class="user-detail">
                  <div class="user-name">{{ userProfile.name }}</div>
                  <div class="user-role">{{ userProfile.role }}</div>
                </div>
              </div>
              <el-divider style="margin: 12px 0" />
              <div class="user-menu">
                <div class="menu-item" @click="showUserDialog">
                  <el-icon><Setting /></el-icon>
                  <span>账户密码</span>
                </div>
                <div class="menu-item" @click="handleLogout">
                  <el-icon><SwitchButton /></el-icon>
                  <span>退出登录</span>
                </div>
              </div>
            </div>
          </el-popover>
        </div>
      </header>

      <main class="content">
        <section class="module-content">
          <component :is="currentComponent" />
        </section>
      </main>
    </div>
  </div>

  <el-dialog v-model="userDialogVisible" title="账号设置" width="460px">
    <el-form :model="userProfile" label-width="88px">
      <el-form-item label="用户名">
        <el-input v-model="userProfile.name" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="角色">
        <el-select v-model="userProfile.role" style="width: 100%">
          <el-option label="管理员" value="管理员" />
          <el-option label="普通用户" value="普通用户" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="userDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="saveUserProfile">保存</el-button>
    </template>
  </el-dialog>
</template>
