<template>
  <div class="server-config-container">
    <!-- 顶部可拖动标题栏 -->
    <div class="drag-region">
      <div class="window-controls">
        <button class="window-btn minimize" @click="handleMinimize" title="最小化">
          <svg viewBox="0 0 12 12"><rect y="5" width="12" height="2" fill="currentColor"/></svg>
        </button>
        <button class="window-btn maximize" @click="handleMaximize" :title="isMaximized ? '还原' : '最大化'">
          <svg v-if="isMaximized" viewBox="0 0 12 12">
            <rect x="1.5" y="3" width="7" height="7" stroke="currentColor" stroke-width="1.5" fill="none"/>
            <path d="M3.5 3V1.5H11V9H9.5" stroke="currentColor" stroke-width="1.5" fill="none"/>
          </svg>
          <svg v-else viewBox="0 0 12 12">
            <rect x="1" y="1" width="10" height="10" stroke="currentColor" stroke-width="1.5" fill="none"/>
          </svg>
        </button>
        <button class="window-btn close" @click="handleClose" title="关闭">
          <svg viewBox="0 0 12 12">
            <path d="M1 1L11 11M1 11L11 1" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
          </svg>
        </button>
      </div>
    </div>
    
    <!-- 背景装饰 -->
    <div class="bg-decoration">
      <div class="circle circle-1"></div>
      <div class="circle circle-2"></div>
      <div class="circle circle-3"></div>
    </div>
    
    <div class="config-card">
      <div class="config-header">
        <div class="logo">
          <el-icon><Setting /></el-icon>
        </div>
        <h1>服务器配置</h1>
        <p>配置后端服务器地址以连接系统</p>
      </div>
      
      <!-- 服务器列表 -->
      <div class="server-list" v-if="serverStore.servers.length > 0">
        <div
          v-for="server in serverStore.servers"
          :key="server.id"
          class="server-item"
          :class="{ active: server.id === serverStore.currentServerId }"
          @click="selectServer(server.id)"
        >
          <div class="server-info">
            <div class="server-name">{{ server.name }}</div>
            <div class="server-url">{{ server.url }}</div>
          </div>
          <div class="server-actions">
            <el-tag v-if="server.id === serverStore.currentServerId" type="success" size="small">
              当前使用
            </el-tag>
            <el-button
              type="danger"
              link
              size="small"
              @click.stop="deleteServer(server.id)"
            >
              删除
            </el-button>
          </div>
        </div>
      </div>
      
      <el-divider v-if="serverStore.servers.length > 0" />
      
      <!-- 添加服务器表单 -->
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-position="top"
        class="config-form"
      >
        <el-form-item label="服务器名称" prop="name">
          <el-input 
            v-model="form.name" 
            placeholder="例如：本地服务器" 
            size="large"
            :prefix-icon="Connection"
          />
        </el-form-item>
        
        <el-form-item label="服务器地址" prop="url">
          <div class="url-input-row">
            <el-input 
              v-model="form.url" 
              placeholder="例如：http://localhost:3000" 
              size="large"
              :prefix-icon="Link"
            />
            <el-button @click="testConnection" :loading="testing" class="test-btn">
              测试连接
            </el-button>
          </div>
        </el-form-item>
        
        <el-form-item class="checkbox-row">
          <el-checkbox v-model="form.isDefault">设为默认服务器</el-checkbox>
        </el-form-item>
        
        <el-form-item class="action-row">
          <el-button type="primary" @click="addServer" :loading="loading" class="primary-btn">
            添加服务器
          </el-button>
          <el-button v-if="serverStore.isConfigured" @click="goBack" class="back-btn">
            返回
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="connection-status" v-if="connectionResult !== null">
        <el-alert
          :type="connectionResult ? 'success' : 'error'"
          :title="connectionResult ? '连接成功' : '连接失败'"
          :description="connectionResult ? '服务器响应正常' : '无法连接到服务器，请检查地址是否正确'"
          show-icon
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Setting, Connection, Link } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { useServerStore } from '@/stores/server';
import { useAuthStore } from '@/stores/auth';

const router = useRouter();
const serverStore = useServerStore();
const authStore = useAuthStore();

const formRef = ref<FormInstance>();
const loading = ref(false);
const testing = ref(false);
const connectionResult = ref<boolean | null>(null);
const isMaximized = ref(false);

// 窗口控制
function handleMinimize() {
  window.electronAPI?.minimizeWindow?.();
}

