<script setup lang="ts">
import { ref, onMounted } from 'vue'
import {
  getAllNotices,
  createNotice,
  updateNotice,
  deleteNotice,
  type SysNotice,
  type CreateNoticeDto,
  type UpdateNoticeDto,
} from '@/api/notice'
import AppLayout from '@/components/AppLayout.vue'
import { useToast } from '@/composables/useToast'

const toast = useToast()

// ==================== 列表数据 ====================
const notices = ref<SysNotice[]>([])
const loading = ref(false)

// ==================== 创建/编辑弹窗 ====================
const showFormModal = ref(false)
const formLoading = ref(false)
const isEditing = ref(false)
const editingId = ref<number | null>(null)
const form = ref<CreateNoticeDto>({
  noticeTitle: '',
  noticeType: '1',
  noticeContent: '',
  status: '0',
})
const formErrors = ref<Record<string, string>>({})

// ==================== 删除确认弹窗 ====================
const showDeleteModal = ref(false)
const deleteTarget = ref<SysNotice | null>(null)
const deleteLoading = ref(false)

// ==================== 类型/状态映射 ====================
const noticeTypeMap: Record<string, string> = { '1': '通知', '2': '公告' }
const statusMap: Record<string, string> = { '0': '正常', '1': '关闭' }

// ==================== 数据获取 ====================
async function fetchNotices() {
  loading.value = true
  try {
    notices.value = await getAllNotices()
  } catch (e: any) {
    notices.value = []
    const msg = e?.response?.data?.message || e?.message || '获取公告列表失败'
    toast.error(msg)
  } finally {
    loading.value = false
  }
}

// ==================== 创建/编辑 ====================
function openCreateModal() {
  isEditing.value = false
  editingId.value = null
  form.value = { noticeTitle: '', noticeType: '1', noticeContent: '', status: '0' }
  formErrors.value = {}
  showFormModal.value = true
}

function openEditModal(notice: SysNotice) {
  isEditing.value = true
  editingId.value = notice.id
  form.value = {
    noticeTitle: notice.noticeTitle,
    noticeType: notice.noticeType,
    noticeContent: notice.noticeContent,
    status: notice.status,
  }
  formErrors.value = {}
  showFormModal.value = true
}

function validateForm(): boolean {
  const errs: Record<string, string> = {}
  if (!form.value.noticeTitle.trim()) {
    errs.noticeTitle = '标题不能为空'
  }
  if (!form.value.noticeContent.trim()) {
    errs.noticeContent = '内容不能为空'
  }
  formErrors.value = errs
  return Object.keys(errs).length === 0
}

async function handleSubmit() {
  if (!validateForm()) return
  formLoading.value = true
  try {
    if (isEditing.value && editingId.value != null) {
      const updateData: UpdateNoticeDto = { ...form.value }
      await updateNotice(editingId.value, updateData)
      toast.success('公告更新成功')
    } else {
      await createNotice(form.value)
      toast.success('公告创建成功')
    }
    showFormModal.value = false
    fetchNotices()
  } catch (e: any) {
    const msg = e?.response?.data?.message || e?.message || '操作失败'
    toast.error(msg)
  } finally {
    formLoading.value = false
  }
}

// ==================== 删除 ====================
function openDeleteModal(notice: SysNotice) {
  deleteTarget.value = notice
  showDeleteModal.value = true
}

async function handleDelete() {
  if (!deleteTarget.value) return
  deleteLoading.value = true
  try {
    await deleteNotice(deleteTarget.value.id)
    toast.success('公告已删除')
    showDeleteModal.value = false
    fetchNotices()
  } catch (e: any) {
    const msg = e?.response?.data?.message || e?.message || '删除失败'
    toast.error(msg)
  } finally {
    deleteLoading.value = false
  }
}

// ==================== 工具函数 ====================
function formatTime(t: string | null): string {
  if (!t) return '--'
  return new Date(t).toLocaleString('zh-CN')
}

function truncateContent(content: string, max = 50): string {
  if (!content) return '--'
  return content.length > max ? content.slice(0, max) + '...' : content
}

// ==================== 初始化 ====================
onMounted(fetchNotices)
</script>

