<template>
  <div class="system-settings admin-theme">
    <AdminSidebar active="settings" />

    <!-- 主内容区域 -->
    <main class="main-content">
      <AdminHeader :title="$t('nav.systemSettings')" />

      <!-- 设置选项卡 -->
      <div class="settings-tabs">
        <div class="tab-nav">
          <div
            class="tab-item"
            :class="{ active: activeTab === 'membership' }"
            @click="activeTab = 'membership'"
          >
            <UserOutlined />
            <span>{{ $t('systemSettings.membership') }}</span>
          </div>
          <!-- 任务清理管理标签暂时隐藏 -->
          <div
            v-if="false"
            class="tab-item"
            :class="{ active: activeTab === 'cleanup' }"
            @click="activeTab = 'cleanup'"
          >
            <DeleteOutlined />
            <span>{{ $t('systemSettings.cleanup') }}</span>
          </div>
          <div
            class="tab-item"
            :class="{ active: activeTab === 'pointsCost' }"
            @click="activeTab = 'pointsCost'"
          >
            <ThunderboltOutlined />
            <span>{{ $t('systemSettings.pointsCostTitle') }}</span>
          </div>
          <div
            class="tab-item"
            :class="{ active: activeTab === 'aiModel' }"
            @click="activeTab = 'aiModel'"
          >
            <SettingOutlined />
            <span>{{ $t('systemSettings.aiModel') }}</span>
          </div>
        </div>

        <!-- 会员收费标准选项卡 -->
        <div v-if="activeTab === 'membership'" class="tab-content">
          <h2 class="page-title">{{ $t('systemSettings.membership') }}</h2>
          <div class="membership-cards">
            <a-card v-for="level in membershipLevels" :key="level.id" class="membership-card">
              <div class="card-header">
                <h3>{{ level.name }}</h3>
              </div>
              <div class="card-body">
                <p class="price">¥{{ Math.floor(level.price || 0) }}/{{ Math.floor((level.resourcePoints || level.pointsBonus || 0) / 30) }}{{ $t('subscription.items') }}</p>
                <p class="description">{{ level.resourcePoints || level.pointsBonus || 0 }}{{ $t('subscription.points') }}</p>
                <p class="validity">{{ formatDuration(level.durationDays) }}</p>
              </div>
              <div class="card-footer">
                <a-button type="primary" @click="editLevel(level)">{{ $t('common.edit') }}</a-button>
              </div>
            </a-card>
          </div>
        </div>

        <!-- 任务清理管理选项卡 -->
        <div v-if="activeTab === 'cleanup'" class="tab-content">
          <h2 class="page-title">{{ $t('systemSettings.cleanup') }}</h2>

          <!-- 清理统计信息 -->
          <div class="cleanup-stats">
            <a-card class="stats-card">
              <template #header>
                <div class="card-header">
                  <h3>{{ $t('systemSettings.cleanupStatsInfo') }}</h3>
                  <a-button type="primary" @click="refreshStats" :loading="loadingStats">
                    <ReloadOutlined />
                    {{ $t('systemSettings.refresh') }}
                  </a-button>
                </div>
              </template>
              <div class="stats-content" v-if="cleanupStats">
                <div class="stats-grid">
                  <div class="stat-item">
                    <div class="stat-label">{{ $t('systemSettings.currentTotalTasks') }}</div>
                    <div class="stat-value">{{ cleanupStats.currentTasks?.textToVideo?.total + cleanupStats.currentTasks?.imageToVideo?.total || 0 }}</div>
                  </div>
                  <div class="stat-item">
                    <div class="stat-label">{{ $t('systemSettings.completedTasks') }}</div>
                    <div class="stat-value">{{ cleanupStats.currentTasks?.textToVideo?.completed + cleanupStats.currentTasks?.imageToVideo?.completed || 0 }}</div>
                  </div>
                  <div class="stat-item">
                    <div class="stat-label">{{ $t('systemSettings.failedTasks') }}</div>
                    <div class="stat-value">{{ cleanupStats.currentTasks?.textToVideo?.failed + cleanupStats.currentTasks?.imageToVideo?.failed || 0 }}</div>
                  </div>
                  <div class="stat-item">
                    <div class="stat-label">{{ $t('systemSettings.archivedTasks') }}</div>
                    <div class="stat-value">{{ cleanupStats.archives?.completedTasks || 0 }}</div>
                  </div>
                  <div class="stat-item">
                    <div class="stat-label">{{ $t('systemSettings.cleanupLogsCount') }}</div>
                    <div class="stat-value">{{ cleanupStats.archives?.cleanupLogs || 0 }}</div>
                  </div>
                  <div class="stat-item">
                    <div class="stat-label">{{ $t('systemSettings.retentionDays') }}</div>
                    <div class="stat-value">{{ cleanupStats.config?.retentionDays || 30 }}{{ $t('systemSettings.days') }}</div>
                  </div>
                </div>
              </div>
            </a-card>
          </div>

          <!-- 清理操作 -->
          <div class="cleanup-actions">
            <a-card class="actions-card">
              <template #header>
                <div class="card-header">
                  <h3>{{ $t('systemSettings.cleanupActions') }}</h3>
                </div>
              </template>
              <div class="actions-content">
                <div class="action-buttons">
                  <a-button
                    type="primary"
                    @click="performFullCleanup"
                    :loading="loadingCleanup"
                    class="action-btn"
                  >
                    <DeleteOutlined />
                    {{ $t('systemSettings.performFullCleanup') }}
                  </a-button>
                  <a-button
                    type="warning"
                    @click="showUserCleanupDialog = true"
                    class="action-btn"
                  >
                    <UserOutlined />
                    {{ $t('systemSettings.cleanupUserTasks') }}
                  </a-button>
                </div>
                <div class="action-description">
                  <p><strong>{{ $t('systemSettings.fullCleanupDesc') }}：</strong>{{ $t('systemSettings.fullCleanupDescDetail') }}</p>
                  <p><strong>{{ $t('systemSettings.userCleanupDesc') }}：</strong>{{ $t('systemSettings.userCleanupDescDetail') }}</p>
                </div>
              </div>
            </a-card>
          </div>

          <!-- 清理配置 -->
          <div class="cleanup-config">
            <a-card class="config-card">
              <template #header>
                <div class="card-header">
                  <h3>{{ $t('systemSettings.cleanupConfig') }}</h3>
                </div>
              </template>
              <div class="config-content">
                <a-form :model="cleanupConfig" label-width="120px">
                  <a-form-item :label="$t('systemSettings.taskRetentionDays')">
                    <a-input-number
                      v-model="cleanupConfig.retentionDays"
                      :min="1"
                      :max="365"
                      controls-position="right"
                    />
                    <span class="config-tip">{{ $t('systemSettings.taskRetentionTip') }}</span>
                  </a-form-item>
                  <a-form-item :label="$t('systemSettings.archiveRetentionDays')">
                    <a-input-number
                      v-model="cleanupConfig.archiveRetentionDays"
                      :min="30"
                      :max="3650"
                      controls-position="right"
                    />
                    <span class="config-tip">{{ $t('systemSettings.archiveRetentionTip') }}</span>
                  </a-form-item>
                  <a-form-item>
                    <a-button type="primary" @click="saveCleanupConfig" :loading="loadingConfig">
                      {{ $t('common.save') }}
                    </a-button>
                  </a-form-item>
                </a-form>
              </div>
            </a-card>
          </div>
        </div>

        <!-- 资源点配置选项卡 -->
        <div v-if="activeTab === 'pointsCost'" class="tab-content">
          <h2 class="page-title">{{ $t('systemSettings.pointsCostTitle') }}</h2>
          <p class="section-desc">{{ $t('systemSettings.pointsCostDesc') }}</p>

          <div class="points-config-grid">
            <a-card class="points-config-card">
              <div class="points-card-icon text-to-video-icon">
                <VideoCameraOutlined />
              </div>
              <div class="points-card-info">
                <h3>{{ $t('systemSettings.textToVideoTitle') }}</h3>
                <p>{{ $t('systemSettings.textToVideoDesc') }}</p>
              </div>
              <div class="points-card-input">
                <a-input-number
                  v-model:value="pointsCostForm.textToVideoPoints"
                  :min="0"
                  :max="9999"
                  :precision="0"
                />
                <span class="points-unit">{{ $t('systemSettings.pointsUnit') }}</span>
              </div>
            </a-card>

            <a-card class="points-config-card">
              <div class="points-card-icon image-to-video-icon">
                <PictureOutlined />
              </div>
              <div class="points-card-info">
                <h3>{{ $t('systemSettings.imageToVideoTitle') }}</h3>
                <p>{{ $t('systemSettings.imageToVideoDesc') }}</p>
              </div>
              <div class="points-card-input">
                <a-input-number
                  v-model:value="pointsCostForm.imageToVideoPoints"
                  :min="0"
                  :max="9999"
                  :precision="0"
                />
                <span class="points-unit">{{ $t('systemSettings.pointsUnit') }}</span>
              </div>
            </a-card>

            <a-card class="points-config-card">
              <div class="points-card-icon storyboard-image-icon">
                <AppstoreOutlined />
              </div>
              <div class="points-card-info">
                <h3>{{ $t('systemSettings.storyboardImageTitle') }}</h3>
                <p>{{ $t('systemSettings.storyboardImageDesc') }}</p>
              </div>
              <div class="points-card-input">
                <a-input-number
                  v-model:value="pointsCostForm.storyboardImagePoints"
                  :min="0"
                  :max="9999"
                  :precision="0"
                />
                <span class="points-unit">{{ $t('systemSettings.pointsUnit') }}</span>
              </div>
            </a-card>

            <a-card class="points-config-card">
              <div class="points-card-icon storyboard-video-icon">
                <PlaySquareOutlined />
              </div>
              <div class="points-card-info">
                <h3>{{ $t('systemSettings.storyboardVideoTitle') }}</h3>
                <p>{{ $t('systemSettings.storyboardVideoDesc') }}</p>
              </div>
              <div class="points-card-input">
                <a-input-number
                  v-model:value="pointsCostForm.storyboardVideoPoints"
                  :min="0"
                  :max="9999"
                  :precision="0"
                />
                <span class="points-unit">{{ $t('systemSettings.pointsUnit') }}</span>
              </div>
            </a-card>
          </div>

          <div class="points-config-footer">
            <a-button
              type="primary"
              @click="savePointsCost"
              :loading="savingPointsCost"
              class="ai-save-btn"
            >
              <CheckOutlined v-if="!savingPointsCost" />
              {{ $t('systemSettings.savePointsConfig') }}
            </a-button>
          </div>
        </div>

        <!-- AI模型设置选项卡 -->
        <div v-if="activeTab === 'aiModel'" class="tab-content">
          <h2 class="page-title">{{ $t('systemSettings.aiModel') }}</h2>
          <a-card class="ai-model-card">
            <template #header>
              <div class="card-header">
                <h3>{{ $t('systemSettings.promptOptimization') }}</h3>
              </div>
            </template>
            <div class="ai-model-content">
              <a-form label-width="180px">
                <a-form-item :label="$t('systemSettings.promptOptimizationModel')">
                  <a-input v-model:value="promptOptimizationModel" style="width: 400px;" placeholder="gpt-5.1-thinking"></a-input>
                  <div class="model-tip">{{ $t('systemSettings.promptOptimizationModelTip') }}</div>
                </a-form-item>
                <a-form-item :label="$t('systemSettings.storyboardSystemPrompt')">
                  <a-input 
                    v-model="storyboardSystemPrompt" 
                    type="textarea" 
                    :rows="4" 
                    style="width: 500px;" 
                    :placeholder="$t('systemSettings.storyboardSystemPromptPlaceholder')">
                  </a-input>
                  <div class="model-tip">{{ $t('systemSettings.storyboardSystemPromptTip') }}</div>
                </a-form-item>
                <a-form-item>
                  <a-button 
                    type="primary" 
                    @click="saveAiModelSettings" 
                    :loading="savingAiModel"
                    class="ai-save-btn"
                  >
                    <CheckOutlined v-if="!savingAiModel" />
                    {{ $t('common.save') }}
                  </a-button>
                </a-form-item>
              </a-form>
            </div>
          </a-card>
        </div>
      </div>
    </main>

    <!-- 编辑会员收费标准对话框 -->
    <a-modal
      v-model:open="editDialogVisible"
      width="480px"
      @cancel="handleCloseEditDialog"
      class="membership-modal"
      :show-close="false"
    >
      <template #header>
        <div class="modal-header">
          <h2 class="modal-title">{{ $t('systemSettings.membership') }}</h2>
          <button class="close-btn" @click="handleCloseEditDialog">×</button>
        </div>
      </template>

      <div class="modal-content">
        <a-form :model="editForm" :rules="editRules" ref="editFormRef">
          <div class="form-group">
            <label class="form-label">{{ $t('systemSettings.membershipLevel') }}</label>
            <a-select v-model:value="editForm.level" :placeholder="$t('systemSettings.selectLevelPlaceholder')" style="width: 100%;" disabled>
              <a-select-option value="free">{{ $t('systemSettings.freeMembership') }}</a-select-option>
              <a-select-option value="starter">{{ $t('systemSettings.starterMembership') }}</a-select-option>
              <a-select-option value="standard">{{ $t('systemSettings.standardMembership') }}</a-select-option>
              <a-select-option value="professional">{{ $t('systemSettings.professionalMembership') }}</a-select-option>
            </a-select>
          </div>

          <div class="form-group">
            <label class="form-label">{{ $t('systemSettings.membershipPrice') }}</label>
            <div class="price-input">
              <span class="price-prefix">¥</span>
              <input
                type="number"
                v-model.number="editForm.price"
                placeholder="0"
                min="0"
                step="1"
                class="form-control"
              />
            </div>
          </div>

          <div class="form-group">
            <label class="form-label">{{ $t('systemSettings.resourcePointsAmount') }}</label>
            <input
              type="number"
              v-model="editForm.resourcePoints"
              placeholder="0"
              min="0"
              class="form-control"
            />
          </div>

          <div class="form-group">
            <label class="form-label">{{ $t('systemSettings.validityPeriod') }}</label>
            <a-select v-model:value="editForm.validityPeriod" style="width: 100%;">
              <a-select-option value="365">{{ $t('systemSettings.oneYear') }}</a-select-option>
              <a-select-option value="730">{{ $t('systemSettings.twoYears') }}</a-select-option>
              <a-select-option value="1095">{{ $t('systemSettings.threeYears') }}</a-select-option>
              <a-select-option value="0">{{ $t('systemSettings.permanent') }}</a-select-option>
            </a-select>
          </div>
        </a-form>
      </div>

      <template #footer>
        <div class="modal-footer">
          <button class="btn btn-cancel" @click="handleCloseEditDialog">{{ $t('common.cancel') }}</button>
          <button class="btn btn-save" @click="saveEdit">{{ $t('common.save') }}</button>
        </div>
      </template>
    </a-modal>

    <!-- 用户清理对话框 -->
    <a-modal
      v-model:open="showUserCleanupDialog"
      :title="$t('systemSettings.cleanupUserTasks')"
      width="480px"
      @cancel="handleCloseUserCleanupDialog"
    >
      <div class="user-cleanup-content">
        <a-form :model="userCleanupForm" :rules="userCleanupRules" ref="userCleanupFormRef">
          <a-form-item :label="$t('members.username')" prop="username">
            <a-input
              v-model="userCleanupForm.username"
              :placeholder="$t('systemSettings.enterUsername')"
              clearable
            />
          </a-form-item>
          <a-form-item>
            <a-alert
              :title="$t('systemSettings.warning')"
              type="warning"
              :closable="false"
              show-icon
            >
              <template #default>
                <p>{{ $t('systemSettings.cleanupWarning') }}</p>
                <ul>
                  <li>{{ $t('systemSettings.successTasksArchived') }}</li>
                  <li>{{ $t('systemSettings.failedTasksLogged') }}</li>
                  <li>{{ $t('systemSettings.originalTasksDeleted') }}</li>
                </ul>
                <p><strong>{{ $t('systemSettings.irreversibleWarning') }}</strong></p>
              </template>
            </a-alert>
          </a-form-item>
        </a-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <a-button @click="handleCloseUserCleanupDialog">{{ $t('common.cancel') }}</a-button>
          <a-button
            type="danger"
            @click="performUserCleanup"
            :loading="loadingUserCleanup"
          >
            {{ $t('systemSettings.confirmCleanup') }}
          </a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import { useI18n } from 'vue-i18n'
