<script setup>
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

import { fetchSystemConfig, updateSystemConfig, executeScheduleNow } from '../api/system'
import { fetchKdocsQr, fetchKdocsStatus, clearKdocsLogin } from '../api/kdocs'
import { fetchProxyConfig, testProxy, updateProxyConfig } from '../api/proxy'

const loading = ref(false)

// 并发
const maxConcurrentGlobal = ref(2)
const maxConcurrentPerAccount = ref(1)
const maxScreenshotConcurrent = ref(3)

// 定时
const scheduleEnabled = ref(false)
const scheduleTime = ref('02:00')
const scheduleBrowseType = ref('应读')
const scheduleWeekdays = ref(['1', '2', '3', '4', '5', '6', '7'])
const scheduleScreenshotEnabled = ref(true)

// 代理
const proxyEnabled = ref(false)
const proxyApiUrl = ref('')
const proxyExpireMinutes = ref(3)

// 自动审核
const autoApproveEnabled = ref(false)
const autoApproveHourlyLimit = ref(10)
const autoApproveVipDays = ref(7)

// 金山文档上传
const kdocsEnabled = ref(false)
const kdocsDocUrl = ref('')
const kdocsDefaultUnit = ref('')
const kdocsSheetName = ref('')
const kdocsSheetIndex = ref(0)
const kdocsUnitColumn = ref('A')
const kdocsImageColumn = ref('D')
const kdocsAdminNotifyEnabled = ref(false)
const kdocsAdminNotifyEmail = ref('')
const kdocsStatus = ref({})
const kdocsQrOpen = ref(false)
const kdocsQrImage = ref('')
const kdocsPolling = ref(false)
let kdocsPollingTimer = null

const weekdaysOptions = [
  { label: '周一', value: '1' },
  { label: '周二', value: '2' },
  { label: '周三', value: '3' },
  { label: '周四', value: '4' },
  { label: '周五', value: '5' },
  { label: '周六', value: '6' },
  { label: '周日', value: '7' },
]

const weekdayNames = {
  1: '周一',
  2: '周二',
  3: '周三',
  4: '周四',
  5: '周五',
  6: '周六',
  7: '周日',
}

const scheduleWeekdayDisplay = computed(() =>
  (scheduleWeekdays.value || [])
    .map((d) => weekdayNames[Number(d)] || d)
    .join('、'),
)

function normalizeBrowseType(value) {
  if (String(value) === '注册前未读') return '注册前未读'
  return '应读'
}

async function loadAll() {
  loading.value = true
  try {
    const [system, proxy, kdocsInfo] = await Promise.all([
      fetchSystemConfig(),
      fetchProxyConfig(),
      fetchKdocsStatus().catch(() => ({})),
    ])

    maxConcurrentGlobal.value = system.max_concurrent_global ?? 2
    maxConcurrentPerAccount.value = system.max_concurrent_per_account ?? 1
    maxScreenshotConcurrent.value = system.max_screenshot_concurrent ?? 3

    scheduleEnabled.value = (system.schedule_enabled ?? 0) === 1
    scheduleTime.value = system.schedule_time || '02:00'
    scheduleBrowseType.value = normalizeBrowseType(system.schedule_browse_type)

    const weekdays = String(system.schedule_weekdays || '1,2,3,4,5,6,7')
      .split(',')
      .map((x) => x.trim())
      .filter(Boolean)
    scheduleWeekdays.value = weekdays.length ? weekdays : ['1', '2', '3', '4', '5', '6', '7']
    scheduleScreenshotEnabled.value = (system.enable_screenshot ?? 1) === 1

    autoApproveEnabled.value = (system.auto_approve_enabled ?? 0) === 1
    autoApproveHourlyLimit.value = system.auto_approve_hourly_limit ?? 10
    autoApproveVipDays.value = system.auto_approve_vip_days ?? 7

    proxyEnabled.value = (proxy.proxy_enabled ?? 0) === 1
    proxyApiUrl.value = proxy.proxy_api_url || ''
    proxyExpireMinutes.value = proxy.proxy_expire_minutes ?? 3

    kdocsEnabled.value = (system.kdocs_enabled ?? 0) === 1
    kdocsDocUrl.value = system.kdocs_doc_url || ''
    kdocsDefaultUnit.value = system.kdocs_default_unit || ''
    kdocsSheetName.value = system.kdocs_sheet_name || ''
    kdocsSheetIndex.value = system.kdocs_sheet_index ?? 0
    kdocsUnitColumn.value = (system.kdocs_unit_column || 'A').toUpperCase()
    kdocsImageColumn.value = (system.kdocs_image_column || 'D').toUpperCase()
    kdocsAdminNotifyEnabled.value = (system.kdocs_admin_notify_enabled ?? 0) === 1
    kdocsAdminNotifyEmail.value = system.kdocs_admin_notify_email || ''
    kdocsStatus.value = kdocsInfo || {}
  } catch {
    // handled by interceptor
  } finally {
    loading.value = false
  }
}

