<script setup lang="ts">
/**
 * 视频专辑表单：基础字段 + 编辑态视频多选。
 */
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 {
  adminCreate,
  adminGet,
  adminList,
  adminUpdate,
  getAlbumVideoIds,
  normalizeAdminList,
  type VideoAlbum,
  type VideoItem,
} 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 categories = ref<{ id: number, name: string }[]>([])
const videos = ref<VideoItem[]>([])
const selectedIds = ref<number[]>([])

const form = reactive({
  name: '',
  categoryId: '' as string | number,
  cover: '',
  description: '',
  sortOrder: 0,
  isActive: 1,
})

const pageTitle = computed(() => (mode.value === 'create' ? '新建专辑' : '编辑专辑'))

async function load() {
  if (!guardAdmin()) return
  loading.value = true
  try {
    categories.value = normalizeAdminList(await adminList('video-categories')) as { id: number, name: string }[]
    videos.value = normalizeAdminList(await adminList('videos')) as VideoItem[]
    if (mode.value === 'edit' && id.value) {
      const data = await adminGet('video-albums', id.value) as VideoAlbum
      form.name = String(data.name || '')
      form.categoryId = data.categoryId || ''
      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
      try {
        const ids = await getAlbumVideoIds(id.value)
        selectedIds.value = Array.isArray(ids) ? ids.map(Number) : []
      }
      catch {
        selectedIds.value = Array.isArray(data.videoIds) ? data.videoIds.map(Number) : []
      }
    }
  }
  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)

function toggleVideo(vid: string | number) {
  const n = Number(vid)
  const i = selectedIds.value.indexOf(n)
  if (i >= 0) selectedIds.value.splice(i, 1)
  else selectedIds.value.push(n)
}

async function onSubmit() {
  if (!form.name.trim()) {
    toast.show('请填写名称')
    return
  }
  submitting.value = true
  try {
    const payload = {
      name: form.name,
      categoryId: form.categoryId ? Number(form.categoryId) : undefined,
      cover: form.cover,
      description: form.description,
      sortOrder: Number(form.sortOrder || 0),
      isActive: form.isActive,
      videoIds: selectedIds.value,
    }
    if (mode.value === 'edit' && id.value) await adminUpdate('video-albums', id.value, payload)
    else await adminCreate('video-albums', payload)
    toast.success('已保存')
    setTimeout(() => uni.navigateBack(), 400)
  }
  catch (e: unknown) {
    toast.error(e instanceof Error ? e.message : '保存失败')
  }
  finally {
    submitting.value = false
  }
}

function catLabel() {
  return categories.value.find(c => String(c.id) === String(form.categoryId))?.name || '选择分类'
}
</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 />
        <wd-picker
          :columns="[categories.map(c => ({ label: c.name, value: c.id }))]"
          @confirm="({ value }: { value: unknown[] }) => { form.categoryId = (value?.[0] as { value?: number })?.value ?? value?.[0] as number }"
        >
          <view class="picker-row"><text>分类</text><text class="val">{{ catLabel() }}</text></view>
        </wd-picker>
        <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) => form.isActive = v ? 1 : 0" />
        </view>
        <wd-textarea v-model="form.description" label="描述" />
        <view v-if="mode === 'edit'" class="section">
          <text class="label text-art-muted">关联视频 ({{ selectedIds.length }})</text>
          <view class="tag-wrap">
            <view
              v-for="v in videos"
              :key="String(v.id)"
              class="tag"
              :class="{ on: selectedIds.includes(Number(v.id)) }"
              @click="toggleVideo(v.id)"
            >
              {{ v.title }}
            </view>
          </view>
        </view>
        <wd-button
          block
          type="primary"
          :loading="submitting"
          custom-style="margin-top:24rpx;background:#d4b383;border-color:#d4b383;"
          @click="onSubmit"
        >
          保存
        </wd-button>
      </view>
      <wd-loading v-if="loading" />
    </view>
  </AppPageShell>
</template>

<style scoped lang="scss">
.page-pad { padding: 24rpx 32rpx 80rpx; }
.form-card { padding: 24rpx; }
.picker-row, .switch-row {
  display: flex; justify-content: space-between; align-items: center;
  padding: 20rpx 0; color: rgb(var(--art-text));
  border-bottom: 1px solid rgba(255, 255, 255, 0.06);
}
.val { color: rgba(255, 255, 255, 0.6); }
.section { margin-top: 16rpx; }
.label { font-size: 24rpx; }
.tag-wrap { display: flex; flex-wrap: wrap; gap: 12rpx; margin-top: 12rpx; }
.tag {
  padding: 8rpx 16rpx; border-radius: 8rpx; font-size: 22rpx;
  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>
