<template>
  <div class="announcement-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <h1>公告管理</h1>
        <p>管理系统公告的发布和维护</p>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><Bell /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.total }}</div>
                <div class="stat-label">总公告数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon published">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.published }}</div>
                <div class="stat-label">已发布</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon draft">
                <el-icon><Edit /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.draft }}</div>
                <div class="stat-label">草稿</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon offline">
                <el-icon><Close /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.offline }}</div>
                <div class="stat-label">已下架</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 查询筛选区域 -->
    <el-card class="search-card">
      <el-form :model="queryForm" :inline="true">
        <el-form-item label="公告标题">
          <el-input
            v-model="queryForm.title"
            placeholder="请输入公告标题"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="公告状态">
          <div class="custom-select-wrapper">
            <select 
              v-model="queryForm.status" 
              class="custom-select"
            >
              <option value="">全部状态</option>
              <option :value="0">草稿</option>
              <option :value="1">已发布</option>
              <option :value="2">已下架</option>
            </select>
          </div>
        </el-form-item>
        <el-form-item label="优先级">
          <div class="custom-select-wrapper">
            <select 
              v-model="queryForm.priority" 
              class="custom-select"
            >
              <option value="">全部优先级</option>
              <option :value="0">普通</option>
              <option :value="1">置顶</option>
            </select>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            添加公告
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 公告列表 -->
    <el-card class="table-card">
      <el-table
        :data="announcements"
        style="width: 100%"
        v-loading="loading"
        stripe
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="公告标题" min-width="200" />
        <el-table-column prop="content" label="公告内容" min-width="250" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.status === 0" type="info">草稿</el-tag>
            <el-tag v-else-if="row.status === 1" type="success">已发布</el-tag>
            <el-tag v-else-if="row.status === 2" type="warning">已下架</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.priority === 1" type="danger" effect="dark">置顶</el-tag>
            <el-tag v-else type="info">普通</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="发布时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="publisherName" label="发布人" width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleView(row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button link type="warning" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button link type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          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="700px"
      @close="handleDialogClose"
    >
      <el-form
        :model="announcementForm"
        :rules="announcementRules"
        ref="announcementFormRef"
        label-width="100px"
      >
        <el-form-item label="公告标题" prop="title">
          <el-input
            v-model="announcementForm.title"
            placeholder="请输入公告标题"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input
            v-model="announcementForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入公告内容"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="公告状态" prop="status">
          <el-radio-group v-model="announcementForm.status">
            <el-radio :value="0">草稿</el-radio>
            <el-radio :value="1">已发布</el-radio>
            <el-radio :value="2">已下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-radio-group v-model="announcementForm.priority">
            <el-radio :value="0">普通</el-radio>
            <el-radio :value="1">置顶</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ submitting ? '提交中...' : '确定' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看公告详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="公告详情"
      width="700px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="公告ID">{{ viewAnnouncement.id }}</el-descriptions-item>
        <el-descriptions-item label="公告标题">{{ viewAnnouncement.title }}</el-descriptions-item>
        <el-descriptions-item label="公告内容">
          <div style="white-space: pre-wrap;">{{ viewAnnouncement.content }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag v-if="viewAnnouncement.status === 0" type="info">草稿</el-tag>
          <el-tag v-else-if="viewAnnouncement.status === 1" type="success">已发布</el-tag>
          <el-tag v-else-if="viewAnnouncement.status === 2" type="warning">已下架</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="优先级">
          <el-tag v-if="viewAnnouncement.priority === 1" type="danger">置顶</el-tag>
          <el-tag v-else type="info">普通</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="发布时间">{{ formatDate(viewAnnouncement.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="发布人">{{ viewAnnouncement.publisherName }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatDate(viewAnnouncement.updateTime) }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Bell,
  CircleCheck,
  Edit,
  Close,
  Search,
  Refresh,
  Plus,
  View,
  Delete
} from '@element-plus/icons-vue'
import { lotteryApi } from '../../api/index.js'

export default {
  name: 'AnnouncementManagement',
  components: {
    Bell,
    CircleCheck,
    Edit,
    Close,
    Search,
    Refresh,
    Plus,
    View,
    Delete
  },
  setup() {
    const loading = ref(false)
    const submitting = ref(false)
    const dialogVisible = ref(false)
    const viewDialogVisible = ref(false)
    const dialogTitle = ref('添加公告')
    const announcementFormRef = ref()
    
    // 统计数据
    const stats = reactive({
      total: 0,
      published: 0,
      draft: 0,
      offline: 0
    })

    // 查询表单
    const queryForm = reactive({
      title: '',
      status: '',
      priority: ''
    })

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

    // 公告列表
    const announcements = ref([])

    // 公告表单
    const announcementForm = reactive({
      id: null,
      title: '',
      content: '',
      status: 1,
      priority: 0
    })

    // 查看公告数据
    const viewAnnouncement = ref({})

    // 表单验证规则
    const announcementRules = {
      title: [
        { required: true, message: '请输入公告标题', trigger: 'blur' },
        { min: 1, max: 100, message: '标题长度在1到100个字符', trigger: 'blur' }
      ],
      content: [
        { required: true, message: '请输入公告内容', trigger: 'blur' },
        { min: 1, max: 500, message: '内容长度在1到500个字符', trigger: 'blur' }
      ],
      status: [
        { required: true, message: '请选择公告状态', trigger: 'change' }
      ]
    }

    // 格式化日期
    const formatDate = (date) => {
      if (!date) return '-'
      if (typeof date === 'string') return date
      return new Date(date).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    }

    // 加载公告列表
    const loadAnnouncements = async () => {
      loading.value = true
      try {
        const params = {
          current: pagination.current,
          pageSize: pagination.pageSize,
          title: queryForm.title,
          status: queryForm.status,
          priority: queryForm.priority
        }
        
        const response = await lotteryApi.getAnnouncementList(params)
        
        if (response && response.success) {
          announcements.value = response.data.records || []
          pagination.total = response.data.total || 0
          
          // 更新统计数据
          updateStats()
        } else {
          ElMessage.error(response?.message || '加载公告列表失败')
        }
      } catch (error) {
        console.error('加载公告列表失败:', error)
        ElMessage.error('加载公告列表失败')
      } finally {
        loading.value = false
      }
    }

    // 更新统计数据
    const updateStats = async () => {
      try {
        // 获取所有公告进行统计
        const response = await lotteryApi.getAnnouncementList({
          current: 1,
          pageSize: 1000
        })
        
        if (response && response.success) {
          const allAnnouncements = response.data.records || []
          stats.total = allAnnouncements.length
          stats.published = allAnnouncements.filter(a => a.status === 1).length
          stats.draft = allAnnouncements.filter(a => a.status === 0).length
          stats.offline = allAnnouncements.filter(a => a.status === 2).length
        }
      } catch (error) {
        console.error('更新统计数据失败:', error)
      }
    }

    // 查询
    const handleQuery = () => {
      pagination.current = 1
      loadAnnouncements()
    }

    // 重置
    const handleReset = () => {
      queryForm.title = ''
      queryForm.status = ''
      queryForm.priority = ''
      pagination.current = 1
      loadAnnouncements()
    }

    // 添加公告
    const handleAdd = () => {
      dialogTitle.value = '添加公告'
      announcementForm.id = null
      announcementForm.title = ''
      announcementForm.content = ''
      announcementForm.status = 1
      announcementForm.priority = 0
      dialogVisible.value = true
    }

    // 查看公告
    const handleView = (row) => {
      viewAnnouncement.value = { ...row }
      viewDialogVisible.value = true
    }

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

    // 删除公告
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确定要删除这条公告吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await lotteryApi.deleteAnnouncement(row.id)
        
        if (response && response.success) {
          ElMessage.success('删除成功')
          loadAnnouncements()
        } else {
          ElMessage.error(response?.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除公告失败:', error)
          ElMessage.error('删除公告失败')
        }
      }
    }

    // 提交表单
    const handleSubmit = async () => {
      try {
        await announcementFormRef.value.validate()
        submitting.value = true
        
        const data = {
          title: announcementForm.title,
          content: announcementForm.content,
          status: announcementForm.status,
          priority: announcementForm.priority
        }
        
        let response
        if (announcementForm.id) {
          // 编辑
          data.id = announcementForm.id
          response = await lotteryApi.updateAnnouncement(data)
        } else {
          // 添加
          response = await lotteryApi.addAnnouncement(data)
        }
        
        if (response && response.success) {
          ElMessage.success(announcementForm.id ? '更新成功' : '添加成功')
          dialogVisible.value = false
          loadAnnouncements()
        } else {
          ElMessage.error(response?.message || '操作失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('提交失败:', error)
          ElMessage.error('操作失败')
        }
      } finally {
        submitting.value = false
      }
    }

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

    // 分页大小变化
    const handleSizeChange = (val) => {
      pagination.pageSize = val
      pagination.current = 1
      loadAnnouncements()
    }

    // 当前页变化
    const handleCurrentChange = (val) => {
      pagination.current = val
      loadAnnouncements()
    }

    // 初始化
    onMounted(() => {
      loadAnnouncements()
    })

    return {
      loading,
      submitting,
      dialogVisible,
      viewDialogVisible,
      dialogTitle,
      announcementFormRef,
      stats,
      queryForm,
      pagination,
      announcements,
      announcementForm,
      viewAnnouncement,
      announcementRules,
      formatDate,
      handleQuery,
      handleReset,
      handleAdd,
      handleView,
      handleEdit,
      handleDelete,
      handleSubmit,
      handleDialogClose,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.announcement-management {
  padding: 20px;
}

.page-header {
  background: linear-gradient(135deg, #2563eb 0%, #06b6d4 100%);
  color: white;
  padding: 30px;
  border-radius: 12px;
  margin-bottom: 20px;
}

.header-content h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
}

.header-content p {
  margin: 0;
  opacity: 0.9;
  font-size: 14px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 12px;
  border: none;
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 15px;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #2563eb, #06b6d4);
  color: white;
  font-size: 24px;
}

.stat-icon.published {
  background: linear-gradient(135deg, #10b981, #34d399);
}

.stat-icon.draft {
  background: linear-gradient(135deg, #f59e0b, #fbbf24);
}

.stat-icon.offline {
  background: linear-gradient(135deg, #ef4444, #f87171);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-top: 4px;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 12px;
  overflow: visible !important;
}

.search-card :deep(.el-card__body) {
  overflow: visible !important;
}

.table-card {
  border-radius: 12px;
}

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

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  font-weight: 600;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-dialog__header) {
  background: linear-gradient(135deg, #2563eb 0%, #06b6d4 100%);
  padding: 20px;
  margin: 0;
}

:deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
  font-size: 18px;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
  font-size: 20px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

/* 自定义下拉框样式 */
.custom-select-wrapper {
  position: relative;
  width: 100%;
}

.custom-select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: white;
  font-size: 14px;
  color: #606266;
  appearance: none;
  -webkit-appearance: none;
  -moz-appearance: none;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23606266'%3E%3Cpath d='M7 10l5 5 5-5z'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 8px center;
  background-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.custom-select:hover {
  border-color: #c0c4cc;
}

.custom-select:focus {
  outline: none;
  border-color: #409eff;
}
</style>
