<template>
  <div class="page-container">
    <h1>系统配置</h1>
    <el-alert
      title="所有配置项默认折叠，请点击标题展开。修改后，请务必点击页面底部的“保存所有配置”按钮以生效。"
      type-info
      show-icon
      :closable="false"
      style="margin-bottom: 20px;"
    />

    <!-- 使用 el-form 组件包裹所有配置项 -->
    <el-form :model="configForm" label-width="120px" label-position="right">
      <!-- 使用 el-collapse 实现折叠面板效果 -->
      <el-collapse v-model="activeCollapseNames">

        <!-- 基础配置 -->
        <el-collapse-item name="1">
          <template #title>
            <span class="collapse-title">基础配置</span>
          </template>
          <el-form-item label="豆瓣 Cookie">
            <el-input 
              v-model="configForm.douban.cookie" 
              type="textarea"
              :rows="5"
              placeholder="请输入从豆瓣网站获取的完整 Cookie，用于刮削影视信息"
            />
          </el-form-item>
          <!-- 动态增减的本地短剧路径 -->
          <el-form-item
            v-for="(pathItem, index) in configForm.skit_paths"
            :key="pathItem.id"
            :label="index === 0 ? '本地短剧路径' : ''"
            :class="{ 'extra-path-item': index > 0 }"
          >
            <div class="path-input-row">
              <el-input v-model="pathItem.path" placeholder="例如: /skits" />
              <el-button
                @click="removePath(index)"
                :icon="'Delete'"
                type="danger"
                circle
                v-if="configForm.skit_paths.length > 1"
                class="remove-button"
              />
            </div>
            <el-text v-if="index === 0" class="input-tip" type="info">
              重要：此处应填写 Docker 容器内的路径，例如 /skits，而不是宿主机的路径。
            </el-text>
          </el-form-item>
          <el-form-item>
             <el-button @click="addPath" type="primary" :icon="'Plus'" text>
              添加更多路径
            </el-button>
          </el-form-item>
        </el-collapse-item>

        <!-- 站点配置 -->
        <el-collapse-item name="2">
          <template #title>
            <span class="collapse-title">PTSKIT 站点配置</span>
          </template>
          <el-form-item label="站点 URL"><el-input v-model="configForm.ptskit.url" placeholder="例如: https://pt.skit.com" /></el-form-item>
          <el-form-item label="站点 Cookie"><el-input v-model="configForm.ptskit.cookie" type="textarea" :rows="5" placeholder="请输入登录 PTSKIT 站点后获取的完整 Cookie" /></el-form-item>
          <el-form-item label="User-Agent">
            <el-input v-model="configForm.ptskit.user_agent" placeholder="可选，留空则使用默认值" />
            <el-text class="input-tip" type="info">模拟浏览器访问的 User-Agent，一般无需填写。</el-text>
          </el-form-item>
          <el-button type="primary" :loading="testLoading.ptskit" @click="handleTestConnection('ptskit')">测试连接</el-button>
        </el-collapse-item>

        <!-- 下载器配置 -->
        <el-collapse-item name="3">
          <template #title>
            <span class="collapse-title">下载器配置</span>
          </template>
          <el-tabs v-model="activeDownloaderTab" style="margin-top: -10px;">
            <!-- qBittorrent 配置 -->
            <el-tab-pane label="qBittorrent" name="qb">
              <el-row :gutter="20">
                <el-col :span="12"><el-form-item label="IP / 主机名"><el-input v-model="configForm.qbittorrent.host" placeholder="例如: 192.168.1.10" /></el-form-item></el-col>
                <el-col :span="12"><el-form-item label="端口"><el-input v-model.number="configForm.qbittorrent.port" placeholder="例如: 8080" /></el-form-item></el-col>
                <el-col :span="12"><el-form-item label="用户名"><el-input v-model="configForm.qbittorrent.username" placeholder="请输入用户名" /></el-form-item></el-col>
                <el-col :span="12"><el-form-item label="密码"><el-input v-model="configForm.qbittorrent.password" type="password" placeholder="请输入密码" show-password /></el-form-item></el-col>
              </el-row>
              <el-button type="primary" :loading="testLoading.qb" @click="handleTestConnection('qb')">测试连接</el-button>
            </el-tab-pane>
            <!-- Transmission 配置 -->
            <el-tab-pane label="Transmission" name="tr">
              <el-row :gutter="20">
                <el-col :span="12"><el-form-item label="IP / 主机名"><el-input v-model="configForm.transmission.host" placeholder="例如: 192.168.1.11" /></el-form-item></el-col>
                <el-col :span="12"><el-form-item label="端口"><el-input v-model.number="configForm.transmission.port" placeholder="例如: 9091" /></el-form-item></el-col>
                <el-col :span="12"><el-form-item label="用户名"><el-input v-model="configForm.transmission.username" placeholder="可选" /></el-form-item></el-col>
                <el-col :span="12"><el-form-item label="密码"><el-input v-model="configForm.transmission.password" type="password" placeholder="可选" show-password /></el-form-item></el-col>
              </el-row>
              <el-button type="primary" :loading="testLoading.tr" @click="handleTestConnection('tr')">测试连接</el-button>
            </el-tab-pane>
          </el-tabs>
        </el-collapse-item>

        <!-- 媒体服务器配置 -->
        <el-collapse-item name="4">
          <template #title>
            <span class="collapse-title">媒体服务器配置</span>
          </template>
          <el-tabs v-model="activeMediaServerTab" style="margin-top: -10px;">
            <!-- Emby 配置 -->
            <el-tab-pane label="Emby" name="emby">
              <el-form-item label="IP / 主机名"><el-input v-model="configForm.emby.host" placeholder="例如: emby.local" /></el-form-item>
              <el-form-item label="端口"><el-input v-model.number="configForm.emby.port" placeholder="例如: 8096" /></el-form-item>
              <el-form-item label="SSL"><el-switch v-model="configForm.emby.use_ssl" active-text="https" inactive-text="http" /></el-form-item>
              <el-form-item label="API 密钥"><el-input v-model="configForm.emby.api_key" type="password" placeholder="请输入 Emby API Key" show-password /></el-form-item>
              <el-button type="primary" :loading="testLoading.emby" @click="handleTestConnection('emby')">测试连接</el-button>
            </el-tab-pane>
            <!-- Plex 配置 -->
            <el-tab-pane label="Plex" name="plex">
              <el-form-item label="IP / 主机名"><el-input v-model="configForm.plex.host" placeholder="例如: 192.168.1.12" /></el-form-item>
              <el-form-item label="端口"><el-input v-model.number="configForm.plex.port" placeholder="例如: 32400" /></el-form-item>
              <el-form-item label="SSL"><el-switch v-model="configForm.plex.use_ssl" active-text="https" inactive-text="http" /></el-form-item>
              <el-form-item label="X-Plex-Token"><el-input v-model="configForm.plex.token" type="password" placeholder="请输入 Plex Token" show-password /></el-form-item>
              <el-button type="primary" :loading="testLoading.plex" @click="handleTestConnection('plex')">测试连接</el-button>
            </el-tab-pane>
            <!-- 飞牛影视 (Fnos) 配置 -->
            <el-tab-pane label="飞牛影视" name="fnos">
               <el-form-item label="IP / 主机名"><el-input v-model="configForm.fnos.host" placeholder="请输入 Fnos 服务地址" /></el-form-item>
               <el-form-item label="端口"><el-input v-model.number="configForm.fnos.port" placeholder="请输入 Fnos 服务端口" /></el-form-item>
               <el-form-item label="SSL"><el-switch v-model="configForm.fnos.use_ssl" active-text="https" inactive-text="http" /></el-form-item>
               <el-form-item label="Authorization"><el-input v-model="configForm.fnos.authorization" type="password" placeholder="请输入 Authorization" show-password /></el-form-item>
               <el-button type="primary" :loading="testLoading.fnos" @click="handleTestConnection('fnos')">测试连接</el-button>
            </el-tab-pane>
          </el-tabs>
        </el-collapse-item>

      </el-collapse>

      <!-- 页面底部全局操作 -->
      <div class="footer-actions">
        <el-button type="success" :icon="'Select'" size="large" :loading="saveLoading" @click="handleSaveConfig">
          保存所有配置
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import * as api from '../api';