<template>
  <AppLayout>
    <!-- ========== 操作栏 ========== -->
    <div class="filter-bar">
      <div class="filter-row">
        <div class="filter-spacer"></div>
        <button class="btn btn-primary" @click="openCreateModal">
          <i class="fas fa-plus"></i> 新增公告
        </button>
      </div>
    </div>

    <!-- ========== 数据表格 ========== -->
    <div class="table-container">
      <table class="data-table" v-if="!loading">
        <thead>
          <tr>
            <th style="width: 60px">ID</th>
            <th style="width: 200px">标题</th>
            <th style="width: 80px">类型</th>
            <th style="width: 260px">内容</th>
            <th style="width: 80px">状态</th>
            <th style="width: 150px">创建时间</th>
            <th style="width: 160px">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="notices.length === 0">
            <td colspan="7" class="empty-cell">暂无公告数据</td>
          </tr>
          <tr v-for="n in notices" :key="n.id">
            <td>{{ n.id }}</td>
            <td class="text-bold">{{ n.noticeTitle }}</td>
            <td>
              <span class="type-badge" :class="n.noticeType === '2' ? 'announce' : 'notice'">
                {{ noticeTypeMap[n.noticeType] || n.noticeType }}
              </span>
            </td>
            <td class="text-ellipsis">{{ truncateContent(n.noticeContent) }}</td>
            <td>
              <span class="status-badge" :class="n.status === '0' ? 'active' : 'inactive'">
                {{ statusMap[n.status] || n.status }}
              </span>
            </td>
            <td>{{ formatTime(n.createdAt) }}</td>
            <td class="action-cell">
              <button class="btn btn-sm btn-outline" @click="openEditModal(n)">
                <i class="fas fa-edit"></i> 编辑
              </button>
              <button class="btn btn-sm btn-danger" @click="openDeleteModal(n)">
                <i class="fas fa-trash"></i>
              </button>
            </td>
          </tr>
        </tbody>
      </table>

      <div v-else class="loading-state">
        <i class="fas fa-spinner fa-spin"></i> 加载中...
      </div>
    </div>

    <!-- ========== 创建/编辑弹窗 ========== -->
    <Teleport to="body">
      <div class="modal-overlay" v-if="showFormModal" @click.self="showFormModal = false">
        <div class="modal-box">
          <div class="modal-header">
            <h3>
              <i :class="isEditing ? 'fas fa-edit' : 'fas fa-plus'"></i>
              {{ isEditing ? '编辑公告' : '新增公告' }}
            </h3>
            <button class="modal-close" @click="showFormModal = false">&times;</button>
          </div>
          <div class="modal-body">
            <div class="form-group">
              <label>公告标题 <span class="required">*</span></label>
              <input v-model="form.noticeTitle" class="form-input" placeholder="请输入公告标题" />
              <span class="field-error" v-if="formErrors.noticeTitle">{{ formErrors.noticeTitle }}</span>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>公告类型</label>
                <select v-model="form.noticeType" class="form-input">
                  <option value="1">通知</option>
                  <option value="2">公告</option>
                </select>
              </div>
              <div class="form-group">
                <label>状态</label>
                <select v-model="form.status" class="form-input">
                  <option value="0">正常</option>
                  <option value="1">关闭</option>
                </select>
              </div>
            </div>
            <div class="form-group">
              <label>公告内容 <span class="required">*</span></label>
              <textarea
                v-model="form.noticeContent"
                class="form-textarea"
                rows="6"
                placeholder="请输入公告内容"
              ></textarea>
              <span class="field-error" v-if="formErrors.noticeContent">{{ formErrors.noticeContent }}</span>
            </div>
          </div>
          <div class="modal-footer">
            <button class="btn btn-outline" @click="showFormModal = false">取消</button>
            <button class="btn btn-primary" :disabled="formLoading" @click="handleSubmit">
              <i class="fas fa-spinner fa-spin" v-if="formLoading"></i>
              {{ formLoading ? '保存中...' : '保存' }}
            </button>
          </div>
        </div>
      </div>
    </Teleport>

    <!-- ========== 删除确认弹窗 ========== -->
    <Teleport to="body">
      <div class="modal-overlay" v-if="showDeleteModal" @click.self="showDeleteModal = false">
        <div class="modal-box modal-sm">
          <div class="modal-header">
            <h3><i class="fas fa-exclamation-triangle" style="color: #e74c3c"></i> 确认删除</h3>
            <button class="modal-close" @click="showDeleteModal = false">&times;</button>
          </div>
          <div class="modal-body">
            <p class="modal-desc">
              确定要删除公告 <strong>{{ deleteTarget?.noticeTitle }}</strong> 吗？
            </p>
          </div>
          <div class="modal-footer">
            <button class="btn btn-outline" @click="showDeleteModal = false">取消</button>
            <button class="btn btn-danger" :disabled="deleteLoading" @click="handleDelete">
              <i class="fas fa-spinner fa-spin" v-if="deleteLoading"></i>
              {{ deleteLoading ? '删除中...' : '确认删除' }}
            </button>
          </div>
        </div>
      </div>
    </Teleport>
  </AppLayout>
