<template>
  <div class="system-page">
    <a-page-header
      title="系统管理"
      sub-title="系统配置和权限管理"
    >
      <template #extra>
        <a-space>
          <a-button @click="fetchData">
            <template #icon><ReloadOutlined /></template>
            刷新数据
          </a-button>
          <a-button type="primary" @click="initSystem" :loading="initLoading">
            <template #icon><SettingOutlined /></template>
            初始化系统
          </a-button>
        </a-space>
      </template>
    </a-page-header>

    <div class="system-content">
      <!-- 系统统计卡片 -->
      <a-row :gutter="16" style="margin-bottom: 24px;">
        <a-col :span="6">
          <a-card>
            <a-statistic
              title="系统配置"
              :value="systemStats.configs?.total || 0"
              :value-style="{ color: '#1890ff' }"
            >
              <template #prefix>
                <SettingOutlined />
              </template>
            </a-statistic>
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card>
            <a-statistic
              title="菜单权限"
              :value="systemStats.menus?.total || 0"
              :value-style="{ color: '#52c41a' }"
            >
              <template #prefix>
                <MenuOutlined />
              </template>
            </a-statistic>
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card>
            <a-statistic
              title="系统用户"
              :value="systemStats.users?.total || 0"
              :value-style="{ color: '#fa8c16' }"
            >
              <template #prefix>
                <UserOutlined />
              </template>
            </a-statistic>
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card>
            <a-statistic
              title="用户角色"
              :value="systemStats.roles?.total || 0"
              :value-style="{ color: '#722ed1' }"
            >
              <template #prefix>
                <TeamOutlined />
              </template>
            </a-statistic>
          </a-card>
        </a-col>
      </a-row>

      <!-- 功能标签页 -->
      <a-tabs v-model:activeKey="activeTab" type="card">
        <!-- 系统配置管理 -->
        <a-tab-pane key="configs" tab="系统配置">
          <div class="config-section">
            <div class="section-header">
              <a-space>
                <a-select
                  v-model:value="selectedCategory"
                  placeholder="选择配置分类"
                  style="width: 200px;"
                  @change="filterConfigs"
                  allow-clear
                >
                  <a-select-option value="">全部分类</a-select-option>
                  <a-select-option 
                    v-for="category in categories" 
                    :key="category" 
                    :value="category"
                  >
                    {{ getCategoryName(category) }}
                  </a-select-option>
                </a-select>
                <a-button type="primary" @click="showAddConfigModal = true">
                  <template #icon><PlusOutlined /></template>
                  添加配置
                </a-button>
                <a-button @click="batchSaveConfigs" :loading="batchSaveLoading">
                  <template #icon><SaveOutlined /></template>
                  批量保存
                </a-button>
              </a-space>
            </div>

            <a-table
              :columns="configColumns"
              :data-source="filteredConfigs"
              :loading="configLoading"
              :pagination="{ pageSize: 15 }"
              row-key="id"
              size="small"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'config_value'">
                  <div v-if="record.config_type === 'boolean'">
                    <a-switch 
                      :checked="record.parsed_value" 
                      @change="updateConfigValue(record, $event)"
                      :disabled="!record.is_editable"
                    />
                  </div>
                  <div v-else-if="record.config_type === 'number'">
                    <a-input-number
                      :value="record.parsed_value"
                      @change="updateConfigValue(record, $event)"
                      :disabled="!record.is_editable"
                      style="width: 100%;"
                    />
                  </div>
                  <div v-else>
                    <a-input
                      :value="record.config_value"
                      @change="updateConfigValue(record, $event.target.value)"
                      :disabled="!record.is_editable"
                    />
                  </div>
                </template>
                
                <template v-else-if="column.dataIndex === 'category'">
                  <a-tag :color="getCategoryColor(record.category)">
                    {{ getCategoryName(record.category) }}
                  </a-tag>
                </template>
                
                <template v-else-if="column.dataIndex === 'is_public'">
                  <a-tag :color="record.is_public ? 'green' : 'orange'">
                    {{ record.is_public ? '公开' : '私有' }}
                  </a-tag>
                </template>
                
                <template v-else-if="column.dataIndex === 'is_editable'">
                  <a-tag :color="record.is_editable ? 'blue' : 'red'">
                    {{ record.is_editable ? '可编辑' : '只读' }}
                  </a-tag>
                </template>
                
                <template v-else-if="column.dataIndex === 'action'">
                  <a-space size="small">
                    <a-button 
                      type="primary" 
                      size="small" 
                      @click="editConfig(record)"
                      :disabled="!record.is_editable"
                    >
                      编辑
                    </a-button>
                    <a-button 
                      size="small" 
                      @click="resetConfig(record)"
                      :disabled="!record.is_editable"
                    >
                      重置
                    </a-button>
                    <a-button 
                      type="primary" 
                      danger 
                      size="small" 
                      @click="deleteConfig(record)"
                      :disabled="!record.is_editable"
                    >
                      删除
                    </a-button>
                  </a-space>
                </template>
              </template>
            </a-table>
          </div>
        </a-tab-pane>

        <!-- 菜单权限管理 -->
        <a-tab-pane key="menus" tab="菜单权限">
          <div class="menu-section">
            <div class="section-header">
              <a-space>
                <a-button @click="fetchMenus">
                  <template #icon><ReloadOutlined /></template>
                  刷新菜单
                </a-button>
                <a-button type="primary" @click="showAddMenuModal = true">
                  <template #icon><PlusOutlined /></template>
                  添加菜单
                </a-button>
              </a-space>
            </div>

            <a-table
              :columns="menuColumns"
              :data-source="menus"
              :loading="menuLoading"
              :pagination="false"
              row-key="id"
              size="small"
              :default-expand-all-rows="true"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'menu_name'">
                  <a-space>
                    <component 
                      :is="getIconComponent(record.icon)" 
                      v-if="record.icon"
                      style="color: #1890ff;"
                    />
                    {{ record.menu_name }}
                  </a-space>
                </template>
                
                <template v-else-if="column.dataIndex === 'required_roles'">
                  <a-space wrap>
                    <a-tag 
                      v-for="role in parseRoles(record.required_roles)" 
                      :key="role" 
                      :color="getRoleColor(role)"
                    >
                      {{ getRoleName(role) }}
                    </a-tag>
                  </a-space>
                </template>
                
                <template v-else-if="column.dataIndex === 'is_visible'">
                  <a-switch 
                    :checked="record.is_visible" 
                    @change="updateMenuVisible(record, $event)"
                  />
                </template>
                
                <template v-else-if="column.dataIndex === 'is_enabled'">
                  <a-switch 
                    :checked="record.is_enabled" 
                    @change="updateMenuEnabled(record, $event)"
                  />
                </template>
                
                <template v-else-if="column.dataIndex === 'action'">
                  <a-space size="small">
                    <a-button 
                      type="primary" 
                      size="small" 
                      @click="editMenu(record)"
                    >
                      编辑
                    </a-button>
                    <a-button 
                      type="primary" 
                      danger 
                      size="small" 
                      @click="deleteMenu(record)"
                    >
                      删除
                    </a-button>
                  </a-space>
                </template>
              </template>
            </a-table>
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>

    <!-- 添加配置模态框 -->
    <a-modal
      v-model:open="showAddConfigModal"
      title="添加系统配置"
      :confirm-loading="configSubmitLoading"
      @ok="saveConfig"
      @cancel="resetConfigForm"
    >
      <a-form
        ref="configFormRef"
        :model="configForm"
        :rules="configRules"
        layout="vertical"
      >
        <a-form-item label="配置键名" name="config_key">
          <a-input v-model:value="configForm.config_key" placeholder="例如: system.name" />
        </a-form-item>
        
        <a-form-item label="配置值" name="config_value">
          <a-textarea v-model:value="configForm.config_value" :rows="3" />
        </a-form-item>
        
        <a-form-item label="配置分类" name="category">
          <a-select v-model:value="configForm.category">
            <a-select-option value="general">通用配置</a-select-option>
            <a-select-option value="ui">界面配置</a-select-option>
            <a-select-option value="security">安全配置</a-select-option>
            <a-select-option value="notification">通知配置</a-select-option>
            <a-select-option value="monitoring">监控配置</a-select-option>
            <a-select-option value="report">报表配置</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="配置描述" name="description">
          <a-input v-model:value="configForm.description" />
        </a-form-item>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item name="is_public">
              <a-checkbox v-model:checked="configForm.is_public">
                公开配置（前端可访问）
              </a-checkbox>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="is_editable">
              <a-checkbox v-model:checked="configForm.is_editable">
                允许编辑
              </a-checkbox>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="排序顺序" name="sort_order">
          <a-input-number 
            v-model:value="configForm.sort_order" 
            :min="0" 
            style="width: 100%;"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 编辑配置模态框 -->
    <a-modal
      v-model:open="showEditConfigModal"
      title="编辑系统配置"
      :confirm-loading="configSubmitLoading"
      @ok="saveConfig"
      @cancel="resetConfigForm"
    >
      <a-form
        ref="configFormRef"
        :model="configForm"
        :rules="configRules"
        layout="vertical"
      >
        <a-form-item label="配置键名">
          <a-input :value="configForm.config_key" disabled />
        </a-form-item>
        
        <a-form-item label="配置值" name="config_value">
          <a-textarea v-model:value="configForm.config_value" :rows="3" />
        </a-form-item>
        
        <a-form-item label="配置描述" name="description">
          <a-input v-model:value="configForm.description" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import { 
  ReloadOutlined, 
  SettingOutlined, 
  PlusOutlined,
  SaveOutlined,
  MenuOutlined,
  UserOutlined,
  TeamOutlined
} from '@ant-design/icons-vue'
import { api } from '../utils/api'
import * as Icons from '@ant-design/icons-vue'

