<% @page_title = '配置 - 清巡' %>
<% @active_page = 'config' %>

<style>
  .config-page .card {
    max-width: 800px;
    margin: 0 auto;
  }
  .config-page .card-body {
    padding: 60px 70px;
  }
  .config-page .card-header {
    padding: 24px 70px;
  }
  .config-page .form-group {
    margin-bottom: 50px;
  }
  .config-page .form-label {
    display: block;
    font-size: 16px;
    font-weight: 600;
    color: #606266;
    margin-bottom: 18px;
  }
  .config-page .form-input {
    width: 100%;
    padding: 18px 22px;
    font-size: 16px;
    border: 1px solid #dcdfe6;
    border-radius: 12px;
    transition: all 0.2s;
    outline: none;
    line-height: 1.8;
  }
  .config-page .form-input:focus {
    border-color: #409eff;
    box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
  }
  .config-page .form-input::placeholder {
    color: #c0c4cc;
  }
  .config-page .form-input--api-token {
    width: 100%;
    padding: 40px 24px;
    font-size: 15px;
    font-family: monospace;
    min-height: 100px;
  }
  .config-page .button-group {
    display: flex;
    gap: 20px;
    margin-top: 60px;
    flex-wrap: wrap;
  }
  .config-page .button-group .el-button {
    flex: 1;
    min-width: 160px;
    padding: 18px 28px;
    font-size: 16px;
    border-radius: 12px;
    height: 58px;
  }
  .config-page .section-header {
    display: flex;
    align-items: center;
    gap: 14px;
  }
  .config-page .section-header i {
    font-size: 22px;
    color: #409eff;
  }
  .config-page .section-header h2 {
    font-size: 20px;
    font-weight: 600;
    color: #303133;
    margin: 0;
  }
  .config-page .tip-text {
    font-size: 14px;
    color: #909399;
    margin-top: 16px;
    line-height: 1.8;
  }
  .config-page .page-header {
    margin-bottom: 40px;
  }
  .config-page .page-header h1 {
    font-size: 32px;
  }
  .config-page .main-content {
    padding: 40px;
  }
</style>

<div id="app" class="config-page">
  <div class="app-wrapper">

    <main class="main-content">
      <div class="page-header">
        <h1>配置</h1>
      </div>

      <el-card class="card">
        <template #header>
          <div class="card-header section-header">
            <i class="el-icon-setting"></i>
            <h2>云端连接设置</h2>
          </div>
        </template>
        <div class="card-body">
          <div id="messages"></div>

          <form id="config-form" method="post">
            <div class="form-group">
              <label class="form-label" for="api_token">API 令牌 </label>
              <input type="text" id="api_token" name="api_token" class="form-input form-input--api-token" placeholder="请输入 API 令牌" value="<%= Rack::Utils.escape_html(@api_token) %>" required style="height:30px;width: 80%;font-size: 15px;padding-left: 10px;">
              <p class="tip-text">在云端服务中生成的 API 访问令牌，用于身份验证<br>获取方式：云端 → 账户设置 → API令牌，拷贝到此处</p>
            </div>
            <br>
            <div class="form-group">
              <label class="form-label" for="cloud_url">云端地址 </label>
              <input type="text" id="cloud_url" name="cloud_url" class="form-input" placeholder="http://localhost:3000" value="<%= Rack::Utils.escape_html(@cloud_url) %>" required style="height:30px;width: 80%;font-size: 15px;padding-left: 10px;">
              <p class="tip-text">云端服务的完整 URL 地址，例如：https://api.example.com</p>
            </div>
            <br>
            <div class="button-group">
              <el-button type="primary" native-type="submit">保存配置</el-button>
              <el-button type="success" :loading="testLoading" @click.prevent="testConnection">测试连接</el-button>
              <el-button type="danger" id="reset-btn">重置配置</el-button>
            </div>
          </form>

          <form id="reset-form" method="post" action="/reset-config" style="display: none;"></form>
        </div>
      </el-card>
    </main>
  </div>
</div>

  <% content_for :xxx do %>
  <script>
    // 初始化 Vue 应用
    const { createApp, ref } = Vue;
    const app = createApp({
      setup() {
        const testLoading = ref(false);

        const testConnection = async () => {
          const apiToken = document.getElementById('api_token').value.trim();
          const cloudUrl = document.getElementById('cloud_url').value.trim();

          if (!apiToken) {
            ElementPlus.ElMessage.error('请先输入 API 令牌');
            return;
          }

          testLoading.value = true;

          try {
            const response = await fetch('/api/test-connection', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
              },
              body: new URLSearchParams({
                api_token: apiToken,
                cloud_url: cloudUrl
              })
            });

            const result = await response.json();

            if (result.success) {
              ElementPlus.ElMessage.success({
                message: result.message || '连接测试成功！',
                duration: 5000
              });

              // 如果有数据，显示更多详细信息
              if (result.data) {
                let detail = '连接详情：\n';
                if (result.data.server) {
                  detail += `• 服务器版本: ${result.data.server.version}\n`;
                }
                if (result.data.user) {
                  detail += `• 用户邮箱: ${result.data.user.email}\n`;
                  if (result.data.user.subscription_tier) {
                    detail += `• 订阅套餐: ${result.data.user.subscription_tier}\n`;
                  }
                }
                console.log(detail);
              }
            } else {
              ElementPlus.ElMessage.error({
                message: result.message || '连接测试失败',
                duration: 8000
              });
            }
          } catch (error) {
            ElementPlus.ElMessage.error({
              message: '请求失败: ' + error.message,
              duration: 8000
            });
          } finally {
            testLoading.value = false;
          }
        };

        return {
          testLoading,
          testConnection
        };
      }
    });

    app.use(ElementPlus);

    app.mount('#app');

    // 等待 DOM 加载完成
    document.addEventListener('DOMContentLoaded', function() {
      // 重置按钮
      const resetBtn = document.getElementById('reset-btn');
      if (resetBtn) {
        resetBtn.addEventListener('click', function() {
          if (confirm('确定要重置配置吗？')) {
            document.getElementById('reset-form').submit();
          }
        });
      }

      // 检查 URL 参数中的消息
      const urlParams = new URLSearchParams(window.location.search);
      const error = urlParams.get('error');
      const notice = urlParams.get('notice');

      if (error) {
        ElementPlus.ElMessage.error(decodeURIComponent(error));
      }
      if (notice) {
        ElementPlus.ElMessage.success(decodeURIComponent(notice));
      }
    });
  </script>
<% end %>