<script setup lang="ts">
/**
 * 专栏表单：封面/启用 + 编辑态挂载文章（add/remove）。
 */
import { computed, reactive, ref } from 'vue'
import { onLoad, 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 AdminMediaPicker from '../../components/AdminMediaPicker.vue'
import { useAdminGuard } from '../../composables/useAdminGuard'
import {
  addPostToColumn,
  adminCreate,
  adminGet,
  adminList,
  adminUpdate,
  getAdminColumnPosts,
  normalizeAdminList,
  removePostFromColumn,
  type Column,
  type Post,
} from '@/api'

const toast = useToast()
const { guardAdmin } = useAdminGuard()
const mode = ref<'create' | 'edit'>('create')
const id = ref('')
const loading = ref(false)
const submitting = ref(false)
const linkedPosts = ref<Post[]>([])
const allPosts = ref<Post[]>([])
const postKeyword = ref('')

const form = reactive({
  name: '',
  cover: '',
  description: '',
  sortOrder: 0,
  isActive: 1,
})

const pageTitle = computed(() => (mode.value === 'create' ? '新建专栏' : '编辑专栏'))
const filteredPosts = computed(() => {
  const kw = postKeyword.value.trim().toLowerCase()
  const linkedIds = new Set(linkedPosts.value.map(p => Number(p.id)))
  return allPosts.value.filter((p) => {
    if (linkedIds.has(Number(p.id))) return false
    if (!kw) return true
    return String(p.title || '').toLowerCase().includes(kw)
  }).slice(0, 30)
})

async function load() {
  if (!guardAdmin()) return
  loading.value = true
  try {
    const postData = await adminList('posts', { page: 1, pageSize: 200 })
    allPosts.value = normalizeAdminList(postData) as Post[]
    if (mode.value === 'edit' && id.value) {
      const data = await adminGet('columns', id.value) as Column
      form.name = String(data.name || data.title || '')
      form.cover = String(data.cover || '')
      form.description = String(data.description || '')
      form.sortOrder = Number(data.sortOrder || 0)
      form.isActive = data.isActive === 0 || data.isActive === false ? 0 : 1
      linkedPosts.value = await getAdminColumnPosts(id.value)
    }
  }
  catch (e: unknown) {
    toast.error(e instanceof Error ? e.message : '加载失败')
  }
  finally {
    loading.value = false
  }
}

onLoad((q) => {
  mode.value = q?.mode === 'edit' ? 'edit' : 'create'
  id.value = String(q?.id || '')
})
onShow(load)

async function onSubmit() {
  if (!form.name.trim()) {
    toast.show('请填写名称')
    return
  }
  submitting.value = true
  try {
    const payload = { ...form }
    if (mode.value === 'edit' && id.value) {
      await adminUpdate('columns', id.value, payload)
      toast.success('已保存')
    }
    else {
      const created = await adminCreate('columns', payload) as Column
      if (created?.id) id.value = String(created.id)
      mode.value = 'edit'
      toast.success('已创建，可继续挂载文章')
    }
  }
  catch (e: unknown) {
    toast.error(e instanceof Error ? e.message : '保存失败')
  }
  finally {
    submitting.value = false
  }
}

async function addPost(post: Post) {
  if (!id.value) {
    toast.show('请先保存专栏')
    return
  }
  try {
    await addPostToColumn(id.value, post.id)
    linkedPosts.value.push(post)
    toast.success('已添加')
  }
  catch (e: unknown) {
    toast.error(e instanceof Error ? e.message : '添加失败')
  }
}

async function removePost(post: Post) {
  if (!id.value) return
  try {
    await removePostFromColumn(id.value, post.id)
    linkedPosts.value = linkedPosts.value.filter(p => Number(p.id) !== Number(post.id))
    toast.success('已移除')
  }
  catch (e: unknown) {
    toast.error(e instanceof Error ? e.message : '移除失败')
  }
}
</script>

<template>
  <AppPageShell admin>
    <AppNavbar :title="pageTitle" show-back />
    <view class="page-pad">
      <view class="admin-card form-card">
        <wd-input v-model="form.name" label="名称" clearable />
        <AdminMediaPicker v-model="form.cover" label="封面" />
        <wd-input v-model="form.sortOrder" label="排序" type="number" />
        <view class="switch-row">
          <text>启用</text>
          <wd-switch :model-value="!!form.isActive" @change="(v: boolean | { value: boolean }) => form.isActive = (typeof v === 'boolean' ? v : v.value) ? 1 : 0" />
        </view>
        <wd-textarea v-model="form.description" label="描述" />
        <wd-button
          block
          type="primary"
          :loading="submitting"
          custom-style="margin-top:24rpx;background:#d4b383;border-color:#d4b383;"
          @click="onSubmit"
        >
          保存
        </wd-button>
      </view>

      <view v-if="mode === 'edit' && id" class="admin-card form-card" style="margin-top: 20rpx;">
        <text class="section-title" style="font-size: 30rpx;">专栏文章</text>
        <view v-for="p in linkedPosts" :key="String(p.id)" class="post-row">
          <text class="ptitle">{{ p.title }}</text>
          <wd-button size="small" type="warning" plain @click="removePost(p)">移除</wd-button>
        </view>
        <wd-input v-model="postKeyword" label="搜索添加" placeholder="文章标题" clearable />
        <view v-for="p in filteredPosts" :key="`a-${p.id}`" class="post-row">
          <text class="ptitle">{{ p.title }}</text>
          <wd-button size="small" @click="addPost(p)">添加</wd-button>
        </view>
      </view>
      <wd-loading v-if="loading" />
    </view>
  </AppPageShell>
</template>

<style scoped lang="scss">
.page-pad { padding: 24rpx 32rpx 80rpx; }
.form-card { padding: 24rpx; }
.switch-row {
  display: flex; justify-content: space-between; align-items: center;
  padding: 20rpx 0; color: rgb(var(--art-text));
}
.post-row {
  display: flex; align-items: center; gap: 12rpx;
  padding: 16rpx 0; border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}
.ptitle {
  flex: 1; font-size: 26rpx; color: rgb(var(--art-text));
  overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
</style>