// 响应式数据
const loading = ref(false)
const configLoading = ref(false)
const menuLoading = ref(false)
const initLoading = ref(false)
const configSubmitLoading = ref(false)
const batchSaveLoading = ref(false)

const activeTab = ref('configs')
const systemStats = ref({})
const configs = ref([])
const menus = ref([])
const categories = ref([])
const selectedCategory = ref('')

// 模态框状态
const showAddConfigModal = ref(false)
const showEditConfigModal = ref(false)
const showAddMenuModal = ref(false)

// 表单引用
const configFormRef = ref()

// 配置表单数据
const configForm = reactive({
  id: null,
  config_key: '',
  config_value: '',
  category: 'general',
  description: '',
  is_public: false,
  is_editable: true,
  sort_order: 0
})

// 表单验证规则
const configRules = {
  config_key: [{ required: true, message: '请输入配置键名' }],
  config_value: [{ required: true, message: '请输入配置值' }],
  category: [{ required: true, message: '请选择配置分类' }]
}

// 过滤后的配置列表
const filteredConfigs = computed(() => {
  if (!selectedCategory.value) {
    return configs.value
  }
  return configs.value.filter(config => config.category === selectedCategory.value)
})

// 配置表格列定义
const configColumns = [
  {
    title: '配置键名',
    dataIndex: 'config_key',
    key: 'config_key',
    width: 200,
    ellipsis: true
  },
  {
    title: '配置值',
    dataIndex: 'config_value',
    key: 'config_value',
    width: 250
  },
  {
    title: '分类',
    dataIndex: 'category',
    key: 'category',
    width: 120
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true
  },
  {
    title: '公开',
    dataIndex: 'is_public',
    key: 'is_public',
    width: 80
  },
  {
    title: '可编辑',
    dataIndex: 'is_editable',
    key: 'is_editable',
    width: 80
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 180,
    fixed: 'right'
  }
]

