<template>
  <div class="system-management">
    <a-page-header title="系统管理" sub-title="管理系统设置和配置">
      <template #extra>
        <a-space>
          <a-button 
            v-if="hasPermission('system:write')" 
            @click="exportConfig"
          >
            <ExportOutlined />
            导出配置
          </a-button>
          <a-button @click="handleRefresh">
            <ReloadOutlined />
            刷新
          </a-button>
        </a-space>
      </template>
    </a-page-header>

    <a-row :gutter="16">
      <a-col :span="8">
        <a-card title="系统信息" size="small">
          <a-descriptions :column="1" bordered size="small">
            <a-descriptions-item label="系统版本">{{ systemInfo.version }}</a-descriptions-item>
            <a-descriptions-item label="运行环境">{{ systemInfo.environment }}</a-descriptions-item>
            <a-descriptions-item label="启动时间">{{ systemInfo.startTime }}</a-descriptions-item>
            <a-descriptions-item label="运行时长">{{ systemInfo.uptime }}</a-descriptions-item>
          </a-descriptions>
        </a-card>
      </a-col>

      <a-col :span="8">
        <a-card title="数据库状态" size="small">
          <a-descriptions :column="1" bordered size="small">
            <a-descriptions-item label="连接状态">
              <a-tag :color="databaseStatus.status === 'running' ? 'green' : 'red'">
                {{ databaseStatus.status === 'running' ? '正常' : '异常' }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="数据库类型">{{ databaseStatus.type }}</a-descriptions-item>
            <a-descriptions-item label="连接数">{{ databaseStatus.connections }}</a-descriptions-item>
            <a-descriptions-item label="查询次数">{{ databaseStatus.queriesPerMinute }}次/分钟</a-descriptions-item>
          </a-descriptions>
        </a-card>
      </a-col>

      <a-col :span="8">
        <a-card title="缓存状态" size="small">
          <a-descriptions :column="1" bordered size="small">
            <a-descriptions-item label="Redis状态">
              <a-tag :color="cacheStatus.status === 'running' ? 'green' : 'red'">
                {{ cacheStatus.status === 'running' ? '正常' : '异常' }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="内存使用">{{ cacheStatus.memoryUsage }}</a-descriptions-item>
            <a-descriptions-item label="命中率">{{ cacheStatus.hitRate }}</a-descriptions-item>
            <a-descriptions-item label="键数量">{{ cacheStatus.keyCount }}</a-descriptions-item>
          </a-descriptions>
        </a-card>
      </a-col>
    </a-row>

    <a-row :gutter="16" style="margin-top: 16px;">
      <a-col :span="12">
        <a-card title="服务监控" size="small">
          <a-list item-layout="horizontal" :data-source="services">
            <template #renderItem="{ item }">
              <a-list-item>
                <a-list-item-meta :description="item.description">
                  <template #title>
                    <a-space>
                      <a-tag :color="item.status === 'running' ? 'green' : 'red'">
                        {{ item.status === 'running' ? '运行中' : '停止' }}
                      </a-tag>
                      {{ item.name }}
                    </a-space>
                  </template>
                  <template #avatar>
                    <a-avatar :style="{ backgroundColor: item.status === 'running' ? '#52c41a' : '#ff4d4f' }">
                      <DatabaseOutlined v-if="item.type === 'database'" />
                      <CloudServerOutlined v-if="item.type === 'cache'" />
                      <MessageOutlined v-if="item.type === 'mq'" />
                    </a-avatar>
                  </template>
                </a-list-item-meta>
                <template #actions>
                  <a-button 
                    size="small" 
                    v-if="item.status === 'running' && hasPermission('system:write')" 
                    danger 
                    @click="handleStopService(item)"
                  >
                    停止
                  </a-button>
                  <a-button 
                    size="small" 
                    v-if="item.status === 'stopped' && hasPermission('system:write')" 
                    type="primary" 
                    @click="handleStartService(item)"
                  >
                    启动
                  </a-button>
                </template>
              </a-list-item>
            </template>
          </a-list>
        </a-card>
      </a-col>

      <a-col :span="12">
        <a-card title="系统监控" size="small">
          <div style="height: 200px;" ref="monitorChartContainer"></div>
        </a-card>
      </a-col>
    </a-row>

    <a-row :gutter="16" style="margin-top: 16px;">
      <a-col :span="12">
        <a-card title="系统日志" size="small">
          <a-timeline>
            <a-timeline-item color="green">
              <p>用户登录成功 - admin (2024-03-15 14:30:22)</p>
            </a-timeline-item>
            <a-timeline-item color="blue">
              <p>数据库备份完成 - 备份文件: backup_20240315.sql (2024-03-15 14:00:00)</p>
            </a-timeline-item>
            <a-timeline-item color="orange">
              <p>系统警告 - 内存使用率超过80% (2024-03-15 13:45:18)</p>
            </a-timeline-item>
            <a-timeline-item color="green">
              <p>定时任务执行 - 清理过期日志 (2024-03-15 13:30:00)</p>
            </a-timeline-item>
          </a-timeline>
          <div style="text-align: center; margin-top: 16px;">
            <a-button type="link" @click="viewLogs">查看完整日志</a-button>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <a-row :gutter="16" style="margin-top: 16px;">
      <a-col :span="24">
        <a-card title="系统设置" size="small">
          <a-form :model="systemSettings" layout="vertical">
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item label="系统名称">
                  <a-input 
                    v-model:value="systemSettings.systemName" 
                    placeholder="请输入系统名称" 
                    :disabled="!hasPermission('system:write')"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="系统版本">
                  <a-input 
                    v-model:value="systemSettings.systemVersion" 
                    placeholder="请输入系统版本" 
                    :disabled="!hasPermission('system:write')"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="维护模式">
                  <a-switch 
                    v-model:checked="systemSettings.maintenanceMode" 
                    :disabled="!hasPermission('system:write')"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item label="会话超时(分钟)">
                  <a-input-number 
                    v-model:value="systemSettings.sessionTimeout" 
                    :min="5" 
                    :max="480" 
                    style="width: 100%" 
                    :disabled="!hasPermission('system:write')"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="每页显示数量">
                  <a-input-number 
                    v-model:value="systemSettings.pageSize" 
                    :min="10" 
                    :max="100" 
                    style="width: 100%" 
                    :disabled="!hasPermission('system:write')"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="启用API文档">
                  <a-switch 
                    v-model:checked="systemSettings.enableSwagger" 
                    :disabled="!hasPermission('system:write')"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-form-item v-if="hasPermission('system:write')">
              <a-button type="primary" @click="saveSettings">保存设置</a-button>
              <a-button style="margin-left: 8px" @click="resetSettings">重置</a-button>
            </a-form-item>
          </a-form>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { message, Modal } from 'ant-design-vue'
import * as echarts from 'echarts'
import {
  ReloadOutlined,
  DatabaseOutlined,
  CloudServerOutlined,
  MessageOutlined,
  ExportOutlined
} from '@ant-design/icons-vue'
import { useAppStore } from '@/stores/app'
import { 
  getServices, 
  startService, 
  stopService, 
  getSystemInfo, 
  getDatabaseStatus, 
  getCacheStatus,
  getSystemSettings,
  updateSystemSettings,
  getSystemMonitorData
} from '@/api/system'
import type { Service, SystemInfo, DatabaseStatus, CacheStatus, SystemSettings } from '@/api/system'

const appStore = useAppStore()

// 权限检查方法
const hasPermission = (permission: string) => {
  return appStore.hasPermission(permission)
}

const services = ref<Service[]>([])
const systemInfo = ref<SystemInfo>({
  version: 'v1.0.0',
  environment: 'Production',
  uptime: '12天3小时',
  startTime: '2024-03-15 10:00:00'
})

const databaseStatus = ref<DatabaseStatus>({
  status: 'running',
  type: 'MySQL',
  connections: '15/100',
  queriesPerMinute: 1234
})

const cacheStatus = ref<CacheStatus>({
  status: 'running',
  memoryUsage: '65%',
  hitRate: '92%',
  keyCount: 1234
})

const systemSettings = reactive<SystemSettings>({
  systemName: '结伴客管理系统',
  systemVersion: 'v1.0.0',
  maintenanceMode: false,
  sessionTimeout: 30,
  pageSize: 20,
  enableSwagger: true
})

// 图表容器引用
const monitorChartContainer = ref<HTMLDivElement | null>(null)
let monitorChartInstance: echarts.ECharts | null = null
let monitorInterval: number | null = null

// 初始化监控图表
const initMonitorChart = () => {
  if (monitorChartContainer.value) {
    monitorChartInstance = echarts.init(monitorChartContainer.value)
    updateMonitorChart()
  }
}

// 更新监控图表
const updateMonitorChart = async () => {
  try {
    const response = await getSystemMonitorData()
    if (response.success && monitorChartInstance) {
      const data = response.data
      
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['CPU使用率', '内存使用率', '网络流量']
        },
        xAxis: {
          type: 'category',
          data: [new Date(data.timestamp).toLocaleTimeString()]
        },
        yAxis: [
          {
            type: 'value',
            name: '使用率(%)',
            min: 0,
            max: 100
          },
          {
            type: 'value',
            name: '流量(KB/s)',
            min: 0
          }
        ],
        series: [
          {
            name: 'CPU使用率',
            data: [data.cpuUsage],
            type: 'line',
            smooth: true
          },
          {
            name: '内存使用率',
            data: [data.memoryUsage],
            type: 'line',
            smooth: true
          },
          {
            name: '网络流量',
            data: [data.networkTraffic],
            type: 'line',
            smooth: true,
            yAxisIndex: 1
          }
        ]
      }
      
      monitorChartInstance.setOption(option)
    }
  } catch (error) {
    console.error('获取监控数据失败:', error)
  }
}