import {
  UserOutlined,
  SettingOutlined,
  DeleteOutlined,
  ReloadOutlined,
  CheckOutlined,
  ThunderboltOutlined,
  PictureOutlined,
  PlaySquareOutlined
} from '@ant-design/icons-vue'
import api from '@/api/request'
import cleanupApi from '@/api/cleanup'
import AdminSidebar from '@/components/AdminSidebar.vue'
import AdminHeader from '@/components/AdminHeader.vue'

const { t } = useI18n()

// 选项卡状态
const activeTab = ref('membership')

// 会员收费标准相关
const membershipLevels = ref([])
const loadingLevels = ref(false)

const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = reactive({
  id: null,
  level: '',
  price: '',
  resourcePoints: 0,
  validityPeriod: '365'
})

const editRules = computed(() => ({
  level: [{ required: true, message: t('systemSettings.selectLevelRequired'), trigger: 'change' }],
  price: [
    { required: true, message: t('systemSettings.enterPriceRequired'), trigger: 'blur' },
    { pattern: /^\d+(\.\d+)?$/, message: t('systemSettings.enterValidNumber'), trigger: 'blur' }
  ],
  resourcePoints: [{ required: true, message: t('systemSettings.enterResourcePointsRequired'), trigger: 'blur' }],
  validityPeriod: [{ required: true, message: t('systemSettings.selectValidityRequired'), trigger: 'change' }]
}))

