<template>
  <div class="announcements-container">
    <div class="page-header">
      <h2>官方公告</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><plus /></el-icon>发布公告
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="公告标题">
          <el-input v-model="searchForm.title" placeholder="请输入公告标题" clearable />
        </el-form-item>
        <el-form-item label="发布时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            clearable
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="已发布" value="published" />
            <el-option label="草稿" value="draft" />
            <el-option label="已下线" value="offline" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        row-key="id"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="title" label="公告标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="publisher" label="发布人" width="120" align="center" />
        <el-table-column prop="publishTime" label="发布时间" width="180" align="center" />
        <el-table-column prop="viewCount" label="查看数" width="100" align="center" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleView(scope.row)">
              <el-icon><view /></el-icon>查看
            </el-button>
            <el-button type="primary" link @click="handleEdit(scope.row)">
              <el-icon><edit /></el-icon>编辑
            </el-button>
            <el-button 
              type="primary" 
              link 
              @click="handleChangeStatus(scope.row)"
              v-if="scope.row.status !== 'offline'"
            >
              <el-icon><turn-off /></el-icon>下线
            </el-button>
            <el-button 
              type="primary" 
              link 
              @click="handleDelete(scope.row)"
              v-if="scope.row.status === 'offline'"
            >
              <el-icon><delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 公告详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :before-close="handleDialogClose"
    >
      <div v-if="dialogType === 'view'" class="announcement-detail">
        <h2 class="detail-title">{{ currentAnnouncement.title }}</h2>
        <div class="detail-info">
          <span>发布人: {{ currentAnnouncement.publisher }}</span>
          <span>发布时间: {{ currentAnnouncement.publishTime }}</span>
          <span>状态: {{ getStatusText(currentAnnouncement.status) }}</span>
        </div>
        <div class="detail-content" v-html="currentAnnouncement.content"></div>
      </div>
      <div v-else>
        <el-form :model="announcementForm" label-width="120px" :rules="rules" ref="announcementFormRef">
          <el-form-item label="公告标题" prop="title">
            <el-input v-model="announcementForm.title" placeholder="请输入公告标题" />
          </el-form-item>
          <el-form-item label="公告内容" prop="content">
            <el-input
              v-model="announcementForm.content"
              type="textarea"
              :rows="10"
              placeholder="请输入公告内容"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="announcementForm.status">
              <el-radio label="published">立即发布</el-radio>
              <el-radio label="draft">保存为草稿</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer" v-if="dialogType !== 'view'">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { 
  Plus, Search, Refresh, View, Edit, TurnOff, Delete
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单
const searchForm = reactive({
  title: '',
  dateRange: [],
  status: ''
})

// 重置搜索
const resetSearch = () => {
  searchForm.title = ''
  searchForm.dateRange = []
  searchForm.status = ''
  handleSearch()
}

// 表格数据
const loading = ref(false)
const tableData = ref([])

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 处理页码变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchData()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchData()
}

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('') // 'add', 'edit', 'view'
const dialogTitle = computed(() => {
  if (dialogType.value === 'add') return '发布公告'
  if (dialogType.value === 'edit') return '编辑公告'
  return '公告详情'
})

// 当前选中的公告
const currentAnnouncement = ref({})

// 表单对象和规则
const announcementFormRef = ref(null)
const announcementForm = reactive({
  id: '',
  title: '',
  content: '',
  status: 'published'
})

const rules = {
  title: [{ required: true, message: '请输入公告标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入公告内容', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 状态标签样式
const getStatusType = (status) => {
  const map = {
    published: 'success',
    draft: 'info',
    offline: 'danger'
  }
  return map[status] || 'info'
}

const getStatusText = (status) => {
  const map = {
    published: '已发布',
    draft: '草稿',
    offline: '已下线'
  }
  return map[status] || '未知'
}

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchData()
}

// 获取数据
const fetchData = () => {
  loading.value = true
  
  // 模拟API请求
  setTimeout(() => {
    // 这里应该是真实的API请求
    const mockData = []
    for (let i = 0; i < pagination.pageSize; i++) {
      const id = (pagination.currentPage - 1) * pagination.pageSize + i + 1
      if (id > 35) break // 模拟总数
      
      mockData.push({
        id: `announcement-${id}`,
        title: `关于云服务平台升级维护的公告 ${id}`,
        publisher: '系统管理员',
        publishTime: '2023-10-15 08:30:00',
        viewCount: Math.floor(Math.random() * 1000),
        status: ['published', 'draft', 'offline'][Math.floor(Math.random() * 3)],
        content: `<p>尊敬的用户：</p>
                 <p>为了提供更好的服务体验，我们的云服务平台将于2023年10月20日凌晨2:00-6:00进行系统升级维护。</p>
                 <p>维护期间，部分功能可能暂时无法使用，给您带来的不便敬请谅解。</p>
                 <p>感谢您的理解与支持！</p>`
      })
    }
    
    tableData.value = mockData
    pagination.total = 35
    loading.value = false
  }, 500)
}

// 添加公告
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  announcementForm.id = ''
  announcementForm.title = ''
  announcementForm.content = ''
  announcementForm.status = 'published'
}

// 查看公告
const handleView = (row) => {
  dialogType.value = 'view'
  dialogVisible.value = true
  currentAnnouncement.value = { ...row }
}

// 编辑公告
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  announcementForm.id = row.id
  announcementForm.title = row.title
  announcementForm.content = row.content
  announcementForm.status = row.status
}

// 更改公告状态（下线）
const handleChangeStatus = (row) => {
  ElMessageBox.confirm(`确定要下线"${row.title}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该是API请求
    ElMessage.success('操作成功')
    fetchData()
  }).catch(() => {})
}

// 删除公告
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除"${row.title}"吗？删除后不可恢复！`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(() => {
    // 这里应该是API请求
    ElMessage.success('删除成功')
    fetchData()
  }).catch(() => {})
}

// 关闭对话框
const handleDialogClose = () => {
  dialogVisible.value = false
  if (announcementFormRef.value) {
    announcementFormRef.value.resetFields()
  }
}

// 提交表单
const submitForm = async () => {
  if (!announcementFormRef.value) return
  
  await announcementFormRef.value.validate((valid) => {
    if (valid) {
      // 这里应该是API请求
      ElMessage.success(dialogType.value === 'add' ? '发布成功' : '更新成功')
      dialogVisible.value = false
      fetchData()
    }
  })
}

// 初始加载
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.announcements-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 公告详情样式 */
.announcement-detail {
  padding: 0 20px;
}

.detail-title {
  text-align: center;
  margin-bottom: 20px;
  font-size: 22px;
  color: #303133;
}

.detail-info {
  display: flex;
  justify-content: space-around;
  color: #909399;
  margin-bottom: 30px;
  font-size: 14px;
  border-bottom: 1px solid #EBEEF5;
  padding-bottom: 15px;
}

.detail-content {
  line-height: 1.8;
  color: #606266;
}
</style> 