<script setup lang="ts">
/**
 * 全局配置：按 settingsSchema 分 Tab 编辑，分组保存。
 */
import { computed, ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useToast } from '@wot-ui/ui'
import AppNavbar from '@/components/layout/AppNavbar.vue'
import AppPageShell from '@/components/layout/AppPageShell.vue'
import { useAdminGuard } from '../../composables/useAdminGuard'
import { batchUpdateSettings, getAdminSettings } from '@/api'
import { MENU_OPTIONS, SETTING_GROUPS, SETTINGS_SCHEMA } from '../../config/settingsSchema'
import AdminFormField from '../../components/AdminFormField.vue'

const toast = useToast()
const { guardAdmin } = useAdminGuard()
const loading = ref(false)
const submitting = ref(false)
const tab = ref(0)
const values = ref<Record<string, string>>({})

const currentGroup = computed(() => SETTING_GROUPS[tab.value]?.id || 'site')
const currentFields = computed(() => SETTINGS_SCHEMA.filter(f => f.group === currentGroup.value))

function parseMenus(raw: string): string[] {
  try {
    const arr = JSON.parse(raw || '[]')
    return Array.isArray(arr) ? arr.map(String) : []
  }
  catch {
    return []
  }
}

function toggleMenu(key: string) {
  const list = parseMenus(values.value.visible_menus || '[]')
  const i = list.indexOf(key)
  if (i >= 0) list.splice(i, 1)
  else list.push(key)
  values.value.visible_menus = JSON.stringify(list)
}

function normalizeSettings(data: unknown): Record<string, string> {
  const map: Record<string, string> = {}
  SETTINGS_SCHEMA.forEach((f) => { map[f.key] = f.default })
  if (Array.isArray(data)) {
    data.forEach((row: unknown) => {
      const r = row as { key?: string, keyName?: string, value?: string }
      const k = r.key || r.keyName
      if (k) map[k] = String(r.value ?? '')
    })
  }
  else if (data && typeof data === 'object') {
    Object.entries(data as Record<string, unknown>).forEach(([k, v]) => {
      map[k] = typeof v === 'string' ? v : JSON.stringify(v)
    })
  }
  return map
}

async function load() {
  if (!guardAdmin()) return
  loading.value = true
  try {
    values.value = normalizeSettings(await getAdminSettings())
  }
  catch (e: unknown) {
    toast.error(e instanceof Error ? e.message : '加载失败')
  }
  finally {
    loading.value = false
  }
}

onShow(load)

async function saveGroup() {
  submitting.value = true
  try {
    const payload: Record<string, string> = {}
    currentFields.value.forEach((f) => {
      payload[f.key] = values.value[f.key] ?? f.default
    })
    await batchUpdateSettings(payload)
    toast.success('本组已保存')
  }
  catch (e: unknown) {
    toast.error(e instanceof Error ? e.message : '保存失败')
  }
  finally {
    submitting.value = false
  }
}
</script>

<template>
  <AppPageShell admin>
    <AppNavbar title="全局配置" show-back />
    <view class="page-pad">
      <wd-tabs v-model="tab">
        <wd-tab v-for="g in SETTING_GROUPS" :key="g.id" :title="g.label" />
      </wd-tabs>
      <view class="admin-card form-card">
        <template v-for="f in currentFields" :key="f.key">
          <AdminFormField
            v-if="f.type === 'text' || f.type === 'email' || f.type === 'number'"
            :label="f.label"
          >
            <wd-input v-model="values[f.key]" :placeholder="f.label" clearable />
          </AdminFormField>
          <AdminFormField
            v-else-if="f.type === 'textarea' || f.type === 'homepage-json'"
            :label="f.label"
          >
            <wd-textarea
              v-model="values[f.key]"
              :placeholder="f.label"
              :rows="f.type === 'homepage-json' ? 10 : 3"
            />
          </AdminFormField>
          <view v-else-if="f.type === 'menu-checkboxes'" class="menus">
            <text class="label text-art-muted">{{ f.label }}</text>
            <view class="tags">
              <view
                v-for="m in MENU_OPTIONS"
                :key="m.key"
                class="tag"
                :class="{ on: parseMenus(values.visible_menus || '').includes(m.key) }"
                @click="toggleMenu(m.key)"
              >
                {{ m.label }}
              </view>
            </view>
          </view>
        </template>
        <wd-button
          block
          type="primary"
          :loading="submitting"
          custom-style="margin-top:24rpx;background:#d4b383;border-color:#d4b383;"
          @click="saveGroup"
        >
          保存本组
        </wd-button>
      </view>
      <wd-loading v-if="loading" />
    </view>
  </AppPageShell>
</template>

<style scoped lang="scss">
.page-pad { padding: 24rpx 32rpx 80rpx; }
.form-card { margin-top: 20rpx; }
.menus { margin: 16rpx 0; }
.label { font-size: 24rpx; }
.tags { display: flex; flex-wrap: wrap; gap: 12rpx; margin-top: 12rpx; }
.tag {
  padding: 10rpx 18rpx; border-radius: 8rpx; font-size: 24rpx;
  background: rgba(255, 255, 255, 0.06); color: rgba(255, 255, 255, 0.65);
}
.tag.on { background: rgba(212, 179, 131, 0.25); color: rgb(var(--art-accent)); }
</style>