// --- 响应式状态定义 ---

// 控制哪个折叠面板是展开的，空数组表示默认全部折叠
const activeCollapseNames = ref([]); 
const activeDownloaderTab = ref('qb');
const activeMediaServerTab = ref('emby');

// 表单数据模型
const configForm = ref({
  douban: { cookie: '' },
  // skit_paths 现在是一个对象数组，以便 v-for 绑定 key
  skit_paths: [{ id: Date.now(), path: '' }],
  ptskit: { url: '', cookie: '', user_agent: '' },
  qbittorrent: { host: '', port: null, username: '', password: '' },
  transmission: { host: '', port: null, username: '', password: '' },
  emby: { host: '', port: null, use_ssl: false, api_key: '' },
  plex: { host: '', port: null, use_ssl: false, token: '' },
  fnos: { host: '', port: null, use_ssl: false, authorization: '' },
});

// 加载状态
const saveLoading = ref(false);
const testLoading = reactive({
  ptskit: false, qb: false, tr: false, emby: false, plex: false, fnos: false
});

// --- 方法定义 ---

/**
 * @description 添加一个新的本地短剧路径输入框
 */
const addPath = () => {
  configForm.value.skit_paths.push({ id: Date.now(), path: '' });
};

/**
 * @description 移除指定索引的本地短剧路径
 * @param {number} index - 要移除的路径在数组中的索引
 */
