<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { announcementApi } from '@/api/office.js'

const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const submitLoading = ref(false)
const isEdit = ref(false)

const searchForm = reactive({ type: '', publish_status: '' })
const pagination = reactive({ page: 1, per_page: 20 })

const formRef = ref(null)
const form = reactive({ id: null, title: '', content: '', type: 1, is_top: 0 })

const typeMap = { 1: '通知', 2: '公告', 3: '制度' }
const typeTagType = { 1: '', 2: 'warning', 3: 'danger' }
const publishStatusMap = { 0: '草稿', 1: '已发布' }
const publishStatusType = { 0: 'info', 1: 'success' }

const formRules = {
  title: [{ required: true, message: '请输入标题' }]
}

async function fetchList() {
  loading.value = true
  try {
    const res = await announcementApi.getList({ ...searchForm, ...pagination })
    tableData.value = res.data?.list || res.data?.data || []
    total.value = res.data?.total || 0
  } finally { loading.value = false }
}

function handleSearch() { pagination.page = 1; fetchList() }
function handleReset() { Object.assign(searchForm, { type: '', publish_status: '' }); handleSearch() }

function handleAdd() {
  isEdit.value = false
  Object.assign(form, { id: null, title: '', content: '', type: 1, is_top: 0 })
  dialogVisible.value = true
}

function handleEdit(row) {
  isEdit.value = true
  Object.assign(form, { id: row.id, title: row.title, content: row.content, type: row.type, is_top: row.is_top })
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      if (isEdit.value) { await announcementApi.update(form.id, form) } else { await announcementApi.create(form) }
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功'); dialogVisible.value = false; fetchList()
    } finally { submitLoading.value = false }
  })
}

async function handlePublish(row) {
  await ElMessageBox.confirm('确定发布该公告吗？发布后不可编辑或删除。', '发布确认', { type: 'warning' })
  await announcementApi.publish(row.id)
  ElMessage.success('发布成功'); fetchList()
}

async function handleDelete(row) {
  await ElMessageBox.confirm('确定删除该公告吗？', '删除确认', { type: 'warning' })
  await announcementApi.delete(row.id); ElMessage.success('删除成功'); fetchList()
}

function handlePageChange(val) { pagination.page = val; fetchList() }
function handleSizeChange(val) { pagination.per_page = val; pagination.page = 1; fetchList() }
onMounted(() => { fetchList() })
</script>

<template>
  <div class="p-6 space-y-4">
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 flex items-center flex-wrap gap-3">
      <el-select v-model="searchForm.type" placeholder="类型" clearable style="width:120px">
        <el-option v-for="(v, k) in typeMap" :key="k" :label="v" :value="Number(k)" />
      </el-select>
      <el-select v-model="searchForm.publish_status" placeholder="发布状态" clearable style="width:130px">
        <el-option v-for="(v, k) in publishStatusMap" :key="k" :label="v" :value="Number(k)" />
      </el-select>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm">
      <div class="flex items-center justify-between px-5 py-4 border-b border-gray-50">
        <div class="flex items-center gap-3">
          <span class="font-medium text-gray-700">公告列表</span>
        </div>
        <el-button type="primary" @click="handleAdd">新增公告</el-button>
      </div>
      <div class="px-2">
        <el-table v-loading="loading" :data="tableData" style="width:100%">
          <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
          <el-table-column label="类型" width="90" align="center">
            <template #default="{ row }">
              <el-tag :type="typeTagType[row.type]" size="small">{{ typeMap[row.type] }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="置顶" width="70" align="center">
            <template #default="{ row }">{{ row.is_top ? '是' : '否' }}</template>
          </el-table-column>
          <el-table-column label="发布状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="publishStatusType[row.publish_status]" size="small">{{ publishStatusMap[row.publish_status] }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="作者" min-width="100">
            <template #default="{ row }">{{ row.author?.name || '-' }}</template>
          </el-table-column>
          <el-table-column prop="published_at" label="发布时间" min-width="160" />
          <el-table-column label="操作" width="200" fixed="right" align="center">
            <template #default="{ row }">
              <el-button v-if="row.publish_status === 0" size="small" type="success" text @click="handlePublish(row)">发布</el-button>
              <el-button v-if="row.publish_status === 0" size="small" type="primary" text @click="handleEdit(row)">编辑</el-button>
              <el-button v-if="row.publish_status === 0" size="small" type="danger" text @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="px-5 py-3 border-t border-gray-50">
        <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.per_page" :total="total" :page-sizes="[10,20,50]" layout="total,sizes,prev,pager,next,jumper" background @current-change="handlePageChange" @size-change="handleSizeChange" />
      </div>
    </div>
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑公告' : '新增公告'" width="600px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="form.content" type="textarea" :rows="5" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="form.type" style="width:100%">
            <el-option v-for="(v, k) in typeMap" :key="k" :label="v" :value="Number(k)" />
          </el-select>
        </el-form-item>
        <el-form-item label="置顶">
          <el-switch v-model="form.is_top" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
