<template>
  <div class="news-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-select v-model="searchForm.category" placeholder="请选择分类" clearable>
            <el-option label="产品动态" value="product" />
            <el-option label="技术干货" value="technology" />
            <el-option label="行业资讯" value="industry" />
            <el-option label="活动公告" value="activity" />
            <el-option label="其他" value="other" />
          </el-select>
        </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>
          <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>

    <!-- 新闻列表卡片 -->
    <div v-loading="loading" class="news-list">
      <el-card class="table-card">
        <el-table
          :data="newsData"
          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="category" label="新闻分类" width="120" align="center">
            <template #default="scope">
              <el-tag :type="getCategoryType(scope.row.category)">
                {{ getCategoryText(scope.row.category) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="author" label="作者" width="150" align="center" />
          <el-table-column prop="publishTime" label="发布时间" width="120" align="center" />
          <el-table-column prop="viewCount" label="阅读量" width="100" align="center" />
          <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="danger" link @click="handleDelete(scope.row)">
                <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>
    </div>

    <!-- 新闻详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :before-close="handleDialogClose"
    >
      <div v-if="dialogType === 'view'" class="news-detail">
        <h2 class="detail-title">{{ currentNews.title }}</h2>
        <div class="detail-info">
          <span>
            <el-tag :type="getCategoryType(currentNews.category)" size="small">
              {{ getCategoryText(currentNews.category) }}
            </el-tag>
          </span>
          <span><el-icon><user /></el-icon> {{ currentNews.author }}</span>
          <span><el-icon><calendar /></el-icon> {{ currentNews.publishTime }}</span>
          <span><el-icon><view /></el-icon> {{ currentNews.viewCount }} 次阅读</span>
        </div>
        <el-image class="detail-cover" :src="currentNews.coverImage" fit="cover" />
        <div class="detail-content" v-html="currentNews.content"></div>
      </div>
      <div v-else>
        <el-form :model="newsForm" label-width="120px" :rules="rules" ref="newsFormRef">
          <el-form-item label="新闻标题" prop="title">
            <el-input v-model="newsForm.title" placeholder="请输入新闻标题" />
          </el-form-item>
          <el-form-item label="新闻分类" prop="category">
            <el-select v-model="newsForm.category" placeholder="请选择分类" style="width: 100%">
              <el-option label="产品动态" value="product" />
              <el-option label="技术干货" value="technology" />
              <el-option label="行业资讯" value="industry" />
              <el-option label="活动公告" value="activity" />
              <el-option label="其他" value="other" />
            </el-select>
          </el-form-item>
          <el-form-item label="封面图片" prop="coverImage">
            <el-input v-model="newsForm.coverImage" placeholder="请输入图片URL" />
            <div class="upload-tip">
              <el-icon><info-filled /></el-icon> 实际使用时应为图片上传组件
            </div>
          </el-form-item>
          <el-form-item label="简介摘要" prop="summary">
            <el-input
              v-model="newsForm.summary"
              type="textarea"
              :rows="3"
              placeholder="请输入新闻简介(100字以内)"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="新闻内容" prop="content">
            <el-input
              v-model="newsForm.content"
              type="textarea"
              :rows="8"
              placeholder="请输入新闻正文内容"
            />
            <div class="upload-tip">
              <el-icon><info-filled /></el-icon> 实际使用时应为富文本编辑器
            </div>
          </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, Delete,
  User, Calendar, Picture, InfoFilled
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

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

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

// 新闻数据
const loading = ref(false)
const newsData = 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 currentNews = ref({})

// 表单对象和规则
const newsFormRef = ref(null)
const newsForm = reactive({
  id: '',
  title: '',
  category: '',
  coverImage: '',
  summary: '',
  content: ''
})

const rules = {
  title: [{ required: true, message: '请输入新闻标题', trigger: 'blur' }],
  category: [{ required: true, message: '请选择新闻分类', trigger: 'change' }],
  coverImage: [{ required: true, message: '请输入封面图片URL', trigger: 'blur' }],
  summary: [{ required: true, message: '请输入新闻简介', trigger: 'blur' }],
  content: [{ required: true, message: '请输入新闻内容', trigger: 'blur' }]
}

// 新闻分类标签
const getCategoryType = (category) => {
  const map = {
    product: 'primary',
    technology: 'success',
    industry: 'info',
    activity: 'warning',
    other: ''
  }
  return map[category] || ''
}

const getCategoryText = (category) => {
  const map = {
    product: '产品动态',
    technology: '技术干货',
    industry: '行业资讯',
    activity: '活动公告',
    other: '其他'
  }
  return map[category] || '未知'
}

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

// 获取数据
const fetchData = () => {
  loading.value = true
  
  // 模拟API请求
  setTimeout(() => {
    // 这里应该是真实的API请求
    const mockData = []
    const categories = ['product', 'technology', 'industry', 'activity', 'other']
    
    for (let i = 0; i < pagination.pageSize; i++) {
      const id = (pagination.currentPage - 1) * pagination.pageSize + i + 1
      if (id > 32) break // 模拟总数
      
      const category = categories[Math.floor(Math.random() * categories.length)]
      
      mockData.push({
        id: `news-${id}`,
        title: `零零七云计算平台${getCategoryText(category)}新闻 ${id}`,
        category,
        author: '零零七云计算小编',
        publishTime: '2023-10-12',
        viewCount: Math.floor(Math.random() * 1000),
        coverImage: `https://picsum.photos/id/${id + 30}/800/400`,
        summary: '零零七云计算平台重磅升级，新增多项功能特性，提供更优质的云服务体验。本次升级包含计算资源优化、存储系统升级、网络性能提升等多方面改进。',
        content: `<p>尊敬的用户：</p>
                 <p>我们很高兴地宣布，零零七云计算平台已完成重大升级，带来全新的用户体验和技术改进。</p>
                 <h3>一、主要升级内容</h3>
                 <ol>
                   <li>计算资源全面升级，性能提升30%</li>
                   <li>存储系统架构优化，读写速度大幅提升</li>
                   <li>网络架构重构，带宽翻倍，延迟降低</li>
                   <li>控制台界面优化，操作更加便捷</li>
                   <li>API接口全面升级，兼容性更好</li>
                 </ol>
                 <h3>二、升级优势</h3>
                 <p>本次升级将为您带来更稳定、高效的云服务体验。我们的技术团队持续致力于提供业界领先的云计算解决方案。</p>
                 <h3>三、后续计划</h3>
                 <p>我们将继续投入研发，计划在年底前推出更多创新功能，敬请期待！</p>
                 <p>感谢您一直以来对零零七云计算的支持与信任！</p>`
      })
    }
    
    newsData.value = mockData
    pagination.total = 32
    loading.value = false
  }, 500)
}

// 添加新闻
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  newsForm.id = ''
  newsForm.title = ''
  newsForm.category = ''
  newsForm.coverImage = ''
  newsForm.summary = ''
  newsForm.content = ''
}

// 查看新闻
const handleView = (row) => {
  dialogType.value = 'view'
  dialogVisible.value = true
  currentNews.value = { ...row }
}

// 编辑新闻
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  newsForm.id = row.id
  newsForm.title = row.title
  newsForm.category = row.category
  newsForm.coverImage = row.coverImage
  newsForm.summary = row.summary
  newsForm.content = row.content
}

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

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

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

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

<style scoped>
.news-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;
}

.news-list {
  margin-bottom: 20px;
}

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

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

/* 新闻详情样式 */
.news-detail {
  padding: 0 20px;
}

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

.detail-info {
  display: flex;
  justify-content: center;
  color: #909399;
  margin-bottom: 20px;
  font-size: 14px;
}

.detail-info span {
  display: flex;
  align-items: center;
  margin: 0 10px;
}

.detail-info .el-icon {
  margin-right: 5px;
}

.detail-cover {
  width: 100%;
  max-height: 400px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.detail-content {
  line-height: 1.8;
  color: #606266;
}

.upload-tip {
  margin-top: 5px;
  color: #909399;
  font-size: 12px;
  display: flex;
  align-items: center;
}

.upload-tip .el-icon {
  margin-right: 5px;
  color: #E6A23C;
}
</style> 