<template>
  <div class="store-page">
    <Breadcrumb />
    <a-card title="文章管理">
      <a-space wrap style="margin-bottom: 12px;">
        <a-button type="primary" @click="openCreate">新增文章</a-button>
        <a-select v-model="filterType" placeholder="分类" style="width: 140px;" allow-clear @change="onFilterChange">
          <a-option value="all">全部分类</a-option>
          <a-option v-for="cat in categories" :key="cat.slug" :value="cat.slug">{{ cat.name }}</a-option>
        </a-select>
        <a-select v-model="filterState" style="width: 120px;" @change="onFilterChange">
          <a-option :value="1">已发布</a-option>
          <a-option :value="0">草稿</a-option>
        </a-select>
      </a-space>

      <a-table
        :bordered="false"
        :data="data"
        :loading="loading"
        :pagination="{
          showPageSize: true,
          showTotal: true,
          pageSize: pagination.pagesize,
          current: pagination.current,
          total: pagination.total
        }"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #columns>
          <a-table-column title="封面" :width="70">
            <template #cell="{ record }">
              <GoodsEmoji :icon="record.cover" size="sm" :fallback="DEFAULT_ARTICLE_EMOJI" aria-label="文章封面" />
            </template>
          </a-table-column>
          <a-table-column title="标题" data-index="title" :width="200" ellipsis tooltip />
          <a-table-column title="标识 (slug)" data-index="slug" :width="180" ellipsis tooltip />
          <a-table-column title="分类" :width="100">
            <template #cell="{ record }">{{ categoryName(record.type) }}</template>
          </a-table-column>
          <a-table-column title="状态" :width="90">
            <template #cell="{ record }">
              <a-tag :color="record.state === 1 ? 'green' : 'gray'">{{ record.state === 1 ? '已发布' : '草稿' }}</a-tag>
            </template>
          </a-table-column>
          <a-table-column title="浏览" data-index="views" :width="70" />
          <a-table-column title="作者" data-index="author" :width="100" />
          <a-table-column title="时间" :width="160">
            <template #cell="{ record }">{{ formatTime(record.time) }}</template>
          </a-table-column>
          <a-table-column title="操作" :width="220">
            <template #cell="{ record }">
              <a-space wrap>
                <a-button size="mini" @click="openEdit(record)">编辑</a-button>
                <a-button size="mini" @click="togglePublic(record)">{{ record.state === 1 ? '撤回' : '发布' }}</a-button>
                <a-button status="danger" size="mini" @click="remove(record)">删除</a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <a-modal v-model:visible="editorVisible" :title="form.id ? '编辑文章' : '新增文章'" width="980px" @before-ok="submitEditor">
      <a-form :model="form" layout="vertical">
        <a-form-item label="标题" required>
          <a-input v-model="form.title" allow-clear />
        </a-form-item>
        <a-form-item v-if="!form.id" label="文章标识 (slug)" required>
          <a-input-group>
            <a-input v-model="form.slug" allow-clear placeholder="小写字母、数字、连字符" />
            <a-button @click="generateSlug">根据标题生成</a-button>
          </a-input-group>
        </a-form-item>
        <a-form-item v-else label="文章标识 (slug)">
          <a-input v-model="form.slug" readonly />
        </a-form-item>
        <a-form-item label="分类" required>
          <a-select v-model="form.type" placeholder="选择分类">
            <a-option v-for="cat in categories" :key="cat.slug" :value="cat.slug">{{ cat.name }}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="封面（Emoji）" required>
          <div class="emoji-panel">
            <div class="emoji-panel__preview">
              <span class="emoji-panel__emoji">{{ displayEmoji }}</span>
              <span class="emoji-panel__hint">当前封面</span>
            </div>
            <div class="emoji-panel__main">
              <div class="emoji-panel__label">快速选择</div>
              <div class="emoji-grid">
                <button
                  v-for="emoji in presetEmojis"
                  :key="emoji"
                  type="button"
                  class="emoji-grid__item"
                  :class="{ 'emoji-grid__item--active': form.cover === emoji }"
                  :title="emoji"
                  @click="form.cover = emoji"
                >
                  {{ emoji }}
                </button>
              </div>
              <div class="emoji-panel__label emoji-panel__label--custom">自定义</div>
              <a-input
                v-model="form.cover"
                class="emoji-custom-input"
                placeholder="输入或粘贴一个 emoji"
                :max-length="8"
                allow-clear
              />
            </div>
          </div>
        </a-form-item>
        <a-form-item label="摘要">
          <a-textarea v-model="form.describe" :auto-size="{ minRows: 2 }" />
        </a-form-item>
        <a-form-item label="发布状态">
          <a-radio-group v-model="form.state">
            <a-radio :value="1">发布</a-radio>
            <a-radio :value="0">草稿</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="正文（富文本）" required>
          <WangEditor v-model="form.content" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { reactive, ref, computed, onMounted } from 'vue'
