<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="publish-proxy">
        <div class="page-card">
          <el-form :model="publishProxy" label-width="150px">
            <el-form-item label="神龙产品Key">
              <el-input v-model="publishProxy.productKey" placeholder="填写神龙产品Key" style="width: 100%" />
              <span class="form-tip">发布时使用该 Key 调用神龙代理获取对应地区的IP</span>
            </el-form-item>

            <el-form-item label="签名">
              <el-input v-model="publishProxy.signature" type="password" show-password placeholder="填写签名" style="width: 100%" />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="savePublishProxy">保存配置</el-button>
              <el-button @click="loadPublishProxy">刷新</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>

      <el-tab-pane label="Python 服务" name="python-service">
        <div class="page-card">
          <el-form :model="pythonService" label-width="150px">
            <el-form-item label="服务地址">
              <el-input v-model="pythonService.url" placeholder="例如：http://localhost:5005" style="width: 100%" />
              <span class="form-tip">留空则使用服务端环境变量/默认值（http://localhost:5005）</span>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="savePythonService">保存配置</el-button>
              <el-button @click="loadPythonService">刷新</el-button>
              <el-button @click="checkPythonService" :loading="checkingPython">测试连接</el-button>
            </el-form-item>
          </el-form>

          <div v-if="pythonCheckResult" style="margin-top: 12px;">
            <el-alert
              :type="pythonCheckResult.ok ? 'success' : 'error'"
              :title="pythonCheckResult.ok ? '连接成功' : '连接失败'"
              :description="pythonCheckResult.ok ? `HTTP ${pythonCheckResult.status || ''}` : (pythonCheckResult.error || '请求失败')"
              show-icon
            />
          </div>
        </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-dialog
          v-model="showAddUserDialog"
          title="新增用户"
          width="480px"
          @closed="resetUserForm"
        >
          <el-form :model="userForm" :rules="userFormRules" ref="userFormRef" label-width="80px">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userForm.username" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="userForm.password" type="password" show-password placeholder="请输入密码" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" placeholder="请输入邮箱（可选）" />
            </el-form-item>
            <el-form-item label="角色" prop="role">
              <el-select v-model="userForm.role" style="width: 100%">
                <el-option label="运营" value="operator" />
                <el-option label="编辑" value="editor" />
                <el-option label="管理员" value="admin" />
              </el-select>
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="showAddUserDialog = false">取消</el-button>
            <el-button type="primary" @click="handleAddUser" :loading="addingUser">确定</el-button>
          </template>
        </el-dialog>
      </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, type FormInstance, type FormRules } 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 publishProxy = reactive({
  productKey: '',
  signature: '',
});

const pythonService = reactive({
  url: '',
});

const checkingPython = ref(false);
const pythonCheckResult = ref<any | null>(null);

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

const userForm = reactive({
  username: '',
  password: '',
  email: '',
  role: 'operator',
});

const userFormRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 50, message: '用户名长度为3-50个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6个字符', trigger: 'blur' },
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' },
  ],
};

function resetUserForm() {
  userForm.username = '';
  userForm.password = '';
  userForm.email = '';
  userForm.role = 'operator';
  userFormRef.value?.resetFields();
}

async function handleAddUser() {
  if (!userFormRef.value) return;
  const valid = await userFormRef.value.validate().catch(() => false);
  if (!valid) return;

  addingUser.value = true;
  try {
    await request.post('/api/users', {
      username: userForm.username,
      password: userForm.password,
      email: userForm.email || undefined,
      role: userForm.role,
    });
    ElMessage.success('用户创建成功');
    showAddUserDialog.value = false;
    loadUsers();
  } catch {
    // 错误已由拦截器处理
  } finally {
    addingUser.value = 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 loadPublishProxy() {
  try {
    const config = await request.get('/api/system/publish-proxy');
    publishProxy.productKey = String(config.productKey || '');
    publishProxy.signature = String(config.signature || '');
  } catch {
    // 错误已处理
  }
}

async function savePublishProxy() {
  try {
    await request.put('/api/system/publish-proxy', {
      productKey: publishProxy.productKey,
      signature: publishProxy.signature,
    });
    ElMessage.success('发布代理配置已保存');
    loadPublishProxy();
  } catch {
    // 错误已处理
  }
}

async function loadPythonService() {
  try {
    const config = await request.get('/api/system/python-service');
    pythonService.url = String(config.url || '');
  } catch {
    // 错误已处理
  }
}

async function savePythonService() {
  try {
    await request.put('/api/system/python-service', {
      url: pythonService.url,
    });
    ElMessage.success('Python 服务配置已保存');
    loadPythonService();
  } catch {
    // 错误已处理
  }
}

async function checkPythonService() {
  checkingPython.value = true;
  pythonCheckResult.value = null;
  try {
    const result = await request.post('/api/system/python-service/check', {
      url: pythonService.url || undefined,
    });
    pythonCheckResult.value = result;
    if (result.ok) {
      ElMessage.success('连接成功');
    } else {
      ElMessage.error('连接失败');
    }
  } catch {
    pythonCheckResult.value = { ok: false, error: '请求失败' };
    ElMessage.error('连接失败');
  } finally {
    checkingPython.value = false;
  }
}

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();
  loadPublishProxy();
  loadPythonService();
  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>