// 任务清理相关
const cleanupStats = ref(null)
const loadingStats = ref(false)
const loadingCleanup = ref(false)
const loadingUserCleanup = ref(false)
const loadingConfig = ref(false)

const showUserCleanupDialog = ref(false)
const userCleanupFormRef = ref(null)
const userCleanupForm = reactive({
  username: ''
})

const userCleanupRules = computed(() => ({
  username: [
    { required: true, message: t('systemSettings.enterUsernameRequired'), trigger: 'blur' },
    { min: 2, max: 50, message: t('systemSettings.usernameLengthLimit'), trigger: 'blur' }
  ]
}))

const cleanupConfig = reactive({
  retentionDays: 30,
  archiveRetentionDays: 365
})

// 资源点配置相关
const pointsCostForm = reactive({
  textToVideoPoints: 30,
  imageToVideoPoints: 30,
  storyboardImagePoints: 30,
  storyboardVideoPoints: 30
})
const savingPointsCost = ref(false)

// AI模型设置相关
const promptOptimizationModel = ref('gpt-5.1-thinking')
const storyboardSystemPrompt = ref('')
const savingAiModel = ref(false)

const editLevel = (level) => {
  // 映射后端数据到前端表单
  editForm.id = level.id
  editForm.level = level.key
  editForm.price = Math.floor(level.price || 0)
  editForm.resourcePoints = level.pointsBonus || level.resourcePoints || 0
  // 根据 durationDays 匹配最近的选项
  const days = level.durationDays || 0
  if (days === 0) {
    editForm.validityPeriod = '0'
  } else if (days <= 365) {
    editForm.validityPeriod = '365'
  } else if (days <= 730) {
    editForm.validityPeriod = '730'
  } else {
    editForm.validityPeriod = '1095'
  }
  editDialogVisible.value = true
}