import { Modal, Notification, Message } from '@arco-design/web-vue'
import WangEditor from '@/components/Editor/WangEditor.vue'
import GoodsEmoji from '@/components/store/GoodsEmoji.vue'
import { slugify, isValidSlug } from '@/utils/slugify'
import { DEFAULT_ARTICLE_EMOJI, getArticleEmoji } from '@/utils/storeFormat'
import {
  getAdminArticleList,
  getAdminArticle,
  saveAdminArticle,
  deleteAdminArticle,
  toggleAdminArticlePublic,
  getAdminCategoryList
} from '@/api/article'

const presetEmojis = ['📄', '📖', '📋', '❓', '📰', '🏃', '💡', '✅', '⚡', '✨']

const loading = ref(false)
const data = ref([])
const categories = ref([])
const pagination = reactive({ total: 0, current: 1, pagesize: 20 })
const filterType = ref('all')
const filterState = ref(1)

const editorVisible = ref(false)
const form = reactive({
  id: null,
  slug: '',
  title: '',
  cover: '',
  describe: '',
  content: '',
  type: '',
  state: 1
})

const displayEmoji = computed(() => getArticleEmoji(form.cover))

const formatTime = (time) => new Date(Number(time)).toLocaleString('zh-CN')
const categoryName = (slug) => categories.value.find(c => c.slug === slug)?.name || slug

const loadCategories = async () => {
  const res = await getAdminCategoryList({})
  if (res?.code === 0) {
    categories.value = res.data || []
    if (!form.type && categories.value.length) form.type = categories.value[0].slug
  }
}

const getList = async () => {
  loading.value = true
  try {
    const res = await getAdminArticleList({
      pagesize: pagination.pagesize,
      current: pagination.current,
      type: filterType.value || 'all',
      state: filterState.value
    })
    if (!res || res.code !== 0) {
      Notification.error({ title: '获取文章列表失败', content: res?.msg ?? '请稍后再试' })
      return
    }
    data.value = res.data || []
    pagination.total = res.pagination?.total || 0
  } finally {
    loading.value = false
  }
}

const onFilterChange = () => {
  pagination.current = 1
  getList()
}

const generateSlug = () => {
  if (!form.title) return Message.warning('请先填写标题')
  form.slug = slugify(form.title)
}

const openCreate = () => {
  form.id = null
  form.slug = ''
  form.title = ''
  form.cover = DEFAULT_ARTICLE_EMOJI
  form.describe = ''
  form.content = ''
  form.state = 1
  form.type = categories.value[0]?.slug || ''
  editorVisible.value = true
}

const openEdit = async (record) => {
  const res = await getAdminArticle({ id: record.id })
  if (!res || res.code !== 0) {
    Notification.error({ title: '获取文章失败', content: res?.msg ?? '请稍后再试' })
    return
  }
  const a = res.data
  form.id = a.id
  form.slug = a.slug
  form.title = a.title
  form.cover = getArticleEmoji(a.cover)
  form.describe = a.describe || ''
  form.content = a.content || ''
  form.type = a.type
  form.state = a.state
  editorVisible.value = true
}