// 开始监控
const startMonitoring = () => {
  initMonitorChart()
  monitorInterval = window.setInterval(updateMonitorChart, 5000)
}

// 停止监控
const stopMonitoring = () => {
  if (monitorInterval) {
    clearInterval(monitorInterval)
    monitorInterval = null
  }
  if (monitorChartInstance) {
    monitorChartInstance.dispose()
    monitorChartInstance = null
  }
}

onMounted(() => {
  loadSystemInfo()
  loadDatabaseStatus()
  loadCacheStatus()
  loadServices()
  loadSystemSettings()
  startMonitoring()
})

onBeforeUnmount(() => {
  stopMonitoring()
})

const loadSystemInfo = async () => {
  try {
    const response = await getSystemInfo()
    systemInfo.value = response.data
  } catch (error) {
    message.error('加载系统信息失败')
  }
}

const loadDatabaseStatus = async () => {
  try {
    const response = await getDatabaseStatus()
    databaseStatus.value = response.data
  } catch (error) {
    message.error('加载数据库状态失败')
  }
}

const loadCacheStatus = async () => {
  try {
    const response = await getCacheStatus()
    cacheStatus.value = response.data
  } catch (error) {
    message.error('加载缓存状态失败')
  }
}

const loadServices = async () => {
  try {
    const response = await getServices()
    services.value = response.data
  } catch (error) {
    message.error('加载服务列表失败')
  }
}