// 菜单表格列定义
const menuColumns = [
  {
    title: '菜单名称',
    dataIndex: 'menu_name',
    key: 'menu_name',
    width: 200
  },
  {
    title: '菜单路径',
    dataIndex: 'menu_path',
    key: 'menu_path',
    width: 150
  },
  {
    title: '所需角色',
    dataIndex: 'required_roles',
    key: 'required_roles',
    width: 200
  },
  {
    title: '排序',
    dataIndex: 'sort_order',
    key: 'sort_order',
    width: 80
  },
  {
    title: '可见',
    dataIndex: 'is_visible',
    key: 'is_visible',
    width: 80
  },
  {
    title: '启用',
    dataIndex: 'is_enabled',
    key: 'is_enabled',
    width: 80
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 120,
    fixed: 'right'
  }
]

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

// 获取所有数据
async function fetchData() {
  await Promise.all([
    fetchSystemStats(),
    fetchConfigs(),
    fetchMenus(),
    fetchCategories()
  ])
}

// 获取系统统计信息
async function fetchSystemStats() {
  try {
    const response = await api.get('/system/stats')
    if (response.success) {
      systemStats.value = response.data
    }
  } catch (error) {
    console.error('获取系统统计失败:', error)
  }
}

// 获取系统配置
async function fetchConfigs() {
  configLoading.value = true
  try {
    const response = await api.get('/system/configs')
    if (response.success) {
      configs.value = response.data
    }
  } catch (error) {
    console.error('获取系统配置失败:', error)
    message.error('获取系统配置失败')
  } finally {
    configLoading.value = false
  }
}

