<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!--分类树-->
        <pane size="20">
          <el-col>
            <div class="head-container">
              <el-input
                v-model="categoryName"
                placeholder="请输入分类名称"
                clearable
                size="small"
                prefix-icon="el-icon-search"
                style="margin-bottom: 20px"
                @input="handleCategoryFilter"
              />
            </div>
            <div class="head-container">
              <el-tree
                :data="categoryTreeData"
                :props="defaultProps"
                :expand-on-click-node="false"
                :filter-node-method="filterCategoryNode"
                ref="categoryTree"
                node-key="id"
                default-expand-all
                highlight-current
                @node-click="handleCategoryNodeClick"
              />
            </div>
          </el-col>
        </pane>
        <!--文档列表-->
        <pane size="80">
          <el-col>
            <el-form
              ref="queryForm"
              :model="queryParams"
              :inline="true"
              label-width="90px"
              size="small"
              v-show="showSearch"
            >
              <el-form-item label="关键词" prop="keyword">
                <el-input
                  v-model="queryParams.keyword"
                  placeholder="请输入标题、标签或关键词"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="标签" prop="tags">
                <el-input
                  v-model="queryParams.tags"
                  placeholder="请输入标签（逗号分隔）"
                  clearable
                />
              </el-form-item>
              <el-form-item label="创建时间">
                <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  style="width: 240px"
                  clearable
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">
                  查询
                </el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"> 重置 </el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['knowledge:document:add']"
        >
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['knowledge:document:edit']"
        >
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['knowledge:document:remove']"
        >
          删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table
      v-loading="loading"
      :data="documentList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center" />
      <el-table-column label="文档标题" prop="title" :show-overflow-tooltip="true" min-width="200" />
      <el-table-column label="分类" prop="categoryId" width="120" align="center">
        <template slot-scope="scope">
          <span>{{ getCategoryName(scope.row.categoryId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="文件名" prop="fileName" :show-overflow-tooltip="true" min-width="150" />
      <el-table-column label="文件类型" prop="fileType" width="100" align="center" />
      <el-table-column label="标签" prop="tags" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="查看次数" prop="viewCount" width="100" align="center" />
      <el-table-column label="下载次数" prop="downloadCount" width="100" align="center" />
      <el-table-column label="创建时间" prop="createTime" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['knowledge:document:query']"
          >
            查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownload(scope.row)"
            v-hasPermi="['knowledge:document:download']"
          >
            下载
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['knowledge:document:edit']"
          >
            修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['knowledge:document:remove']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改文档对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="文档标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入文档标题" maxlength="200" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="分类" prop="categoryId">
              <el-select v-model="form.categoryId" placeholder="请选择分类" clearable style="width: 100%">
                <el-option
                  v-for="item in categoryOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文件" prop="fileId">
              <el-upload
                ref="upload"
                :limit="1"
                :on-exceed="handleExceed"
                :before-upload="beforeUpload"
                :on-success="handleUploadSuccess"
                :on-remove="handleRemove"
                :file-list="fileList"
                :action="uploadUrl"
                :headers="uploadHeaders"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">支持PDF、DOC、DOCX等格式</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="标签" prop="tags">
              <el-input
                v-model="form.tags"
                placeholder="请输入标签，多个标签用逗号分隔（如：交通,应急,法规）"
                maxlength="500"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="关键词" prop="keywords">
              <el-input
                v-model="form.keywords"
                placeholder="请输入关键词，多个关键词用逗号分隔（用于搜索和自动调取）"
                maxlength="500"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="摘要" prop="summary">
              <el-input
                v-model="form.summary"
                type="textarea"
                placeholder="请输入摘要/描述"
                maxlength="1000"
                :rows="4"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否推荐">
              <el-radio-group v-model="form.isFeatured">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
          </el-col>
        </pane>
      </splitpanes>
    </el-row>
  </div>
</template>

<script>
import {
  listKnowledgeDocuments,
  getKnowledgeDocument,
  addKnowledgeDocument,
  updateKnowledgeDocument,
  deleteKnowledgeDocument,
  downloadKnowledgeDocument
} from '@/api/knowledge/document'
import { listKnowledgeCategories } from '@/api/knowledge/category'
import { getToken } from '@/utils/auth'
import { Splitpanes, Pane } from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'

export default {
  name: 'KnowledgeDocument',
  components: {
    Splitpanes,
    Pane
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文档表格数据
      documentList: [],
      // 分类选项（用于下拉选择）
      categoryOptions: [],
      // 分类树数据（用于左侧树）
      categoryTreeData: [],
      // 分类名称（用于搜索）
      categoryName: undefined,
      // 树组件默认属性
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: null,
        categoryId: null,
        tags: null
      },
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [{ required: true, message: '文档标题不能为空', trigger: 'blur' }],
        fileId: [{ required: true, message: '请上传文件', trigger: 'change' }]
      },
      // 文件上传相关
      uploadUrl: process.env.VUE_APP_BASE_API + '/api/file/upload',
      uploadHeaders: {
        Authorization: 'Bearer ' + getToken()
      },
      fileList: []
    }
  },
  created() {
    this.getCategoryTree()
    this.getCategoryList()
    this.getList()
  },
  methods: {
    /** 查询文档列表 */
    getList() {
      this.loading = true
      const params = {
        ...this.queryParams,
        beginTime: this.dateRange && this.dateRange.length > 0 ? this.dateRange[0] : null,
        endTime: this.dateRange && this.dateRange.length > 1 ? this.dateRange[1] : null
      }
      listKnowledgeDocuments(params).then(response => {
        this.documentList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 查询分类列表（用于下拉选择） */
    getCategoryList() {
      listKnowledgeCategories().then(response => {
        // 将树形结构转换为扁平列表
        const flattenCategories = (categories) => {
          let result = []
          categories.forEach(cat => {
            result.push({ id: cat.id, name: cat.name })
            if (cat.children && cat.children.length > 0) {
              result = result.concat(flattenCategories(cat.children))
            }
          })
          return result
        }
        this.categoryOptions = flattenCategories(response.data || [])
      })
    },
    /** 查询分类树（用于左侧树） */
    getCategoryTree() {
      listKnowledgeCategories().then(response => {
        const treeData = response.data || []
        // 添加"全部"选项
        this.categoryTreeData = [
          {
            id: 0,
            name: '全部',
            children: treeData
          }
        ]
      })
    },
    /** 过滤分类树节点 */
    filterCategoryNode(value, data) {
      if (!value) return true
      return data.name && data.name.indexOf(value) !== -1
    },
    /** 处理分类树过滤 */
    handleCategoryFilter(value) {
      this.$refs.categoryTree.filter(value)
    },
    /** 分类树节点点击事件 */
    handleCategoryNodeClick(data) {
      if (data.id === 0) {
        // 点击"全部"时，清空分类筛选
        this.queryParams.categoryId = undefined
      } else {
        this.queryParams.categoryId = data.id
      }
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 获取分类名称 */
    getCategoryName(categoryId) {
      if (!categoryId) return '-'
      const category = this.categoryOptions.find(item => item.id === categoryId)
      return category ? category.name : '-'
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        categoryId: null,
        fileId: null,
        fileName: null,
        fileSize: null,
        fileType: null,
        tags: null,
        keywords: null,
        summary: null,
        isFeatured: false
      }
      this.fileList = []
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.queryParams.categoryId = undefined
      // 重置分类树选中状态
      if (this.$refs.categoryTree) {
        this.$refs.categoryTree.setCurrentKey(null)
      }
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加文档'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids[0]
      getKnowledgeDocument(id).then(response => {
        this.form = response.data
        if (this.form.fileId) {
          this.fileList = [{
            name: this.form.fileName,
            url: '#'
          }]
        }
        this.open = true
        this.title = '修改文档'
      })
    },
    /** 查看按钮操作 */
    handleView(row) {
      getKnowledgeDocument(row.id).then(response => {
        this.$alert(response.data.summary || '暂无摘要', response.data.title, {
          confirmButtonText: '确定',
          type: 'info'
        })
      })
    },
    /** 下载按钮操作 */
    handleDownload(row) {
      downloadKnowledgeDocument(row.id).then(response => {
        const blob = new Blob([response])
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', row.fileName || 'document')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        this.$modal.msgSuccess('下载成功')
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateKnowledgeDocument(this.form.id, this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addKnowledgeDocument(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal
        .confirm('是否确认删除选中的文档？')
        .then(function() {
          return deleteKnowledgeDocument(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    // 文件上传相关方法
    handleExceed() {
      this.$message.warning('只能上传一个文件')
    },
    beforeUpload(file) {
      const isAllowed = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'].includes(file.type)
      if (!isAllowed) {
        this.$message.error('只能上传PDF、DOC、DOCX格式的文件')
        return false
      }
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过 10MB!')
        return false
      }
      return true
    },
    handleUploadSuccess(response, file) {
      if (response.code === 200) {
        this.form.fileId = response.data.id
        this.form.fileName = response.data.originalName
        this.form.fileSize = response.data.fileSize
        this.form.fileType = response.data.fileType
        this.$message.success('文件上传成功')
      } else {
        this.$message.error(response.msg || '文件上传失败')
      }
    },
    handleRemove() {
      this.form.fileId = null
      this.form.fileName = null
      this.form.fileSize = null
      this.form.fileType = null
    }
  }
}
</script>

<style scoped>
</style>

