<template>
  <section>
    <header class="page-head">
      <div>
        <h2>系统设置</h2>
        <p>调整会影响正式服务运行的后台参数。</p>
      </div>
      <el-button @click="loadSettings">刷新</el-button>
    </header>

    <el-card class="panel" shadow="never">
      <div class="setting-head">
        <div>
          <h3>PDF 生成并发限制</h3>
          <p>限制同时生成证书 PDF 的数量。2核4G服务器建议保持默认值 2。</p>
        </div>
        <el-tag type="info">默认 2</el-tag>
      </div>

      <el-form class="settings-form" label-position="top">
        <el-form-item label="同时生成 PDF 数量">
          <el-input-number v-model="form.pdf_generation_concurrency_limit" :min="1" :max="10" :step="1" />
          <div class="form-tip">
            缓存命中的 PDF 下载不占用生成名额；首次生成会排队等待，前台会显示生成中提示。
          </div>
        </el-form-item>
        <el-button type="primary" :loading="saving" @click="saveSettings">保存设置</el-button>
      </el-form>
    </el-card>
  </section>
</template>

<script setup lang="ts">
import { ElMessage } from "element-plus";
import { onMounted, reactive, ref } from "vue";

import { http, type PdfSettings } from "../api";

const saving = ref(false);
const form = reactive({
  pdf_generation_concurrency_limit: 2,
});

async function loadSettings() {
  const { data } = await http.get<PdfSettings>("/admin/settings/pdf");
  form.pdf_generation_concurrency_limit = data.pdf_generation_concurrency_limit;
}

async function saveSettings() {
  saving.value = true;
  try {
    const { data } = await http.put<PdfSettings>("/admin/settings/pdf", {
      pdf_generation_concurrency_limit: form.pdf_generation_concurrency_limit,
    });
    form.pdf_generation_concurrency_limit = data.pdf_generation_concurrency_limit;
    ElMessage.success("系统设置已保存");
  } finally {
    saving.value = false;
  }
}

onMounted(loadSettings);
</script>

<style scoped>
.page-head {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
  margin-bottom: 16px;
}

.page-head p,
.setting-head p {
  margin: 6px 0 0;
  color: #64748b;
}

.panel {
  border-radius: 8px;
}

.setting-head {
  display: flex;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 18px;
}

.setting-head h3 {
  margin: 0;
  font-size: 18px;
}

.settings-form {
  max-width: 520px;
}

.form-tip {
  margin-top: 8px;
  color: #64748b;
  font-size: 13px;
  line-height: 1.7;
}

@media (max-width: 900px) {
  .page-head,
  .setting-head {
    align-items: stretch;
    flex-direction: column;
  }
}
</style>
