<template>
  <div class="knowledge-base-module">
    <el-header class="header">
      <h2>双碳政策知识库</h2>
    </el-header>
    <el-main>
      <el-form style="display: flex">
        <el-form-item label="关键词">
          <el-select
              v-model="searchQuery"
              multiple
              filterable
              allow-create
              default-first-option
              :reserve-keyword="false"
              placeholder="请输入文章关键词"
              style="margin-bottom: 20px; width: 300px"
              @change="performSearch"
          >
            <el-option
                v-for="keyword in uniqueKeywords"
                :key="keyword"
                :label="keyword"
                :value="keyword"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序方式">
          <el-select v-model="sortField" placeholder="排序方式" style="margin-bottom: 20px;width: 300px">
            <el-option label="按标题排序" value="title" />
            <el-option label="按内容摘要排序" value="summary" />
            <el-option label="按政策来源排序" value="source" />
            <el-option label="按日期排序" value="date" />
          </el-select>
        </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" @click="exportData">导出数据</el-button>
        <el-button type="success" @click="showImportDialog = true">导入新闻</el-button>
      </div>
      <el-table :data="paginatedResults" style="width: 100%">
        <el-table-column prop="title" label="文件标题" />
        <el-table-column prop="summary" label="内容摘要" />
        <el-table-column prop="content" label="详细内容" />
        <el-table-column prop="source" label="政策来源" />
        <el-table-column prop="date" label="发布日期" />
        <el-table-column label="关键词">
          <template #default="scope">
            <el-tag v-for="keyword in scope.row.keywords" :key="keyword" type="success" style="margin-right: 5px;">
              {{ keyword }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="margin-top: 20px;"
      />
    </el-main>

    <!-- 导入新闻对话框 -->
    <el-dialog title="导入新闻" v-model="showImportDialog" width="30%">
      <el-form :model="newsForm" :rules="rules" ref="newsFormRef" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="newsForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="内容摘要" prop="summary">
          <el-input v-model="newsForm.summary" placeholder="请输入内容摘要"></el-input>
        </el-form-item>
        <el-form-item label="详细内容" prop="content">
          <el-input v-model="newsForm.content" type="textarea" placeholder="请输入详细内容"></el-input>
        </el-form-item>
        <el-form-item label="政策来源" prop="source">
          <el-input v-model="newsForm.source" placeholder="请输入政策来源"></el-input>
        </el-form-item>
        <el-form-item label="发布日期" prop="date">
          <el-date-picker v-model="newsForm.date" type="date" placeholder="请选择发布日期" value-format="YYYY-MM-DD"></el-date-picker>
        </el-form-item>
        <el-form-item label="关键词" prop="keywords">
          <el-input v-model="newsForm.keywords" placeholder="请输入关键词，多个关键词用逗号分隔"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showImportDialog = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElHeader, ElMain, ElInput, ElButton, ElSelect, ElOption, ElTable, ElTableColumn, ElPagination, ElTag, ElLoading, ElMessage, ElDialog, ElFormItem, ElForm, ElDatePicker } from 'element-plus'
import { knowledgeBase } from './data.js'

const searchQuery = ref([])
const sortField = ref('title')
const results = ref(knowledgeBase)
const pageSize = ref(5)
const currentPage = ref(1)
const total = ref(knowledgeBase.length)
const showImportDialog = ref(false)
const newsFormRef = ref(null)

const uniqueKeywords = computed(() => {
  const allKeywords = knowledgeBase.flatMap(item => item.keywords)
  return [...new Set(allKeywords)]
})

const performSearch = () => {
  const queryWords = searchQuery.value.map(word => word.toLowerCase())
  results.value = knowledgeBase.filter(item => {
    return queryWords.every(word => {
      return (
          item.title.toLowerCase().includes(word) ||
          item.summary.toLowerCase().includes(word) ||
          item.content.toLowerCase().includes(word) ||
          item.source.toLowerCase().includes(word) ||
          item.date.toLowerCase().includes(word) ||
          item.keywords.some(keyword => keyword.toLowerCase().includes(word))
      )
    })
  })
  total.value = results.value.length
  currentPage.value = 1
}

const sortedResults = computed(() => {
  return results.value.sort((a, b) => {
    if (a[sortField.value] < b[sortField.value]) return -1
    if (a[sortField.value] > b[sortField.value]) return 1
    return 0
  })
})

const paginatedResults = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return sortedResults.value.slice(start, end)
})

const handleSizeChange = (newPageSize) => {
  pageSize.value = newPageSize
  currentPage.value = 1
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
}

const exportData = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '正在导出数据...',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  setTimeout(() => {
    loading.close()
    ElMessage.success('导出成功')
  }, 2000)
}

const newsForm = ref({
  title: '',
  summary: '',
  content: '',
  source: '',
  date: '',
  keywords: ''
})

const rules = ref({
  title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
  summary: [{ required: true, message: '内容摘要不能为空', trigger: 'blur' }],
  content: [{ required: true, message: '详细内容不能为空', trigger: 'blur' }],
  source: [{ required: true, message: '政策来源不能为空', trigger: 'blur' }],
  date: [{ required: true, message: '发布日期不能为空', trigger: 'change' }],
  keywords: [{ required: true, message: '关键词不能为空', trigger: 'blur' }]
})

const submitForm = () => {
  newsFormRef.value.validate((valid) => {
    if (valid) {
      const newNews = {
        title: newsForm.value.title,
        summary: newsForm.value.summary,
        content: newsForm.value.content,
        source: newsForm.value.source,
        date: newsForm.value.date, // 已经是 YYYY-MM-DD 格式
        keywords: newsForm.value.keywords.split(',').map(keyword => keyword.trim())
      }
      knowledgeBase.push(newNews)
      performSearch()
      showImportDialog.value = false
      ElMessage.success('新闻导入成功')
    } else {
      ElMessage.error('请填写所有必填项')
      return false
    }
  })
}

onMounted(() => {
  performSearch()
})
</script>

<style scoped>
.knowledge-base-module {
  display: flex;
  flex-direction: column;
  height: 90vh;
}

.header {
  background-color: #409eff;
  color: white;
  text-align: center;
  padding: 10px 0;
}

.main {
  flex: 1;
  padding: 20px;
}
</style>