const removePath = (index) => {
  if (configForm.value.skit_paths.length > 1) {
    configForm.value.skit_paths.splice(index, 1);
  }
};

/**
 * @description 从后端加载配置，并适配前端数据结构
 */
const loadConfig = async () => {
  try {
    const res = await api.getSystemConfig();
    if (!res) return;

    // 深层合并加载的配置，防止后端未返回某些字段时出错
    Object.keys(configForm.value).forEach(key => {
      if (key !== 'skit_paths' && res[key] !== undefined) {
        configForm.value[key] = { ...configForm.value[key], ...res[key] };
      }
    });

    // 特殊处理 skit_paths，将其从字符串数组转换为对象数组
    if (res.skit_paths && Array.isArray(res.skit_paths) && res.skit_paths.length > 0) {
      configForm.value.skit_paths = res.skit_paths.map(p => ({ id: Date.now() + Math.random(), path: p }));
    } else {
      // 如果没有路径，确保至少有一个空的输入框
      configForm.value.skit_paths = [{ id: Date.now(), path: '' }];
    }

  } catch (error) {
    console.error("加载配置失败:", error);
    ElMessage.error("配置加载失败，请刷新页面重试。");
  }
};

/**
 * @description 保存所有配置，发送前处理数据格式
 */
const handleSaveConfig = async () => {
  saveLoading.value = true;
  try {
    // 创建一个 payload 的深拷贝以进行修改
    const payload = JSON.parse(JSON.stringify(configForm.value));

    // 将 skit_paths 从对象数组转换回字符串数组，并过滤掉空值
    payload.skit_paths = payload.skit_paths
      .map(item => item.path.trim())
      .filter(path => path !== '');

    await api.saveSystemConfig(payload);
    ElMessage.success('配置已成功保存！');
  } catch(error) {
    console.error("保存配置失败:", error);
  } finally {
    saveLoading.value = false;
  }
};


const handleTestConnection = async (serviceType) => {
  if (!testLoading.hasOwnProperty(serviceType)) return;
  
  testLoading[serviceType] = true;
  try {
    let serviceConfig = {};
    if (serviceType === 'qb') serviceConfig = configForm.value.qbittorrent;
    else if (serviceType === 'tr') serviceConfig = configForm.value.transmission;
    else serviceConfig = configForm.value[serviceType];
    
    const res = await api.testConnection({ type: serviceType, config: serviceConfig });

    if (res.success) {
      ElMessage.success(`${res.message || '连接成功！'}`);
    } else {
      ElMessage.error(`${res.message || '连接失败，请检查配置。'}`);
    }
  } finally {
    testLoading[serviceType] = false;
  }
};

onMounted(() => {
  loadConfig();
});
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.collapse-title {
  font-size: 16px;
  font-weight: 500;
}

.el-collapse {
  border-top: none;
  border-bottom: none;
}

/* 优化折叠面板样式 */
:deep(.el-collapse-item__header) {
  border-bottom: 1px solid var(--el-border-color-lighter);
}
:deep(.el-collapse-item__wrap) {
  border-bottom: 1px solid var(--el-border-color-lighter);
}
:deep(.el-collapse-item__content) {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 18px;
}

/* 动态路径行的样式 */
.path-input-row {
  display: flex;
  align-items: center;
  width: 100%;
}

.remove-button {
  margin-left: 10px;
}

/* 让第二个及以后的路径输入框，其 label 区域为空，从而实现对齐 */
.extra-path-item {
  margin-bottom: 10px;
}
.extra-path-item :deep(.el-form-item__label) {
  visibility: hidden;
}

.input-tip {
  margin-top: 4px;
  font-size: 12px;
  line-height: 1.2;
}

.footer-actions {
  margin-top: 20px;
  text-align: center;
}
</style>
