<template>
  <div class="announcement-list-container">
    <h2 class="page-title">小喇叭公告管理</h2>
    
    <!-- 操作栏 -->
    <el-card shadow="never" class="toolbar-card">
      <el-row :gutter="20">
        <el-col :span="18">
          <el-space wrap>
            <el-button type="primary" icon="Plus" @click="handleCreate">
              新增公告
            </el-button>
            <el-button icon="Refresh" @click="loadAnnouncementList">刷新</el-button>
          </el-space>
        </el-col>
        <el-col :span="6">
          <el-select
            v-model="statusFilter"
            placeholder="筛选状态"
            clearable
            @change="loadAnnouncementList"
            style="width: 100%"
          >
            <el-option label="全部" :value="null" />
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 公告列表 -->
    <el-card shadow="never" class="table-card">
      <el-table
        v-loading="loading"
        :data="announcementList"
        stripe
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" />
        
        <el-table-column prop="content" label="公告内容" min-width="300" show-overflow-tooltip />
        
        <el-table-column prop="priority" label="优先级" width="100" sortable>
          <template #default="{ row }">
            <el-tag :type="getPriorityColor(row.priority)">
              {{ row.priority }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        
        <el-table-column prop="startTime" label="开始时间" width="180">
          <template #default="{ row }">
            {{ row.startTime || '立即开始' }}
          </template>
        </el-table-column>
        
        <el-table-column prop="endTime" label="结束时间" width="180">
          <template #default="{ row }">
            {{ row.endTime || '永久有效' }}
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="创建时间" width="180" />
        
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              link
              icon="Edit"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              icon="Delete"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadAnnouncementList"
          @current-change="loadAnnouncementList"
        />
      </div>
    </el-card>
    
    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="公告内容" prop="content">
          <el-input
            v-model="formData.content"
            type="textarea"
            :rows="4"
            maxlength="500"
            show-word-limit
            placeholder="请输入公告内容"
          />
        </el-form-item>
        
        <el-form-item label="优先级" prop="priority">
          <el-input-number
            v-model="formData.priority"
            :min="0"
            :max="999"
            placeholder="数字越大越优先"
          />
          <span class="form-tip">数字越大越优先显示</span>
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="生效时间">
          <el-date-picker
            v-model="timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
          <div class="form-tip">不设置则立即生效且永久有效</div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

// 数据列表
const loading = ref(false)
const announcementList = ref([])
const statusFilter = ref(null)

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

// 对话框
const dialogVisible = ref(false)
const dialogTitle = computed(() => formData.id ? '编辑公告' : '新增公告')
const formRef = ref()
const submitting = ref(false)
const timeRange = ref([])

// 表单数据
const formData = reactive({
  id: null,
  content: '',
  priority: 0,
  status: 1,
  startTime: null,
  endTime: null
})

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

// 加载公告列表
const loadAnnouncementList = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      size: pagination.size
    }
    
    if (statusFilter.value !== null && statusFilter.value !== undefined) {
      params.status = statusFilter.value
    }
    
    const response = await request.get('/api/admin/announcement/list', { params })
    
    if (response.code === 200) {
      announcementList.value = response.data.records || []
      pagination.total = response.data.total || 0
    } else {
      ElMessage.error(response.message || '加载失败')
    }
  } catch (error) {
    console.error('加载公告列表失败:', error)
    ElMessage.error('加载失败，请重试')
  } finally {
    loading.value = false
  }
}

// 新增公告
const handleCreate = () => {
  resetForm()
  dialogVisible.value = true
}

// 编辑公告
const handleEdit = (row) => {
  formData.id = row.id
  formData.content = row.content
  formData.priority = row.priority
  formData.status = row.status
  formData.startTime = row.startTime
  formData.endTime = row.endTime
  
  if (row.startTime && row.endTime) {
    timeRange.value = [row.startTime, row.endTime]
  } else {
    timeRange.value = []
  }
  
  dialogVisible.value = true
}

// 状态切换
const handleStatusChange = async (row) => {
  try {
    const response = await request.put(`/api/admin/announcement/${row.id}/status`, null, {
      params: { status: row.status }
    })
    
    if (response.code === 200) {
      ElMessage.success('状态更新成功')
      loadAnnouncementList()
    } else {
      ElMessage.error(response.message || '状态更新失败')
      row.status = row.status === 1 ? 0 : 1 // 恢复原状态
    }
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('状态更新失败，请重试')
    row.status = row.status === 1 ? 0 : 1 // 恢复原状态
  }
}

// 删除公告
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除公告"${row.content.substring(0, 20)}..."吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await request.delete(`/api/admin/announcement/${row.id}`)
    
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadAnnouncementList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除公告失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    // 处理时间范围
    if (timeRange.value && timeRange.value.length === 2) {
      formData.startTime = timeRange.value[0]
      formData.endTime = timeRange.value[1]
    } else {
      formData.startTime = null
      formData.endTime = null
    }
    
    submitting.value = true
    
    let response
    if (formData.id) {
      // 编辑
      response = await request.put(`/api/admin/announcement/${formData.id}`, formData)
    } else {
      // 新增
      response = await request.post('/api/admin/announcement', formData)
    }
    
    if (response.code === 200) {
      ElMessage.success(formData.id ? '更新成功' : '创建成功')
      dialogVisible.value = false
      loadAnnouncementList()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    if (error !== false) {
      console.error('提交失败:', error)
      ElMessage.error('操作失败，请重试')
    }
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  formData.id = null
  formData.content = ''
  formData.priority = 0
  formData.status = 1
  formData.startTime = null
  formData.endTime = null
  timeRange.value = []
  
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 获取优先级颜色
const getPriorityColor = (priority) => {
  if (priority >= 100) return 'danger'
  if (priority >= 50) return 'warning'
  return 'info'
}

// 初始化
onMounted(() => {
  loadAnnouncementList()
})
</script>

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

.page-title {
  margin: 0 0 20px 0;
  font-size: 24px;
  font-weight: 500;
  color: #303133;
}

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

.table-card {
  min-height: 400px;
}

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

.form-tip {
  margin-left: 10px;
  font-size: 12px;
  color: #909399;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table__header) {
  font-weight: 500;
}
</style>