// 获取菜单权限
async function fetchMenus() {
  menuLoading.value = true
  try {
    const response = await api.get('/system/menus')
    if (response.success) {
      menus.value = response.data
    }
  } catch (error) {
    console.error('获取菜单权限失败:', error)
    message.error('获取菜单权限失败')
  } finally {
    menuLoading.value = false
  }
}

// 获取配置分类
async function fetchCategories() {
  try {
    const response = await api.get('/system/configs/categories')
    if (response.success) {
      categories.value = response.data
    }
  } catch (error) {
    console.error('获取配置分类失败:', error)
  }
}

// 初始化系统
async function initSystem() {
  initLoading.value = true
  try {
    const response = await api.post('/system/init')
    if (response.success) {
      message.success('系统初始化成功')
      await fetchData()
    }
  } catch (error) {
    console.error('系统初始化失败:', error)
    message.error('系统初始化失败')
  } finally {
    initLoading.value = false
  }
}

// 过滤配置
function filterConfigs() {
  // 响应式计算属性会自动处理过滤
}

// 更新配置值
function updateConfigValue(config, value) {
  const index = configs.value.findIndex(c => c.id === config.id)
  if (index !== -1) {
    configs.value[index].config_value = String(value)
    configs.value[index].parsed_value = value
    configs.value[index]._changed = true // 标记为已修改
  }
}

// 批量保存配置
async function batchSaveConfigs() {
  const changedConfigs = configs.value.filter(config => config._changed)
  
  if (changedConfigs.length === 0) {
    message.info('没有配置需要保存')
    return
  }
  
  batchSaveLoading.value = true
  try {
    const configsToUpdate = changedConfigs.map(config => ({
      config_key: config.config_key,
      config_value: config.parsed_value
    }))
    
    const response = await api.put('/system/configs/batch', {
      configs: configsToUpdate
    })
    
    if (response.success) {
      message.success(`成功保存 ${changedConfigs.length} 个配置`)
      await fetchConfigs() // 重新获取数据
    }
  } catch (error) {
    console.error('批量保存配置失败:', error)
    message.error('批量保存配置失败')
  } finally {
    batchSaveLoading.value = false
  }
}

// 编辑配置
function editConfig(record) {
  Object.assign(configForm, {
    id: record.id,
    config_key: record.config_key,
    config_value: record.config_value,
    category: record.category,
    description: record.description,
    is_public: record.is_public,
    is_editable: record.is_editable,
    sort_order: record.sort_order
  })
  showEditConfigModal.value = true
}