</template>

<style scoped>
/* ==================== 筛选栏 ==================== */
.filter-bar {
  margin-bottom: 20px;
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter-spacer {
  flex: 1;
}

/* ==================== 表格 ==================== */
.table-container {
  background: #ffffff;
  border-radius: 12px;
  border: 1px solid #e9edf4;
  overflow: hidden;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.data-table th {
  background: #f8f9fc;
  color: #5a6a85;
  font-weight: 600;
  text-align: left;
  padding: 12px 16px;
  border-bottom: 1px solid #e9edf4;
  white-space: nowrap;
}

.data-table td {
  padding: 12px 16px;
  border-bottom: 1px solid #f0f3f8;
  color: #1e293b;
}

.data-table tbody tr:hover {
  background: #f8f9fc;
}

.empty-cell {
  text-align: center;
  color: #8b9ab0;
  padding: 40px 16px !important;
}

.text-bold {
  font-weight: 600;
}

.text-ellipsis {
  max-width: 240px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.action-cell {
  display: flex;
  gap: 6px;
}

.type-badge {
  display: inline-block;
  padding: 2px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

.type-badge.notice {
  background: #e3f2fd;
  color: #1565c0;
}

.type-badge.announce {
  background: #fff3e0;
  color: #e65100;
}

.status-badge {
  display: inline-block;
  padding: 2px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

.status-badge.active {
  background: #e8f5e9;
  color: #2e7d32;
}

.status-badge.inactive {
  background: #fce4e4;
  color: #c62828;
}

.loading-state {
  padding: 60px;
  text-align: center;
  color: #8b9ab0;
  font-size: 15px;
}

/* ==================== 按钮 ==================== */
.btn {
  padding: 8px 16px;
  border-radius: 8px;
  border: none;
  font-size: 14px;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
  transition: all 0.2s;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-primary {
  background: #4f7cff;
  color: #ffffff;
}

.btn-primary:hover:not(:disabled) {
  background: #3b5fd9;
}

.btn-outline {
  background: #ffffff;
  color: #4a5568;
  border: 1px solid #dde2eb;
}

.btn-outline:hover:not(:disabled) {
  background: #f0f3f8;
}

.btn-danger {
  background: #e74c3c;
  color: #ffffff;
}

.btn-danger:hover:not(:disabled) {
  background: #c0392b;
}

.btn-sm {
  padding: 5px 10px;
  font-size: 12px;
  border-radius: 6px;
}

/* ==================== 弹窗 ==================== */
.modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-box {
  background: #ffffff;
  border-radius: 14px;
  width: 560px;
  max-width: 90vw;
  max-height: 85vh;
  overflow-y: auto;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
}

.modal-box.modal-sm {
  width: 420px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px 16px;
  border-bottom: 1px solid #f0f3f8;
}

.modal-header h3 {
  font-size: 18px;
  color: #1e293b;
  display: flex;
  align-items: center;
  gap: 8px;
}

.modal-close {
  background: none;
  border: none;
  font-size: 24px;
  color: #8b9ab0;
  cursor: pointer;
  line-height: 1;
}

.modal-body {
  padding: 20px 24px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 16px 24px;
  border-top: 1px solid #f0f3f8;
}

.modal-desc {
  color: #5a6a85;
  line-height: 1.6;
  margin-bottom: 12px;
}

/* ==================== 表单 ==================== */
.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 6px;
  font-size: 13px;
  font-weight: 600;
  color: #5a6a85;
}

.required {
  color: #e74c3c;
}

.form-input {
  width: 100%;
  padding: 9px 14px;
  border: 1px solid #dde2eb;
  border-radius: 8px;
  font-size: 14px;
  outline: none;
  color: #1e293b;
  transition: border-color 0.2s;
  box-sizing: border-box;
}

.form-input:focus {
  border-color: #4f7cff;
}

.form-textarea {
  width: 100%;
  padding: 9px 14px;
  border: 1px solid #dde2eb;
  border-radius: 8px;
  font-size: 14px;
  outline: none;
  color: #1e293b;
  resize: vertical;
  font-family: inherit;
  transition: border-color 0.2s;
  box-sizing: border-box;
}

.form-textarea:focus {
  border-color: #4f7cff;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.field-error {
  display: block;
  margin-top: 4px;
  font-size: 12px;
  color: #e74c3c;
}
</style>