const handleCloseEditDialog = () => {
  editDialogVisible.value = false
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
}

// 格式化价格，转换为整数显示
const formatPrice = (price) => {
  if (price === null || price === undefined) return '0'
  return Math.floor(Number(price)).toString()
}

// 格式化有效期天数为可读文本
const formatDuration = (days) => {
  if (!days || days <= 0) return t('systemSettings.permanent')
  const years = Math.round(days / 365)
  if (years === 1) return t('systemSettings.oneYear')
  if (years === 2) return t('systemSettings.twoYears')
  if (years === 3) return t('systemSettings.threeYears')
  if (years > 3) return t('systemSettings.permanent')
  return t('systemSettings.daysCount', { days })
}

const saveEdit = async () => {
  const valid = await editFormRef.value.validate()
  if (!valid) return
  
  try {
    // 将整数价格转换为浮点数（保持数据库字段类型）
    const priceInt = parseInt(editForm.price)
    if (Number.isNaN(priceInt) || priceInt < 0) {
      message.error(t('systemSettings.enterValidNumber'))
      return
    }
    const priceValue = parseFloat(priceInt.toFixed(2))

    const pointsInt = parseInt(editForm.resourcePoints)
    if (Number.isNaN(pointsInt) || pointsInt < 0) {
      message.error(t('systemSettings.enterValidNumber'))
      return
    }

    // 计算有效期天数
    const durationDays = parseInt(editForm.validityPeriod) || 0

    // 更新membership_levels表（将整数转换为浮点数写入数据库）
    const updateData = { price: priceValue, pointsBonus: pointsInt, durationDays }
    console.log('准备更新会员等级:', editForm.id, updateData)
    const response = await api.put(`/members/levels/${editForm.id}`, updateData)
    console.log('会员等级更新响应:', response.data)

    if (response.data?.success) {
      message.success(t('systemSettings.membershipUpdateSuccess'))
      editDialogVisible.value = false
      await loadMembershipLevels()
    } else {
      message.error(t('systemSettings.membershipUpdateFailed') + ': ' + (response.data?.message || t('common.unknownError')))
    }
  } catch (error) {
    console.error('Update membership level failed:', error)
    message.error(t('systemSettings.membershipUpdateFailed') + ': ' + (error.response?.data?.message || error.message))
  }
}