// 保存配置
async function saveConfig() {
  try {
    await configFormRef.value.validate()
    configSubmitLoading.value = true
    
    if (configForm.id) {
      // 更新配置
      const response = await api.put(`/system/configs/${configForm.id}`, {
        config_value: configForm.config_value,
        description: configForm.description
      })
      
      if (response.success) {
        message.success('配置更新成功')
        showEditConfigModal.value = false
        await fetchConfigs()
      }
    } else {
      // 创建配置
      const response = await api.post('/system/configs', configForm)
      
      if (response.success) {
        message.success('配置创建成功')
        showAddConfigModal.value = false
        await fetchConfigs()
      }
    }
    
    resetConfigForm()
  } catch (error) {
    console.error('保存配置失败:', error)
    message.error('保存配置失败')
  } finally {
    configSubmitLoading.value = false
  }
}

// 重置配置表单
function resetConfigForm() {
  Object.assign(configForm, {
    id: null,
    config_key: '',
    config_value: '',
    category: 'general',
    description: '',
    is_public: false,
    is_editable: true,
    sort_order: 0
  })
  configFormRef.value?.resetFields()
}

// 删除配置
async function deleteConfig(record) {
  try {
    const response = await api.delete(`/system/configs/${record.id}`)
    if (response.success) {
      message.success('配置删除成功')
      await fetchConfigs()
    }
  } catch (error) {
    console.error('删除配置失败:', error)
    message.error('删除配置失败')
  }
}

// 重置配置
async function resetConfig(record) {
  try {
    const response = await api.post(`/system/configs/${record.id}/reset`)
    if (response.success) {
      message.success('配置重置成功')
      await fetchConfigs()
    }
  } catch (error) {
    console.error('重置配置失败:', error)
    message.error('重置配置失败')
  }
}

// 工具函数
function getCategoryName(category) {
  const categoryMap = {
    general: '通用配置',
    ui: '界面配置',
    security: '安全配置',
    notification: '通知配置',
    monitoring: '监控配置',
    report: '报表配置'
  }
  return categoryMap[category] || category
}

function getCategoryColor(category) {
  const colorMap = {
    general: 'blue',
    ui: 'green',
    security: 'red',
    notification: 'orange',
    monitoring: 'purple',
    report: 'cyan'
  }
  return colorMap[category] || 'default'
}

function getIconComponent(iconName) {
  if (!iconName) return null
  const iconKey = iconName.split('-').map(part => 
    part.charAt(0).toUpperCase() + part.slice(1)
  ).join('')
  return Icons[iconKey] || Icons.SettingOutlined
}

function parseRoles(rolesStr) {
  try {
    return rolesStr ? JSON.parse(rolesStr) : []
  } catch {
    return []
  }
}

function getRoleColor(role) {
  const colorMap = {
    admin: 'red',
    manager: 'orange',
    user: 'blue'
  }
  return colorMap[role] || 'default'
}

function getRoleName(role) {
  const nameMap = {
    admin: '管理员',
    manager: '管理者',
    user: '普通用户'
  }
  return nameMap[role] || role
}

// 菜单相关方法（占位符）
function editMenu(record) {
  message.info('菜单编辑功能开发中')
}

function deleteMenu(record) {
  message.info('菜单删除功能开发中')
}

function updateMenuVisible(record, visible) {
  message.info('菜单可见性更新功能开发中')
}

function updateMenuEnabled(record, enabled) {
  message.info('菜单启用状态更新功能开发中')
}
</script>

<style scoped>
.system-page {
  padding: 0;
}

.system-content {
  padding: 24px;
  background: #f0f2f5;
  min-height: calc(100vh - 180px);
}

.section-header {
  margin-bottom: 16px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ant-card {
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
  border-radius: 8px;
}

.ant-page-header {
  background: #fff;
  padding: 16px 24px;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  color: #262626;
  font-weight: 500;
}

:deep(.ant-tabs-tab) {
  font-weight: 500;
}

:deep(.ant-tabs-card .ant-tabs-content) {
  margin-top: 0;
}

.config-section,
.menu-section {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
}

/* 移动端优化 */
@media (max-width: 768px) {
  .system-content {
    padding: 12px;
  }
  
  .section-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  :deep(.ant-col) {
    margin-bottom: 16px;
  }
  
  :deep(.ant-statistic-title) {
    font-size: 12px;
  }
  
  :deep(.ant-statistic-content-value) {
    font-size: 20px;
  }
}
</style>