const submitEditor = async () => {
  if (!form.title || !form.cover || !form.content || !form.type) {
    Message.error('请填写必填项')
    return false
  }
  if (!form.id) {
    if (!form.slug || !isValidSlug(form.slug)) {
      Message.error('请填写有效的文章标识 (slug)')
      return false
    }
  }
  const payload = {
    id: form.id,
    slug: form.slug,
    title: form.title,
    cover: getArticleEmoji(form.cover),
    describe: form.describe,
    content: form.content,
    type: form.type,
    state: form.state
  }
  const res = await saveAdminArticle(payload)
  if (!res || res.code !== 0) {
    Notification.error({ title: '保存失败', content: res?.msg ?? '请稍后再试' })
    return false
  }
  Message.success('保存成功')
  getList()
  return true
}

const togglePublic = async (record) => {
  const res = await toggleAdminArticlePublic({ id: record.id })
  if (!res || res.code !== 0) {
    Notification.error({ title: '操作失败', content: res?.msg ?? '请稍后再试' })
    return
  }
  Message.success('操作成功')
  getList()
}

const remove = (record) => {
  Modal.confirm({
    title: '删除文章',
    content: `确定删除「${record.title}」吗？`,
    onOk: async () => {
      const res = await deleteAdminArticle({ id: record.id })
      if (!res || res.code !== 0) {
        Notification.error({ title: '删除失败', content: res?.msg ?? '请稍后再试' })
        return
      }
      Message.success('删除成功')
      getList()
    }
  })
}

const onPageChange = (page) => {
  pagination.current = page
  getList()
}
const onPageSizeChange = (size) => {
  pagination.pagesize = size
  pagination.current = 1
  getList()
}

onMounted(async () => {
  await loadCategories()
  getList()
})
</script>

<style scoped lang="less">
.emoji-panel {
  display: flex;
  gap: 24px;
  padding: 20px;
  background: var(--color-fill-1);
  border: 1px solid var(--color-border-2);
  border-radius: 12px;
  align-items: stretch;

  @media (max-width: 640px) {
    flex-direction: column;
  }

  &__preview {
    flex-shrink: 0;
    width: 120px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 8px;
    background: var(--color-bg-2);
    border-radius: 12px;
    border: 1px solid var(--color-border-2);
  }

  &__emoji {
    font-size: 3.5rem;
    line-height: 1;
  }

  &__hint {
    font-size: 12px;
    color: var(--color-text-3);
  }

  &__main {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  &__label {
    font-size: 13px;
    font-weight: 500;
    color: var(--color-text-2);

    &--custom {
      margin-top: 4px;
    }
  }
}

.emoji-grid {
  display: grid;
  grid-template-columns: repeat(5, 52px);
  gap: 10px;

  @media (max-width: 480px) {
    grid-template-columns: repeat(5, 1fr);
  }

  &__item {
    width: 52px;
    height: 52px;
    padding: 0;
    font-size: 26px;
    line-height: 1;
    border: 2px solid var(--color-border-2);
    border-radius: 10px;
    background: var(--color-bg-2);
    cursor: pointer;
    transition: border-color 0.2s, background 0.2s, transform 0.15s;
    display: flex;
    align-items: center;
    justify-content: center;

    @media (max-width: 480px) {
      width: 100%;
      aspect-ratio: 1;
      height: auto;
    }

    &:hover {
      transform: scale(1.06);
      border-color: rgb(var(--primary-5));
    }

    &--active {
      border-color: rgb(var(--primary-6));
      background: var(--color-primary-light-1);
      box-shadow: 0 0 0 2px rgba(var(--primary-6), 0.15);
    }
  }
}

.emoji-custom-input {
  max-width: 320px;
  height: 40px;
}
</style>