// 加载会员等级配置（从membership_levels表读取）
const loadMembershipLevels = async () => {
  loadingLevels.value = true
  try {
    // 从membership_levels表读取数据
    const levelsResp = await api.get('/members/levels', {
      params: { _t: Date.now() },
      headers: { 'Cache-Control': 'no-cache' }
    })
    
    if (levelsResp.data?.success && levelsResp.data?.data) {
      const levels = levelsResp.data.data
      // 将浮点数价格转换为整数显示，并按固定顺序排列
      const levelOrder = { free: 0, starter: 1, standard: 2, professional: 3 }
      membershipLevels.value = levels.map(level => ({
        id: level.id,
        key: level.name,
        name: level.displayName || level.name,
        price: Math.floor(level.price || 0),
        resourcePoints: level.pointsBonus || 0,
        pointsBonus: level.pointsBonus || 0,
        durationDays: level.durationDays || 0,
        description: t('systemSettings.includesPointsPerMonth', { points: level.pointsBonus || 0 })
      })).sort((a, b) => (levelOrder[a.key] ?? 99) - (levelOrder[b.key] ?? 99))
    } else {
      throw new Error('Failed to load membership level data')
    }
  } catch (error) {
    console.error('Load membership config failed:', error)
    console.error('Error details:', error.response?.data || error.message)
    
    // 显示更详细的错误信息
    const errorMessage = error.response?.data?.message || error.response?.data?.error || error.message || t('systemSettings.unknown')
    message.warning(`${t('systemSettings.loadMembershipFailed')}: ${errorMessage}, ${t('systemSettings.usingDefaultConfig')}`)
    
    // API调用失败，清空数据并提示用户检查数据库配置
    membershipLevels.value = []
    message.error(t('common.cannotLoadMembershipConfig'))
  } finally {
    loadingLevels.value = false
  }
}

// 任务清理相关方法
const getAuthHeaders = () => {
  const token = localStorage.getItem('token')
  return token ? { 'Authorization': `Bearer ${token}` } : {}
}

const refreshStats = async (showMessage = true) => {
  loadingStats.value = true
  try {
    const response = await cleanupApi.getCleanupStats()
    cleanupStats.value = response.data
    if (showMessage) {
      message.success(t('systemSettings.statsRefreshSuccess'))
    }
  } catch (error) {
    console.error('Get statistics failed:', error)
    message.error(t('systemSettings.statsRefreshFailed'))
  } finally {
    loadingStats.value = false
  }
}

const performFullCleanup = async () => {
  loadingCleanup.value = true
  try {
    const response = await cleanupApi.performFullCleanup()
    message.success(t('systemSettings.fullCleanupSuccess'))
    console.log('Cleanup result:', response.data)
    // 刷新统计信息
    await refreshStats()
  } catch (error) {
    console.error('Execute full cleanup failed:', error)
    message.error(t('systemSettings.fullCleanupFailed'))
  } finally {
    loadingCleanup.value = false
  }
}

const handleCloseUserCleanupDialog = () => {
  showUserCleanupDialog.value = false
  if (userCleanupFormRef.value) {
    userCleanupFormRef.value.resetFields()
  }
}

const performUserCleanup = async () => {
  const valid = await userCleanupFormRef.value.validate()
  if (!valid) return
  
  loadingUserCleanup.value = true
  try {
    const response = await cleanupApi.cleanupUserTasks(userCleanupForm.username)
    message.success(t('systemSettings.userCleanupSuccess'))
    console.log('Cleanup result:', response.data)
    // 刷新统计信息
    await refreshStats()
    // 关闭对话框
    handleCloseUserCleanupDialog()
  } catch (error) {
    console.error('Cleanup UserOutlined tasks failed:', error)
    message.error(t('systemSettings.userCleanupFailed'))
  } finally {
    loadingUserCleanup.value = false
  }
}