const loadSystemSettings = async () => {
  try {
    const response = await getSystemSettings()
    Object.assign(systemSettings, response.data)
  } catch (error) {
    message.error('加载系统设置失败')
  }
}

const handleRefresh = () => {
  loadSystemInfo()
  loadDatabaseStatus()
  loadCacheStatus()
  loadServices()
  message.success('系统状态已刷新')
}

const exportConfig = () => {
  try {
    // 创建要导出的数据对象
    const exportData = {
      systemInfo: systemInfo.value,
      databaseStatus: databaseStatus.value,
      cacheStatus: cacheStatus.value,
      systemSettings: systemSettings,
      services: services.value,
      exportTime: new Date().toISOString()
    }
    
    // 创建Blob对象
    const blob = new Blob([JSON.stringify(exportData, null, 2)], {
      type: 'application/json'
    })
    
    // 创建下载链接
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `system-config-${new Date().toISOString().slice(0, 10)}.json`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
    
    message.success('配置导出成功')
  } catch (error) {
    message.error('配置导出失败')
  }
}

const handleStopService = (service: Service) => {
  Modal.confirm({
    title: '确认停止',
    content: `确定要停止服务 "${service.name}" 吗？`,
    onOk: async () => {
      try {
        await stopService(service.id)
        message.success('服务已停止')
        loadServices()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}

const handleStartService = (service: Service) => {
  Modal.confirm({
    title: '确认启动',
    content: `确定要启动服务 "${service.name}" 吗？`,
    onOk: async () => {
      try {
        await startService(service.id)
        message.success('服务已启动')
        loadServices()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}

const viewLogs = () => {
  message.info('查看系统日志功能开发中')
}

const saveSettings = async () => {
  try {
    await updateSystemSettings(systemSettings)
    message.success('系统设置已保存')
  } catch (error) {
    message.error('保存设置失败')
  }
}

const resetSettings = () => {
  Object.assign(systemSettings, {
    systemName: '结伴客管理系统',
    systemVersion: 'v1.0.0',
    maintenanceMode: false,
    sessionTimeout: 30,
    pageSize: 20,
    enableSwagger: true
  })
  message.success('设置已重置')
}
</script>

<style scoped lang="less">
.system-management {
  .ant-card {
    margin-bottom: 16px;
  }
  
  .ant-descriptions-item-label {
    font-weight: 500;
  }
}
</style>