<template>
  <div class="articles-page">
    <div class="page-header">
      <el-button type="primary" @click="showAdd = true">创建资讯</el-button>
    </div>
    <div class="table-card">
      <el-table :data="paginatedArticles">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="标题" />
        <el-table-column prop="is_pinned" label="置顶" width="80">
          <template #default="{ row }"><el-tag :type="row.is_pinned ? 'danger' : 'info'" size="small">{{ row.is_pinned ? '是' : '否' }}</el-tag></template>
        </el-table-column>
        <el-table-column prop="is_published" label="发布" width="80">
          <template #default="{ row }"><el-tag :type="row.is_published ? 'success' : 'info'" size="small">{{ row.is_published ? '是' : '否' }}</el-tag></template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">{{ formatDate(row.created_at) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="editArticle(row)">编辑</el-button>
            <el-button link :type="row.is_pinned ? 'warning' : 'success'" size="small" @click="togglePin(row.id)">{{ row.is_pinned ? '取消置顶' : '置顶' }}</el-button>
            <el-button link type="danger" size="small" @click="deleteArticle(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-wrap">
        <el-pagination
          v-model:current-page="page"
          :page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next"
          @current-change="handlePageChange"
        />
      </div>
    </div>
    <el-dialog v-model="showAdd" :title="editing ? '编辑资讯' : '创建资讯'" width="700px">
      <el-form :model="form" label-width="100px">
        <el-form-item label="标题"><el-input v-model="form.title" /></el-form-item>
        <el-form-item label="摘要"><el-input v-model="form.summary" type="textarea" :rows="2" /></el-form-item>
        <el-form-item label="内容"><el-input v-model="form.content" type="textarea" :rows="10" /></el-form-item>
        <el-form-item label="封面图">
          <el-upload
            class="cover-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
            :before-upload="beforeCoverUpload"
            accept="image/*"
          >
            <img v-if="form.cover_image" :src="getImageUrl(form.cover_image)" class="cover-image" />
            <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="cover-tip">建议尺寸: 800x400px，支持 jpg、png、webp 格式</div>
        </el-form-item>
        <el-form-item label="排序"><el-input-number v-model="form.sort_order" /></el-form-item>
        <el-form-item label="发布"><el-switch v-model="form.is_published" /></el-form-item>
        <el-form-item label="置顶"><el-switch v-model="form.is_pinned" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAdd = false">取消</el-button>
        <el-button type="primary" @click="saveArticle">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { adminApi } from '../../api'
import { getImageUrl } from '../../utils/image'

const uploadUrl = import.meta.env.VITE_API_BASE_URL + '/upload'
const uploadHeaders = { Authorization: `Bearer ${localStorage.getItem('token')}` }

const articles = ref<any[]>([])
const showAdd = ref(false)
const editing = ref<any>(null)
const page = ref(1)
const pageSize = 20
const total = computed(() => articles.value.length)
const paginatedArticles = computed(() => {
  const start = (page.value - 1) * pageSize
  return articles.value.slice(start, start + pageSize)
})
const form = reactive({ title: '', content: '', summary: '', cover_image: '', sort_order: 0, is_published: true, is_pinned: false })

function handlePageChange() {
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

function beforeCoverUpload(file: File) {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

function handleCoverSuccess(response: any) {
  if (response.url) {
    form.cover_image = response.url
    ElMessage.success('封面上传成功')
  } else {
    ElMessage.error('上传失败')
  }
}

function formatDate(date: string) {
  if (!date) return '-'
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

async function fetchArticles() {
  const res: any = await adminApi.getArticles()
  articles.value = res.data || []
}

function editArticle(row: any) {
  editing.value = row
  Object.assign(form, { title: row.title, content: row.content, summary: row.summary || '', cover_image: row.cover_image || '', sort_order: row.sort_order, is_published: row.is_published, is_pinned: row.is_pinned })
  showAdd.value = true
}

async function saveArticle() {
  if (editing.value) {
    await adminApi.updateArticle(editing.value.id, form)
  } else {
    await adminApi.createArticle(form)
  }
  ElMessage.success('保存成功')
  showAdd.value = false
  editing.value = null
  await fetchArticles()
}

async function togglePin(id: number) {
  await adminApi.togglePinArticle(id)
  ElMessage.success('操作成功')
  await fetchArticles()
}

async function deleteArticle(id: number) {
  await ElMessageBox.confirm('确定删除？', '确认')
  await adminApi.deleteArticle(id)
  ElMessage.success('删除成功')
  await fetchArticles()
}

onMounted(fetchArticles)
</script>

<style scoped lang="scss">
.articles-page { padding: 0; }
.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; }
.table-card { background: #2d2d44; border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 12px; padding: 20px; }

.cover-uploader {
  :deep(.el-upload) {
    border: 1px dashed rgba(255, 255, 255, 0.2);
    border-radius: 8px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s;
    width: 200px;
    height: 120px;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      border-color: #4e6ef2;
    }
  }
}

.cover-image {
  width: 200px;
  height: 120px;
  object-fit: cover;
  border-radius: 8px;
}

.cover-uploader-icon {
  font-size: 28px;
  color: rgba(255, 255, 255, 0.4);
}

.cover-tip {
  margin-top: 8px;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.4);
}

.pagination-wrap {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.pagination-wrap :deep(.el-pagination) {
  --el-pagination-bg-color: rgba(255, 255, 255, 0.06);
  --el-pagination-text-color: rgba(255, 255, 255, 0.6);
  --el-pagination-button-disabled-bg-color: rgba(255, 255, 255, 0.04);
  --el-pagination-button-bg-color: rgba(255, 255, 255, 0.06);
  --el-pagination-hover-color: #4e6ef2;
}

.pagination-wrap :deep(.el-pagination .el-pager li) {
  background: rgba(255, 255, 255, 0.06);
  color: rgba(255, 255, 255, 0.6);
  border-radius: 6px;
  margin: 0 4px;
}

.pagination-wrap :deep(.el-pagination .el-pager li:hover),
.pagination-wrap :deep(.el-pagination .el-pager li.is-active) {
  background: #4e6ef2;
  color: #fff;
}

.pagination-wrap :deep(.el-pagination .btn-prev),
.pagination-wrap :deep(.el-pagination .btn-next) {
  background: rgba(255, 255, 255, 0.06);
  color: rgba(255, 255, 255, 0.6);
  border-radius: 6px;
}

.pagination-wrap :deep(.el-pagination .btn-prev:hover),
.pagination-wrap :deep(.el-pagination .btn-next:hover) {
  background: rgba(78, 110, 242, 0.2);
  color: #4e6ef2;
}

.pagination-wrap :deep(.el-pagination__total) {
  color: rgba(255, 255, 255, 0.5);
}
</style>