async function saveConcurrency() {
  const payload = {
    max_concurrent_global: Number(maxConcurrentGlobal.value),
    max_concurrent_per_account: Number(maxConcurrentPerAccount.value),
    max_screenshot_concurrent: Number(maxScreenshotConcurrent.value),
  }

  try {
    await ElMessageBox.confirm(
      `确定更新并发配置吗？\n\n全局并发数: ${payload.max_concurrent_global}\n单账号并发数: ${payload.max_concurrent_per_account}\n截图并发数: ${payload.max_screenshot_concurrent}`,
      '保存并发配置',
      { confirmButtonText: '保存', cancelButtonText: '取消', type: 'warning' },
    )
  } catch {
    return
  }

  try {
    const res = await updateSystemConfig(payload)
    ElMessage.success(res?.message || '并发配置已更新')
  } catch {
    // handled by interceptor
  }
}

async function saveSchedule() {
  if (scheduleEnabled.value && (!scheduleWeekdays.value || scheduleWeekdays.value.length === 0)) {
    ElMessage.error('请至少选择一个执行日期')
    return
  }

  const payload = {
    schedule_enabled: scheduleEnabled.value ? 1 : 0,
    schedule_time: scheduleTime.value,
    schedule_browse_type: scheduleBrowseType.value,
    schedule_weekdays: (scheduleWeekdays.value || []).join(','),
    enable_screenshot: scheduleScreenshotEnabled.value ? 1 : 0,
  }

  const screenshotText = scheduleScreenshotEnabled.value ? '截图' : '不截图'
  const message = scheduleEnabled.value
    ? `确定启用定时任务吗？\n\n执行时间: 每天 ${payload.schedule_time}\n执行日期: ${scheduleWeekdayDisplay.value}\n浏览类型: ${payload.schedule_browse_type}\n截图: ${screenshotText}\n\n系统将自动执行所有账号的浏览任务`
    : '确定关闭定时任务吗？'

  try {
    await ElMessageBox.confirm(message, '保存定时任务', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }

  try {
    const res = await updateSystemConfig(payload)
    ElMessage.success(res?.message || (scheduleEnabled.value ? '定时任务已启用' : '定时任务已关闭'))
  } catch {
    // handled by interceptor
  }
}

async function runScheduleNow() {
  const msg = `确定要立即执行定时任务吗？\n\n这将执行所有账号的浏览任务\n浏览类型: ${scheduleBrowseType.value}\n\n注意：无视定时时间和执行日期配置，立即开始执行！`
  try {
    await ElMessageBox.confirm(msg, '立即执行', {
      confirmButtonText: '立即执行',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }

  try {
    const res = await executeScheduleNow()
    ElMessage.success(res?.message || '定时任务已开始执行')
  } catch {
    // handled by interceptor
  }
}

async function saveProxy() {
  if (proxyEnabled.value && !proxyApiUrl.value.trim()) {
    ElMessage.error('启用代理时，API地址不能为空')
    return
  }

  const payload = {
    proxy_enabled: proxyEnabled.value ? 1 : 0,
    proxy_api_url: proxyApiUrl.value.trim(),
    proxy_expire_minutes: Number(proxyExpireMinutes.value) || 3,
  }

  try {
    const res = await updateProxyConfig(payload)
    ElMessage.success(res?.message || '代理配置已更新')
  } catch {
    // handled by interceptor
  }
}

async function saveKdocsConfig() {
  const payload = {
    kdocs_enabled: kdocsEnabled.value ? 1 : 0,
    kdocs_doc_url: kdocsDocUrl.value.trim(),
    kdocs_default_unit: kdocsDefaultUnit.value.trim(),
    kdocs_sheet_name: kdocsSheetName.value.trim(),
    kdocs_sheet_index: Number(kdocsSheetIndex.value) || 0,
    kdocs_unit_column: kdocsUnitColumn.value.trim().toUpperCase(),
    kdocs_image_column: kdocsImageColumn.value.trim().toUpperCase(),
    kdocs_admin_notify_enabled: kdocsAdminNotifyEnabled.value ? 1 : 0,
    kdocs_admin_notify_email: kdocsAdminNotifyEmail.value.trim(),
  }

  try {
    const res = await updateSystemConfig(payload)
    ElMessage.success(res?.message || '表格配置已更新')
  } catch {
    // handled by interceptor
  }
}

async function refreshKdocsStatus() {
  try {
    kdocsStatus.value = await fetchKdocsStatus({ live: 1 })
  } catch {
    // handled by interceptor
  }
}

async function pollKdocsStatus() {
  try {
    const status = await fetchKdocsStatus({ live: 1 })
    kdocsStatus.value = status
    const loggedIn = status?.logged_in === true || status?.last_login_ok === true
    if (loggedIn) {
      ElMessage.success('扫码成功，已登录')
      kdocsQrOpen.value = false
      stopKdocsPolling()
    }
  } catch {
    // handled by interceptor
  }
}

function startKdocsPolling() {
  stopKdocsPolling()
  kdocsPolling.value = true
  pollKdocsStatus()
  kdocsPollingTimer = setInterval(pollKdocsStatus, 2000)
}

function stopKdocsPolling() {
  if (kdocsPollingTimer) {
    clearInterval(kdocsPollingTimer)
    kdocsPollingTimer = null
  }
  kdocsPolling.value = false
}

async function onFetchKdocsQr() {
  try {
    const res = await fetchKdocsQr()
    kdocsQrImage.value = res?.qr_image || ''
    if (!kdocsQrImage.value) {
      if (res?.logged_in) {
        ElMessage.success('当前已登录，无需扫码')
        await refreshKdocsStatus()
        return
      }
      ElMessage.warning('未获取到二维码')
      return
    }
    kdocsQrOpen.value = true
  } catch {
    // handled by interceptor
  }
}

async function onClearKdocsLogin() {
  try {
    await clearKdocsLogin()
    ElMessage.success('登录态已清除')
    await refreshKdocsStatus()
  } catch {
    // handled by interceptor
  }
}

watch(kdocsQrOpen, (open) => {
  if (open) {
    startKdocsPolling()
  } else {
    stopKdocsPolling()
  }
})

onBeforeUnmount(() => {
  stopKdocsPolling()
})

async function onTestProxy() {
  if (!proxyApiUrl.value.trim()) {
    ElMessage.error('请先输入代理API地址')
    return
  }

  try {
    const res = await testProxy({ api_url: proxyApiUrl.value.trim() })
    await ElMessageBox.alert(res?.message || '测试完成', '代理测试', { confirmButtonText: '知道了' })
  } catch {
    // handled by interceptor
  }
}

async function saveAutoApprove() {
  const hourly = Number(autoApproveHourlyLimit.value)
  const vipDays = Number(autoApproveVipDays.value)

  if (!Number.isFinite(hourly) || hourly < 1) {
    ElMessage.error('每小时注册限制必须大于0')
    return
  }
  if (!Number.isFinite(vipDays) || vipDays < 0) {
    ElMessage.error('VIP天数不能为负数')
    return
  }

  const payload = {
    auto_approve_enabled: autoApproveEnabled.value ? 1 : 0,
    auto_approve_hourly_limit: hourly,
    auto_approve_vip_days: vipDays,
  }

  try {
    const res = await updateSystemConfig(payload)
    ElMessage.success(res?.message || '注册设置已保存')
  } catch {
    // handled by interceptor
  }
}

onMounted(loadAll)
</script>

<template>
  <div class="page-stack" v-loading="loading">
    <div class="app-page-title">
      <h2>系统配置</h2>
      <div>
        <el-button @click="loadAll">刷新</el-button>
      </div>
    </div>

    <el-card shadow="never" :body-style="{ padding: '16px' }" class="card">
      <h3 class="section-title">系统并发配置</h3>

      <el-form label-width="130px">
        <el-form-item label="全局最大并发数">
          <el-input-number v-model="maxConcurrentGlobal" :min="1" :max="200" />
          <div class="help">同时最多运行的账号数量（浏览任务使用 API 方式，资源占用较低）。</div>
        </el-form-item>

        <el-form-item label="单账号最大并发数">
          <el-input-number v-model="maxConcurrentPerAccount" :min="1" :max="50" />
          <div class="help">单个账号同时最多运行的任务数量（建议设为 1）。</div>
        </el-form-item>

        <el-form-item label="截图最大并发数">
          <el-input-number v-model="maxScreenshotConcurrent" :min="1" :max="50" />
          <div class="help">同时进行截图的最大数量（wkhtmltoimage 资源占用较低，可按需提高）。</div>
        </el-form-item>
      </el-form>

      <el-button type="primary" @click="saveConcurrency">保存并发配置</el-button>
    </el-card>

    <el-card shadow="never" :body-style="{ padding: '16px' }" class="card">
      <h3 class="section-title">定时任务配置</h3>

      <el-form label-width="130px">
        <el-form-item label="启用定时任务">
          <el-switch v-model="scheduleEnabled" />
          <div class="help">开启后，系统会按计划自动执行浏览任务。</div>
        </el-form-item>

        <el-form-item v-if="scheduleEnabled" label="执行时间">
          <el-time-picker v-model="scheduleTime" value-format="HH:mm" format="HH:mm" />
        </el-form-item>

        <el-form-item v-if="scheduleEnabled" label="浏览类型">
          <el-select v-model="scheduleBrowseType" style="width: 220px">
            <el-option label="注册前未读" value="注册前未读" />
            <el-option label="应读" value="应读" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="scheduleEnabled" label="执行日期">
          <el-checkbox-group v-model="scheduleWeekdays">
            <el-checkbox v-for="w in weekdaysOptions" :key="w.value" :label="w.value">
              {{ w.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item v-if="scheduleEnabled" label="定时任务截图">
          <el-switch v-model="scheduleScreenshotEnabled" />
          <div class="help">开启后，定时任务执行时会生成截图。</div>
        </el-form-item>
      </el-form>

      <div class="row-actions">
        <el-button type="primary" @click="saveSchedule">保存定时任务配置</el-button>
        <el-button type="success" plain @click="runScheduleNow">立即执行</el-button>
      </div>
    </el-card>

    <el-card shadow="never" :body-style="{ padding: '16px' }" class="card">
      <h3 class="section-title">代理设置</h3>

      <el-form label-width="130px">
        <el-form-item label="启用IP代理">
          <el-switch v-model="proxyEnabled" />
          <div class="help">开启后，所有浏览任务将通过代理IP访问（失败自动重试3次）。</div>
        </el-form-item>

        <el-form-item label="代理API地址">
          <el-input v-model="proxyApiUrl" placeholder="http://api.xxx/Tools/IP.ashx?..." />
          <div class="help">API 应返回：IP:PORT（例如 123.45.67.89:8888）。</div>
        </el-form-item>

        <el-form-item label="代理有效期(分钟)">
          <el-input-number v-model="proxyExpireMinutes" :min="1" :max="60" />
        </el-form-item>
      </el-form>

      <div class="row-actions">
        <el-button type="primary" @click="saveProxy">保存代理配置</el-button>
        <el-button @click="onTestProxy">测试代理</el-button>
      </div>
    </el-card>

    <el-card shadow="never" :body-style="{ padding: '16px' }" class="card">
      <h3 class="section-title">注册设置</h3>

      <el-form label-width="130px">
        <el-form-item label="注册赠送VIP">
          <el-switch v-model="autoApproveEnabled" />
          <div class="help">开启后，新用户注册成功后将赠送下方设置的VIP天数（注册已默认无需审核）。</div>
        </el-form-item>

        <el-form-item label="每小时注册限制">
          <el-input-number v-model="autoApproveHourlyLimit" :min="1" :max="10000" />
        </el-form-item>

        <el-form-item label="注册赠送VIP天数">
          <el-input-number v-model="autoApproveVipDays" :min="0" :max="999999" />
        </el-form-item>
      </el-form>

      <el-button type="primary" @click="saveAutoApprove">保存注册设置</el-button>
    </el-card>

    <el-card shadow="never" :body-style="{ padding: '16px' }" class="card">
      <h3 class="section-title">金山文档上传</h3>

      <el-form label-width="130px">
        <el-form-item label="启用上传">
          <el-switch v-model="kdocsEnabled" />
          <div class="help">表格结构变化时可先关闭，避免错误上传。</div>
        </el-form-item>

        <el-form-item label="文档链接">
          <el-input v-model="kdocsDocUrl" placeholder="https://kdocs.cn/..." />
        </el-form-item>

        <el-form-item label="默认县区">
          <el-input v-model="kdocsDefaultUnit" placeholder="如：道县（用户可覆盖）" />
        </el-form-item>

        <el-form-item label="Sheet名称">
          <el-input v-model="kdocsSheetName" placeholder="留空使用第一个Sheet" />
        </el-form-item>

        <el-form-item label="Sheet序号">
          <el-input-number v-model="kdocsSheetIndex" :min="0" :max="50" />
          <div class="help">0 表示第一个Sheet。</div>
        </el-form-item>

        <el-form-item label="县区列">
          <el-input v-model="kdocsUnitColumn" placeholder="A" style="max-width: 120px" />
        </el-form-item>

        <el-form-item label="图片列">
          <el-input v-model="kdocsImageColumn" placeholder="D" style="max-width: 120px" />
        </el-form-item>

        <el-form-item label="管理员通知">
          <el-switch v-model="kdocsAdminNotifyEnabled" />
        </el-form-item>

        <el-form-item label="通知邮箱">
          <el-input v-model="kdocsAdminNotifyEmail" placeholder="admin@example.com" />
        </el-form-item>
      </el-form>

      <div class="row-actions">
        <el-button type="primary" @click="saveKdocsConfig">保存表格配置</el-button>
        <el-button @click="refreshKdocsStatus">刷新状态</el-button>
        <el-button type="success" plain @click="onFetchKdocsQr">获取二维码</el-button>
        <el-button type="danger" plain @click="onClearKdocsLogin">清除登录</el-button>
      </div>

      <div class="help">
        登录状态：
        <span v-if="kdocsStatus.last_login_ok === true">已登录</span>
        <span v-else-if="kdocsStatus.login_required">需要扫码</span>
        <span v-else>未知</span>
        · 待上传 {{ kdocsStatus.queue_size || 0 }}
        <span v-if="kdocsStatus.last_error">· 最近错误：{{ kdocsStatus.last_error }}</span>
      </div>
    </el-card>

    <el-dialog v-model="kdocsQrOpen" title="扫码登录" width="min(420px, 92vw)">
      <div class="kdocs-qr">
        <img v-if="kdocsQrImage" :src="`data:image/png;base64,${kdocsQrImage}`" alt="KDocs QR" />
        <div class="help">请使用管理员微信扫码登录。</div>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
.page-stack {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.card {
  border-radius: var(--app-radius);
  border: 1px solid var(--app-border);
}

.section-title {
  margin: 0 0 12px;
  font-size: 14px;
  font-weight: 800;
}

.kdocs-qr {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.kdocs-qr img {
  width: 260px;
  max-width: 100%;
  border: 1px solid var(--app-border);
  border-radius: 8px;
  padding: 8px;
  background: #fff;
}

.help {
  margin-top: 6px;
  font-size: 12px;
  color: var(--app-muted);
}

.row-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
</style>