const performUserCleanup_old = async () => {
  const valid = await userCleanupFormRef.value.validate()
  if (!valid) return
  
  loadingUserCleanup.value = true
  try {
    const response = await fetch(`/api/cleanup/user-tasks/${userCleanupForm.username}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...getAuthHeaders()
      }
    })
    
    if (response.ok) {
      const result = await response.json()
      message.success(t('systemSettings.userCleanupSuccess'))
      console.log('UserOutlined cleanup result:', result)
      // 关闭对话框并刷新统计信息
      handleCloseUserCleanupDialog()
      await refreshStats()
    } else {
      message.error(t('systemSettings.userCleanupFailed'))
    }
  } catch (error) {
    console.error('Cleanup UserOutlined tasks failed:', error)
    message.error(t('systemSettings.userCleanupFailed'))
  } finally {
    loadingUserCleanup.value = false
  }
}

const saveCleanupConfig = async () => {
  loadingConfig.value = true
  try {
    // 这里可以添加保存配置的API调用
    // 目前只是模拟保存
    await new Promise(resolve => setTimeout(resolve, 1000))
    message.success(t('systemSettings.configSaveSuccess'))
  } catch (error) {
    console.error('Save cleanup config failed:', error)
    message.error(t('systemSettings.configSaveFailed'))
  } finally {
    loadingConfig.value = false
  }
}

// 加载AI模型设置和资源点配置
const loadAiModelSettings = async () => {
  try {
    const response = await fetch('/api/admin/settings', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    if (response.ok) {
      const data = await response.json()
      if (data.promptOptimizationModel) {
        promptOptimizationModel.value = data.promptOptimizationModel
      }
      if (data.storyboardSystemPrompt !== undefined) {
        storyboardSystemPrompt.value = data.storyboardSystemPrompt
      }
      // 加载资源点配置
      if (data.textToVideoPoints !== undefined) {
        pointsCostForm.textToVideoPoints = data.textToVideoPoints
      }
      if (data.imageToVideoPoints !== undefined) {
        pointsCostForm.imageToVideoPoints = data.imageToVideoPoints
      }
      if (data.storyboardImagePoints !== undefined) {
        pointsCostForm.storyboardImagePoints = data.storyboardImagePoints
      }
      if (data.storyboardVideoPoints !== undefined) {
        pointsCostForm.storyboardVideoPoints = data.storyboardVideoPoints
      }
    }
  } catch (error) {
    console.error('Load AI model settings failed:', error)
  }
}

// 保存资源点配置
const savePointsCost = async () => {
  savingPointsCost.value = true
  try {
    const response = await fetch('/api/admin/settings', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify({
        textToVideoPoints: pointsCostForm.textToVideoPoints,
        imageToVideoPoints: pointsCostForm.imageToVideoPoints,
        storyboardImagePoints: pointsCostForm.storyboardImagePoints,
        storyboardVideoPoints: pointsCostForm.storyboardVideoPoints
      })
    })
    if (response.ok) {
      message.success(t('systemSettings.pointsCostSaveSuccess'))
    } else {
      throw new Error('Save failed')
    }
  } catch (error) {
    console.error('Save points cost settings failed:', error)
    message.error(t('systemSettings.pointsCostSaveFailed'))
  } finally {
    savingPointsCost.value = false
  }
}

// 保存AI模型设置
const saveAiModelSettings = async () => {
  savingAiModel.value = true
  try {
    const response = await fetch('/api/admin/settings', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify({
        promptOptimizationModel: promptOptimizationModel.value,
        storyboardSystemPrompt: storyboardSystemPrompt.value
      })
    })
    if (response.ok) {
      message.success(t('systemSettings.aiModelSaveSuccess'))
    } else {
      throw new Error('Save failed')
    }
  } catch (error) {
    console.error('Save AI model settings failed:', error)
    message.error(t('systemSettings.aiModelSaveFailed'))
  } finally {
    savingAiModel.value = false
  }
}

// 页面加载时获取统计信息和会员等级配置
onMounted(() => {
  refreshStats(false) // 初始加载不显示成功提示
  loadMembershipLevels()
  loadAiModelSettings()
})
</script>

<style scoped>
.system-settings {
  display: flex;
  height: 100vh;
  background-color: var(--bg-base);
  font-family: var(--font-sans);
}

.main-content {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.content-section {
  flex-grow: 1;
  padding: var(--space-8);
  background-color: var(--bg-base);
}

/* 设置选项卡样式 */
.settings-tabs {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.tab-nav {
  display: flex;
  background: var(--bg-elevated);
  border-bottom: 1px solid var(--border-subtle);
  padding: 0 var(--space-8);
}

.tab-item {
  display: flex;
  align-items: center;
  padding: var(--space-5) var(--space-6);
  margin-right: var(--space-2);
  cursor: pointer;
  border-bottom: 2px solid transparent;
  transition: var(--transition-all);
  color: var(--text-tertiary);
  font-size: var(--text-base);
  font-weight: var(--font-medium);
}

.tab-item:hover {
  color: var(--text-secondary);
  background: var(--bg-hover);
}

.tab-item.active {
  color: var(--primary-500);
  border-bottom-color: var(--primary-500);
  background: var(--primary-glow-subtle);
}

.tab-item .anticon {
  margin-right: var(--space-2);
  font-size: var(--text-lg);
}

.tab-content {
  flex-grow: 1;
  padding: var(--space-8);
  background-color: var(--bg-base);
}

/* 清理功能样式 */
.cleanup-stats,
.cleanup-actions,
.cleanup-config {
  margin-bottom: var(--space-6);
}

.stats-card,
.actions-card,
.config-card {
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-md);
  background: var(--bg-elevated, #1A1D2E);
  border: 1px solid var(--border-subtle, rgba(255, 255, 255, 0.08));
}

.stats-card :deep(.ant-card-body),
.actions-card :deep(.ant-card-body),
.config-card :deep(.ant-card-body) {
  background: transparent;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.card-header h3 {
  margin: 0;
  font-size: var(--text-lg);
  font-weight: var(--font-semibold);
  color: var(--text-primary);
}

.stats-content {
  padding: 20px 0;
}

.stats-AppstoreOutlined {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-item {
  text-align: center;
  padding: var(--space-5);
  background: var(--bg-surface);
  border-radius: var(--radius-md);
  border: 1px solid var(--border-subtle);
}

.stat-label {
  font-size: var(--text-sm);
  color: var(--text-tertiary);
  margin-bottom: var(--space-2);
}

.stat-value {
  font-size: var(--text-2xl);
  font-weight: var(--font-bold);
  color: var(--text-primary);
}

.actions-content {
  padding: 20px 0;
}

.action-buttons {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.action-btn {
  min-width: 160px;
}

.action-description {
  padding: var(--space-4);
  background: var(--bg-surface);
  border-radius: var(--radius-md);
  border-left: 4px solid var(--primary-500);
}

.action-description p {
  margin: 0 0 var(--space-2) 0;
  font-size: var(--text-sm);
  color: var(--text-tertiary);
  line-height: var(--leading-normal);
}

.action-description p:last-child {
  margin-bottom: 0;
}

.config-content {
  padding: 20px 0;
}

.config-tip {
  margin-left: var(--space-3);
  font-size: var(--text-xs);
  color: var(--text-disabled);
}

/* 用户清理对话框样式 */
.user-cleanup-content {
  padding: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.page-title {
  font-size: var(--text-2xl);
  color: var(--text-primary);
  margin-bottom: var(--space-6);
  font-weight: var(--font-bold);
}

.membership-cards {
  display: flex;
  gap: 25px;
  flex-wrap: wrap;
}

.membership-card {
  flex: 1;
  min-width: 280px;
  max-width: 350px;
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-md);
  transition: var(--transition-all);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  background: var(--bg-elevated, #1A1D2E);
  border: 1px solid var(--border-subtle, rgba(255, 255, 255, 0.08));
}

.membership-card :deep(.ant-card-body) {
  background: transparent;
  padding: 0;
}

.membership-card:hover {
  transform: translateY(-5px);
  box-shadow: var(--shadow-lg);
  border-color: var(--primary-400, #60A5FA);
}

.card-header {
  padding: var(--space-5);
  text-align: center;
  border-bottom: 1px solid var(--border-subtle, rgba(255, 255, 255, 0.08));
}

.card-header h3 {
  font-size: var(--text-xl);
  color: var(--text-primary, #E2E8F0);
  margin: 0;
}

.card-body {
  padding: 25px 20px;
  text-align: center;
  flex-grow: 1;
}

.card-body .price {
  font-size: var(--text-4xl);
  font-weight: var(--font-bold);
  color: var(--primary-400, #60A5FA);
  margin-bottom: var(--space-3);
}

.card-body .description {
  font-size: var(--text-sm);
  color: var(--text-secondary, #94A3B8);
  line-height: var(--leading-relaxed);
}

.card-body .validity {
  font-size: var(--text-sm);
  color: var(--text-tertiary, #64748B);
  margin-top: 4px;
}

.card-footer {
  padding: var(--space-5);
  text-align: center;
  border-top: 1px solid var(--border-subtle, rgba(255, 255, 255, 0.08));
}

.card-footer .ant-btn {
  width: 80%;
  height: 40px;
  line-height: 1;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-size: var(--text-base);
  border-radius: var(--radius-md);
}

/* 会员收费标准模态框样式 - 完全匹配HTML代码 */
.membership-modal {
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-lg);
  border: 1px solid var(--border-default);
  overflow: hidden;
}

.membership-modal .ant-modal-body {
  padding: 0;
}

/* 弹窗头部 */
.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--space-5) var(--space-6);
  border-bottom: 1px solid var(--border-subtle);
}

.modal-title {
  font-size: var(--text-lg);
  font-weight: var(--font-semibold);
  color: var(--text-primary);
  margin: 0;
}

.close-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: var(--bg-surface);
  border-radius: var(--radius-sm);
  font-size: var(--text-base);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-tertiary);
  transition: var(--transition-all);
}

.close-btn:hover {
  background: var(--primary-glow-light);
  color: var(--primary-500);
}

/* 表单内容区域 */
.modal-content {
  padding: var(--space-6);
}

.form-group {
  margin-bottom: var(--space-5);
}

.form-label {
  display: block;
  margin-bottom: var(--space-2);
  font-size: var(--text-sm);
  color: var(--text-primary);
  font-weight: var(--font-medium);
}

/* 输入框和下拉框样式 */
.form-control {
  width: 100%;
  height: 40px;
  padding: 0 var(--space-3);
  border: 1px solid var(--border-default);
  border-radius: var(--radius-sm);
  font-size: var(--text-sm);
  color: var(--text-primary);
  transition: var(--transition-all);
  background-color: var(--bg-surface);
}

.form-control:focus {
  outline: none;
  border-color: var(--primary-500);
  box-shadow: 0 0 0 2px var(--primary-glow-medium);
}

.form-control::placeholder {
  color: var(--text-disabled);
}

/* 价格输入框特殊样式 */
.price-input {
  position: relative;
}

.price-prefix {
  position: absolute;
  left: var(--space-3);
  top: 50%;
  transform: translateY(-50%);
  color: var(--text-tertiary);
  z-index: 10;
}

.price-input .form-control {
  padding-left: 30px;
}

/* 单选按钮组 */
.radio-group {
  display: flex;
  gap: 16px;
}

.radio-option {
  display: flex;
  align-items: center;
}

.radio-input {
  display: none;
}

.radio-label {
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: var(--text-sm);
  color: var(--text-tertiary);
  padding: var(--space-2) var(--space-4);
  border: 1px solid var(--border-default);
  border-radius: var(--radius-sm);
  transition: var(--transition-all);
}

.radio-input:checked + .radio-label {
  border-color: var(--primary-500);
  background-color: var(--primary-glow-subtle);
  color: var(--primary-500);
}

/* 按钮区域 */
.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: var(--space-3);
  padding: var(--space-5) var(--space-6);
  border-top: 1px solid var(--border-subtle);
}

.btn {
  padding: 0 var(--space-5);
  height: 36px;
  border: 1px solid;
  border-radius: var(--radius-sm);
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
  cursor: pointer;
  transition: var(--transition-all);
}

.btn-cancel {
  background: var(--bg-surface);
  border-color: var(--border-default);
  color: var(--text-secondary);
}

.btn-cancel:hover {
  border-color: var(--primary-500);
  color: var(--primary-500);
}

.btn-save {
  background: var(--primary-500);
  border-color: var(--primary-500);
  color: var(--text-inverse);
}

.btn-save:hover {
  background: var(--primary-400);
  border-color: var(--primary-400);
}

/* 资源点配置样式 */
.section-desc {
  font-size: var(--text-sm);
  color: var(--text-tertiary);
  margin-bottom: var(--space-6);
  line-height: var(--leading-relaxed);
}

.points-config-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: var(--space-5);
  margin-bottom: var(--space-8);
}

.points-config-card {
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-md);
  transition: var(--transition-all);
  background: var(--bg-elevated, #1A1D2E);
  border: 1px solid var(--border-subtle, rgba(255, 255, 255, 0.08));
}

.points-config-card:hover {
  transform: translateY(-3px);
  box-shadow: var(--shadow-lg);
  border-color: var(--primary-400, #60A5FA);
}

.points-config-card :deep(.ant-card-body) {
  display: flex;
  align-items: center;
  gap: var(--space-4);
  padding: var(--space-5) var(--space-6);
  background: transparent;
}

.points-card-icon {
  width: 48px;
  height: 48px;
  border-radius: var(--radius-md);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 22px;
  flex-shrink: 0;
}

.text-to-video-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
}

.image-to-video-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: #fff;
}

.storyboard-image-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: #fff;
}

.storyboard-video-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  color: #fff;
}

.points-card-info {
  flex: 1;
  min-width: 0;
}

.points-card-info h3 {
  margin: 0 0 2px 0;
  font-size: var(--text-base);
  font-weight: var(--font-semibold);
  color: var(--text-primary);
}

.points-card-info p {
  margin: 0;
  font-size: var(--text-xs);
  color: var(--text-tertiary);
}

.points-card-input {
  display: flex;
  align-items: center;
  gap: var(--space-2);
  flex-shrink: 0;
}

.points-card-input .ant-input-number {
  width: 100px;
}

.points-unit {
  font-size: var(--text-sm);
  color: var(--text-tertiary);
  white-space: nowrap;
}

.points-config-footer {
  display: flex;
  justify-content: flex-end;
}

/* AI模型设置保存按钮样式 */
.ai-save-btn {
  width: auto !important;
  min-width: 140px;
  padding: var(--space-3) var(--space-8) !important;
  font-size: var(--text-sm) !important;
  font-weight: var(--font-medium);
  border-radius: var(--radius-md) !important;
  background: linear-gradient(135deg, var(--secondary-500) 0%, var(--primary-600) 100%) !important;
  border: none !important;
  box-shadow: 0 4px 15px var(--secondary-glow);
  transition: var(--transition-all) !important;
  display: inline-flex;
  align-items: center;
  gap: var(--space-2);
}

.ai-save-btn:hover {
  transform: translateY(-2px);
  box-shadow: var(--glow-secondary);
  background: linear-gradient(135deg, var(--secondary-600) 0%, var(--primary-700) 100%) !important;
}

.ai-save-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 10px var(--secondary-glow);
}

.ai-save-btn .anticon {
  font-size: var(--text-base);
}

/* 响应式调整 */
@media (max-width: 480px) {
  .membership-modal {
    border-radius: 0;
  }
  
  .modal-content {
    padding: 16px;
  }
  
  .radio-group {
    flex-direction: column;
    gap: 8px;
  }
}

/* Responsive adjustments */
@media (max-width: 1200px) {
  .membership-card {
    max-width: none;
  }
}

/* ========================================
   全局暗底白字 - 覆盖所有 Ant Card 默认白色背景
   ======================================== */
:deep(.ant-card) {
  background: var(--bg-elevated, #1A1D2E);
  border-color: var(--border-subtle, rgba(255, 255, 255, 0.08));
  color: var(--text-primary, #E2E8F0);
}

:deep(.ant-card-head) {
  background: transparent;
  border-bottom-color: var(--border-subtle, rgba(255, 255, 255, 0.08));
  color: var(--text-primary, #E2E8F0);
}

:deep(.ant-card-head-title) {
  color: var(--text-primary, #E2E8F0);
}

:deep(.ant-card-body) {
  background: transparent;
  color: var(--text-primary, #E2E8F0);
}

/* 表单标签和输入框暗底适配 */
:deep(.ant-form-item-label > label) {
  color: var(--text-secondary, #94A3B8) !important;
}

:deep(.ant-input),
:deep(.ant-input-number),
:deep(.ant-select-selector) {
  background: var(--bg-base, #0F1219) !important;
  border-color: var(--border-default, rgba(255, 255, 255, 0.12)) !important;
  color: var(--text-primary, #E2E8F0) !important;
}

:deep(.ant-input::placeholder),
:deep(.ant-input-number-input::placeholder) {
  color: var(--text-tertiary, #64748B) !important;
}

:deep(.ant-select-selection-item) {
  color: var(--text-primary, #E2E8F0) !important;
}

:deep(.ant-select-arrow) {
  color: var(--text-tertiary, #64748B) !important;
}

/* 模态框暗底适配 */
:deep(.ant-modal-content) {
  background: var(--bg-elevated, #1A1D2E);
  color: var(--text-primary, #E2E8F0);
}

:deep(.ant-modal-header) {
  background: var(--bg-elevated, #1A1D2E);
  border-bottom-color: var(--border-subtle, rgba(255, 255, 255, 0.08));
}

:deep(.ant-modal-title) {
  color: var(--text-primary, #E2E8F0) !important;
}

:deep(.ant-modal-close-x) {
  color: var(--text-secondary, #94A3B8);
}

:deep(.ant-modal-footer) {
  border-top-color: var(--border-subtle, rgba(255, 255, 255, 0.08));
}

/* 提示文字 / 说明文字 — 暗底下使用浅色 */
.model-tip {
  color: var(--text-tertiary, #94A3B8);
  font-size: 12px;
  margin-top: 4px;
}

.section-desc {
  color: var(--text-secondary, #94A3B8) !important;
}

:deep(.ant-form-item-explain),
:deep(.ant-form-item-extra) {
  color: var(--text-tertiary, #94A3B8) !important;
}

/* placeholder 在暗底下也要可见 */
:deep(.ant-input::placeholder),
:deep(textarea.ant-input::placeholder),
:deep(.ant-input-number-input::placeholder) {
  color: var(--text-tertiary, #64748B) !important;
}

@media (max-width: 768px) {
  .sidebar {
    width: 60px;
    padding: 15px 0;
  }

  .sidebar .logo span,
  .sidebar .nav-item span,
  .sidebar-footer {
    display: none;
  }

  .sidebar .logo {
    padding: 0 10px 20px;
  }

  .sidebar .logo-icon {
    margin-right: 0;
  }

  .nav-menu {
    padding: 0 10px;
  }

  .nav-item {
    justify-content: center;
    padding: 10px;
  }

  .nav-item .anticon {
    margin-right: 0;
  }

  .top-header {
    padding: 10px 20px;
  }

  .content-section {
    padding: 20px;
  }

  .page-title {
    font-size: 20px;
    margin-bottom: 20px;
  }

  .membership-cards {
    flex-direction: column;
    align-items: center;
  }

  .membership-card {
    width: 90%;
    max-width: 400px;
  }
}
</style>