function handleMaximize() {
  window.electronAPI?.maximizeWindow?.();
}

function handleClose() {
  window.electronAPI?.closeWindow?.();
}

// 监听窗口最大化状态
onMounted(async () => {
  if (window.electronAPI?.isMaximized) {
    isMaximized.value = await window.electronAPI.isMaximized();
  }
  window.electronAPI?.onMaximizedChange?.((maximized: boolean) => {
    isMaximized.value = maximized;
  });
});

const form = reactive({
  name: '',
  url: '',
  isDefault: true,
});

const rules: FormRules = {
  name: [{ required: true, message: '请输入服务器名称', trigger: 'blur' }],
  url: [
    { required: true, message: '请输入服务器地址', trigger: 'blur' },
    { pattern: /^https?:\/\/.+/, message: '请输入有效的 URL', trigger: 'blur' },
  ],
};

async function testConnection() {
  if (!form.url) {
    ElMessage.warning('请先输入服务器地址');
    return;
  }
  
  testing.value = true;
  connectionResult.value = null;
  
  try {
    const result = await serverStore.checkConnection(form.url);
    connectionResult.value = result;
    if (result) {
      ElMessage.success('连接成功');
    } else {
      ElMessage.error('连接失败');
    }
  } catch {
    connectionResult.value = false;
    ElMessage.error('连接失败');
  } finally {
    testing.value = false;
  }
}

async function addServer() {
  if (!formRef.value) return;
  
  const valid = await formRef.value.validate().catch(() => false);
  if (!valid) return;
  
  loading.value = true;
  try {
    // 先测试连接
    const connected = await serverStore.checkConnection(form.url);
    if (!connected) {
      ElMessage.warning('服务器连接失败，仍要添加吗？');
    }
    
    serverStore.addServer({
      name: form.name,
      url: form.url.replace(/\/$/, ''), // 移除末尾斜杠
      isDefault: form.isDefault,
    });
    
    ElMessage.success('服务器添加成功');
    
    // 清空表单
    form.name = '';
    form.url = '';
    form.isDefault = false;
    connectionResult.value = null;
    
    // 如果已登录且切换了服务器，清除登录状态
    if (authStore.isAuthenticated) {
      authStore.clearTokens();
    }
  } finally {
    loading.value = false;
  }
}

function selectServer(id: string) {
  if (id === serverStore.currentServerId) return;
  
  serverStore.setCurrentServer(id);
  // 切换服务器后清除登录状态
  authStore.clearTokens();
  ElMessage.success('已切换服务器');
}

async function deleteServer(id: string) {
  try {
    await ElMessageBox.confirm('确定要删除这个服务器配置吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    serverStore.removeServer(id);
    ElMessage.success('已删除');
  } catch {
    // 取消
  }
}

function goBack() {
  if (authStore.isAuthenticated) {
    router.push('/');
  } else {
    router.push('/login');
  }
}
</script>

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

.server-config-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8eb 100%);
  position: relative;
  overflow: hidden;
  padding: 20px;
}

// 顶部可拖动区域
.drag-region {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 32px;
  -webkit-app-region: drag;
  z-index: 999;
}

// 窗口控制按钮
.window-controls {
  position: absolute;
  top: 0;
  right: 0;
  display: flex;
  -webkit-app-region: no-drag;
  
  .window-btn {
    width: 46px;
    height: 32px;
    border: none;
    background: transparent;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: background 0.15s;
    color: $text-secondary;
    
    svg {
      width: 12px;
      height: 12px;
    }
    
    &:hover {
      background: rgba(0, 0, 0, 0.06);
    }
    
    &.close:hover {
      background: #e81123;
      color: #fff;
    }
  }
}

// 背景装饰
.bg-decoration {
  position: absolute;
  inset: 0;
  overflow: hidden;
  pointer-events: none;
  
  .circle {
    position: absolute;
    border-radius: 50%;
    opacity: 0.5;
  }
  
  .circle-1 {
    width: 400px;
    height: 400px;
    background: linear-gradient(135deg, rgba(79, 140, 255, 0.2), rgba(79, 140, 255, 0.05));
    top: -100px;
    right: -100px;
  }
  
  .circle-2 {
    width: 300px;
    height: 300px;
    background: linear-gradient(135deg, rgba(250, 112, 154, 0.15), rgba(254, 225, 64, 0.1));
    bottom: -80px;
    left: -80px;
  }
  
  .circle-3 {
    width: 200px;
    height: 200px;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.15), rgba(118, 75, 162, 0.1));
    top: 50%;
    left: 10%;
    transform: translateY(-50%);
  }
}

