<template>
  <div class="settings-page">
    <h2>系统设置</h2>
    
    <el-tabs v-model="activeTab">
      <el-tab-pane label="基础设置" name="basic">
        <div class="page-card">
          <el-form :model="settings" label-width="150px">
            <el-form-item label="开放注册">
              <el-switch v-model="settings.allowRegistration" />
              <span class="form-tip">允许新用户自行注册账号</span>
            </el-form-item>
            
            <el-form-item label="默认用户角色">
              <el-select v-model="settings.defaultUserRole" style="width: 200px">
                <el-option label="运营" value="operator" />
                <el-option label="编辑" value="editor" />
                <el-option label="管理员" value="admin" />
              </el-select>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="saveSettings">保存设置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="用户管理" name="users">
        <div class="page-card">
          <div class="table-header">
            <el-button type="primary" @click="showAddUserDialog = true">
              添加用户
            </el-button>
          </div>
          
          <el-table :data="users" v-loading="loadingUsers">
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="email" label="邮箱" />
            <el-table-column prop="role" label="角色" width="100">
              <template #default="{ row }">
                <el-tag>{{ getRoleText(row.role) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
                  {{ row.status === 'active' ? '正常' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="{ row }">
                <el-button type="primary" link size="small" @click="editUser(row)">
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  link
                  size="small"
                  @click="deleteUser(row.id)"
                  :disabled="row.id === authStore.user?.id"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="系统状态" name="status">
        <div class="page-card">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="数据库">
              <el-tag :type="systemStatus.database === 'connected' ? 'success' : 'danger'">
                {{ systemStatus.database === 'connected' ? '已连接' : '未连接' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="Redis">
              <el-tag :type="systemStatus.redis === 'connected' ? 'success' : 'danger'">
                {{ systemStatus.redis === 'connected' ? '已连接' : '未连接' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="在线用户">{{ systemStatus.onlineUsers }}</el-descriptions-item>
            <el-descriptions-item label="总用户数">{{ systemStatus.totalUsers }}</el-descriptions-item>
            <el-descriptions-item label="平台账号数">{{ systemStatus.totalAccounts }}</el-descriptions-item>
            <el-descriptions-item label="发布任务数">{{ systemStatus.totalTasks }}</el-descriptions-item>
            <el-descriptions-item label="运行时间">{{ formatUptime(systemStatus.uptime) }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import request from '@/api/request';
import { useAuthStore } from '@/stores/auth';
import type { User } from '@media-manager/shared';

const authStore = useAuthStore();
const activeTab = ref('basic');
const loadingUsers = ref(false);

const settings = reactive({
  allowRegistration: false,
  defaultUserRole: 'operator',
});

const users = ref<User[]>([]);
const showAddUserDialog = ref(false);

const systemStatus = reactive({
  database: 'disconnected',
  redis: 'disconnected',
  onlineUsers: 0,
  totalUsers: 0,
  totalAccounts: 0,
  totalTasks: 0,
  uptime: 0,
});

function getRoleText(role: string) {
  const texts: Record<string, string> = {
    admin: '管理员',
    editor: '编辑',
    operator: '运营',
  };
  return texts[role] || role;
}

function formatUptime(seconds: number) {
  const days = Math.floor(seconds / 86400);
  const hours = Math.floor((seconds % 86400) / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  return `${days}天 ${hours}小时 ${minutes}分钟`;
}

async function loadSettings() {
  try {
    const config = await request.get('/api/system/config');
    settings.allowRegistration = config.allowRegistration;
    settings.defaultUserRole = config.defaultUserRole;
  } catch {
    // 错误已处理
  }
}

async function saveSettings() {
  try {
    await request.put('/api/system/config', settings);
    ElMessage.success('设置已保存');
  } catch {
    // 错误已处理
  }
}

async function loadUsers() {
  loadingUsers.value = true;
  try {
    const result = await request.get('/api/users');
    users.value = result.items;
  } catch {
    // 错误已处理
  } finally {
    loadingUsers.value = false;
  }
}

async function loadSystemStatus() {
  try {
    const status = await request.get('/api/system/status');
    Object.assign(systemStatus, status);
  } catch {
    // 错误已处理
  }
}

function editUser(user: User) {
  ElMessage.info('编辑功能开发中');
}

async function deleteUser(id: number) {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗？', '提示', { type: 'warning' });
    await request.delete(`/api/users/${id}`);
    ElMessage.success('删除成功');
    loadUsers();
  } catch {
    // 取消或错误
  }
}

onMounted(() => {
  loadSettings();
  loadUsers();
  loadSystemStatus();
});
</script>

<style lang="scss" scoped>
@use '@/styles/variables.scss' as *;

h2 {
  margin: 0 0 20px;
}

.table-header {
  margin-bottom: 16px;
}

.form-tip {
  margin-left: 12px;
  color: $text-secondary;
  font-size: 13px;
}
</style>
