<script setup lang="ts">
/**
 * 文章管理列表：服务端分页 + 筛选 + 行内发布切换 + 删除。
 * 关联/历史/访问日志放在编辑页，降低列表复杂度。
 */
import { ref } from 'vue'
import { onReachBottom, onShow } from '@dcloudio/uni-app'
import { useDialog, useToast } from '@wot-ui/ui'
import AppNavbar from '@/components/layout/AppNavbar.vue'
import AppPageShell from '@/components/layout/AppPageShell.vue'
import AdminFilterBar from '../../components/AdminFilterBar.vue'
import AdminStatusBadge from '../../components/AdminStatusBadge.vue'
import { useAdminGuard } from '../../composables/useAdminGuard'
import {
  adminDelete,
  adminList,
  normalizePagination,
  patchPostStatus,
  type Post,
} from '@/api'

const toast = useToast()
const dialog = useDialog()
const { guardAdmin } = useAdminGuard()

const loading = ref(false)
const list = ref<Post[]>([])
const keyword = ref('')
const filters = ref<Record<string, unknown>>({})
const page = ref(1)
const total = ref(0)
const finished = ref(false)

const filterDefs = [
  { key: 'keyword', label: '关键词', type: 'text' as const },
  {
    key: 'isPublished',
    label: '发布',
    type: 'select' as const,
    options: [
      { label: '全部', value: '' },
      { label: '已发布', value: 1 },
      { label: '草稿', value: 0 },
    ],
  },
]

async function load(reset = true) {
  if (!guardAdmin()) return
  if (reset) {
    page.value = 1
    finished.value = false
    list.value = []
  }
  loading.value = true
  try {
    const data = await adminList('posts', {
      page: page.value,
      pageSize: 20,
      keyword: keyword.value || undefined,
      ...filters.value,
    })
    const p = normalizePagination<Post>(data, page.value, 20)
    list.value = reset ? p.list : [...list.value, ...p.list]
    total.value = p.total
    finished.value = list.value.length >= p.total
  }
  catch (e: unknown) {
    toast.error(e instanceof Error ? e.message : '加载失败')
  }
  finally {
    loading.value = false
  }
}

onShow(() => load(true))
onReachBottom(() => {
  if (finished.value || loading.value) return
  page.value += 1
  load(false)
})

function goCreate() {
  uni.navigateTo({ url: '/subPackages/admin/pages/posts/form?mode=create' })
}

function goEdit(item: Post) {
  uni.navigateTo({ url: `/subPackages/admin/pages/posts/form?mode=edit&id=${item.id}` })
}

async function togglePublish(item: Post) {
  const next = item.isPublished === 1 || item.isPublished === true ? 0 : 1
  try {
    await patchPostStatus(item.id, next)
    item.isPublished = next
    toast.success(next ? '已发布' : '已设为草稿')
  }
  catch (e: unknown) {
    toast.error(e instanceof Error ? e.message : '状态更新失败')
  }
}

function onDelete(item: Post) {
  dialog.confirm({ title: '确认删除', msg: `确定删除「${item.title}」吗？` }).then(async () => {
    try {
      await adminDelete('posts', item.id)
      toast.success('已删除')
      load(true)
    }
    catch (e: unknown) {
      toast.error(e instanceof Error ? e.message : '删除失败')
    }
  }).catch(() => {})
}
</script>

<template>
  <AppPageShell admin>
    <AppNavbar title="文章管理" show-back />
    <view class="page-pad">
      <AdminFilterBar
        v-model:keyword="keyword"
        v-model="filters"
        :filters="filterDefs"
        @search="load(true)"
        @reset="load(true)"
      />
      <view v-for="item in list" :key="String(item.id)" class="admin-card row" @click="goEdit(item)">
        <view class="main">
          <view class="title-row">
            <text class="title">{{ item.title }}</text>
            <AdminStatusBadge
              :value="item.isPublished"
              :map="{ '1': '已发布', '0': '草稿', true: '已发布', false: '草稿' }"
              clickable
              @click="togglePublish(item)"
            />
          </view>
          <text class="sub text-art-muted">
            {{ item.categoryName || '未分类' }} · {{ item.date || '' }}
          </text>
        </view>
        <wd-button size="small" type="warning" plain @click.stop="onDelete(item)">删除</wd-button>
      </view>
      <wd-loading v-if="loading" />
      <wd-empty v-if="!loading && !list.length" description="暂无文章" />
    </view>
    <view class="fab" @click="goCreate">
      <wd-icon name="plus" size="24px" color="#fff" />
    </view>
  </AppPageShell>
</template>

<style scoped lang="scss">
.page-pad { padding: 24rpx 32rpx 120rpx; }
.row {
  padding: 24rpx 28rpx;
  margin-bottom: 16rpx;
  display: flex;
  align-items: center;
  gap: 16rpx;
}
.main { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 8rpx; }
.title-row { display: flex; align-items: center; gap: 12rpx; }
.title {
  flex: 1;
  font-size: 30rpx;
  color: rgb(var(--art-text));
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.sub { font-size: 24rpx; }
.fab {
  position: fixed;
  right: 40rpx;
  bottom: calc(40rpx + env(safe-area-inset-bottom));
  width: 96rpx;
  height: 96rpx;
  border-radius: 50%;
  background: rgb(var(--art-accent));
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
}
</style>