.config-card {
  width: 480px;
  max-width: 100%;
  padding: 48px 40px;
  background: #fff;
  border-radius: $radius-xl;
  box-shadow: $shadow-lg;
  position: relative;
  z-index: 1;
  border: 1px solid rgba(255, 255, 255, 0.8);
}

.config-header {
  text-align: center;
  margin-bottom: 32px;
  
  .logo {
    width: 64px;
    height: 64px;
    margin: 0 auto 20px;
    border-radius: $radius-lg;
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 8px 24px rgba(79, 172, 254, 0.3);
    
    .el-icon {
      font-size: 32px;
      color: #fff;
    }
  }
  
  h1 {
    margin: 0 0 12px;
    font-size: 24px;
    font-weight: 700;
    color: $text-primary;
  }
  
  p {
    margin: 0;
    color: $text-secondary;
    font-size: 14px;
  }
}

.server-list {
  margin-bottom: 16px;
  
  .server-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 14px 18px;
    border: 1px solid $border-light;
    border-radius: $radius-base;
    margin-bottom: 10px;
    cursor: pointer;
    transition: all 0.2s;
    background: $bg-light;
    
    &:hover {
      border-color: $primary-color;
      background: #fff;
    }
    
    &.active {
      border-color: $primary-color;
      background: rgba($primary-color, 0.05);
      box-shadow: 0 0 0 3px rgba($primary-color, 0.08);
    }
    
    .server-info {
      .server-name {
        font-weight: 600;
        color: $text-primary;
        font-size: 15px;
      }
      
      .server-url {
        font-size: 12px;
        color: $text-secondary;
        margin-top: 4px;
      }
    }
    
    .server-actions {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }
}

.config-form {
  :deep(.el-form-item__label) {
    font-weight: 500;
    color: $text-primary;
  }
  
  :deep(.el-input__wrapper) {
    border-radius: $radius-base;
    box-shadow: 0 0 0 1px $border-light inset;
    transition: all 0.2s;
    
    &:hover {
      box-shadow: 0 0 0 1px $primary-color inset;
    }
    
    &.is-focus {
      box-shadow: 0 0 0 1px $primary-color inset, 0 0 0 3px rgba($primary-color, 0.1);
    }
  }
  
  :deep(.el-input__inner) {
    height: 44px;
    font-size: 15px;
  }
  
  :deep(.el-input__prefix) {
    color: $text-secondary;
  }
  
  // URL输入行样式
  .url-input-row {
    display: flex;
    gap: 12px;
    width: 100%;
    
    .el-input {
      flex: 1;
    }
    
    .test-btn {
      height: 44px;
      padding: 0 20px;
      border-radius: $radius-base;
      background: $bg-base;
      border: 1px solid $border-light;
      color: $primary-color;
      font-weight: 500;
      white-space: nowrap;
      
      &:hover {
        background: $primary-color-light;
        border-color: $primary-color;
      }
    }
  }
  
  .checkbox-row {
    margin-bottom: 24px;
    
    :deep(.el-checkbox__label) {
      color: $text-secondary;
    }
  }
  
  .action-row {
    margin-bottom: 0;
    
    .primary-btn {
      height: 44px;
      padding: 0 28px;
      font-size: 15px;
      font-weight: 600;
      border-radius: $radius-base;
      background: linear-gradient(135deg, $primary-color 0%, #3a7bd5 100%);
      border: none;
      box-shadow: 0 4px 16px rgba($primary-color, 0.3);
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 6px 20px rgba($primary-color, 0.4);
      }
      
      &:active {
        transform: translateY(0);
      }
    }
    
    .back-btn {
      height: 44px;
      padding: 0 28px;
      font-size: 15px;
      font-weight: 500;
      border-radius: $radius-base;
      border: 1px solid $border-base;
      background: #fff;
      color: $text-regular;
      transition: all 0.2s;
      
      &:hover {
        border-color: $primary-color;
        color: $primary-color;
      }
    }
  }
}

:deep(.el-divider) {
  margin: 24px 0;
  border-color: $border-lighter;
}

.connection-status {
  margin-top: 20px;
  
  :deep(.el-alert) {
    border-radius: $radius-base;
  }
}
</style>
