<template>
  <div class="app-container">
    <el-row :gutter="16">
      <el-col :span="6">
        <el-card shadow="never">
          <template #header><div class="card-header"><span>文档分类</span><el-button size="small" circle @click="handleAddCate">+</el-button></div></template>
          <el-tree :data="cateTree" :props="{label:'cateName'}" default-expand-all highlight-current
            @node-click="handleCateClick"
            :expand-on-click-node="false">
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ node.label }}</span>
                <span class="tree-actions">
                  <el-button type="primary" link size="small" @click.stop="handleEditCate(data)">编辑</el-button>
                  <el-button type="danger" link size="small" @click.stop="handleDeleteCate(data)">删除</el-button>
                </span>
              </span>
            </template>
          </el-tree>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card shadow="never">
          <template #header><div class="card-header"><span>文档列表</span><el-button type="primary" size="small" @click="handleUpload">上传文档</el-button></div></template>
          <el-table :data="fileList" stripe v-loading="loading" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="fileId" label="序号" width="60" />
            <el-table-column prop="fileName" label="标题" min-width="200" show-overflow-tooltip />
            <el-table-column prop="fileSize" label="大小" width="80" />
            <el-table-column prop="fileTime" label="上传时间" width="160" />
            <el-table-column label="操作" width="240" fixed="right">
              <template #default="s">
                <el-button type="primary" link @click="handleDownload(s.row)">下载</el-button>
                <el-button type="warning" link @click="handleRename(s.row)">重命名</el-button>
                <el-button type="warning" link @click="handleMove(s.row)">移动</el-button>
                <el-button type="danger" link @click="handleDelete(s.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 12px" v-if="selectedRows.length > 0">
            <el-button type="warning" size="small" @click="handleBatchMove">批量移动 ({{ selectedRows.length }})</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 上传文档对话框 -->
    <el-dialog v-model="uploadVisible" title="上传文档" width="500px">
      <el-form :model="uploadForm" label-width="80px">
        <el-form-item label="文档描述"><el-input v-model="uploadForm.fileDesc" /></el-form-item>
        <el-form-item label="选择文件">
          <el-upload
            ref="uploadRef"
            :action="uploadUrl"
            :data="{ fileCate: currentCateId || '0', fileDesc: uploadForm.fileDesc }"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError">
            <el-button>选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer><el-button @click="uploadVisible=false">关 闭</el-button></template>
    </el-dialog>
    <!-- 移动文件对话框 -->
    <el-dialog v-model="moveVisible" title="移动到指定分类" width="400px">
      <el-tree :data="cateTree" :props="{label:'cateName'}" default-expand-all highlight-current
        @node-click="handleMoveCateClick" :expand-on-click-node="false" />
      <template #footer>
        <el-button type="primary" @click="submitMove" :disabled="!moveTargetCateId">确 定</el-button>
        <el-button @click="moveVisible=false">取 消</el-button>
      </template>
    </el-dialog>
    <!-- 新增/编辑分类对话框 -->
    <el-dialog v-model="cateEditVisible" :title="cateEditTitle" width="400px">
      <el-form :model="cateEditForm" label-width="80px">
        <el-form-item label="分类名称"><el-input v-model="cateEditForm.cateName" placeholder="请输入分类名称" /></el-form-item>
        <el-form-item label="分类说明"><el-input v-model="cateEditForm.cateMemo" type="textarea" :rows="3" placeholder="请输入分类说明" /></el-form-item>
        <el-form-item label="排序"><el-input-number v-model="cateEditForm.cateSeq" :min="0" :max="9999" style="width:100%" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitCateEdit">确 定</el-button>
        <el-button @click="cateEditVisible=false">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="Doc">
import { getDocCateTree, getDocCate, getDocFileList, addDocCate, updateDocCate, delDocCate, delDocFile, moveDocFile, updateDocFile } from '@/api/slgc/doc/index'
const { proxy } = getCurrentInstance()
const loading = ref(true); const cateTree = ref([]); const fileList = ref([]); const uploadVisible = ref(false)
const uploadRef = ref(null)
const uploadForm = ref({ fileDesc: '' })
const uploadUrl = ref('/slgc/doc-file/upload')
const currentCateId = ref('')
const selectedRows = ref([])
const moveVisible = ref(false); const moveTargetCateId = ref(''); const moveFileIds = ref([])
const cateEditVisible = ref(false); const cateEditTitle = ref('')
const cateEditForm = ref({ cateId: '', cateName: '', cateMemo: '', cateSeq: 0 })
function handleCateClick(data) { currentCateId.value = data.cateId; loadFileList(data.cateId) }
function handleAddCate() {
  cateEditForm.value = { cateId: '', cateName: '', cateMemo: '', cateSeq: 0 }
  cateEditTitle.value = '新增分类'; cateEditVisible.value = true
}
function handleEditCate(data) {
  getDocCate(data.cateId).then(res => {
    cateEditForm.value = { cateId: res.data.cateId, cateName: res.data.cateName, cateMemo: res.data.cateMemo || '', cateSeq: res.data.cateSeq || 0 }
    cateEditTitle.value = '编辑分类'; cateEditVisible.value = true
  })
}
function submitCateEdit() {
  if (!cateEditForm.value.cateName) { ElMessage.warning('请输入分类名称'); return }
  const action = cateEditForm.value.cateId ? updateDocCate(cateEditForm.value) : addDocCate(cateEditForm.value)
  action.then(() => { ElMessage.success('操作成功'); cateEditVisible.value = false; loadCateTree() })
}
function handleDeleteCate(data) {
  proxy.$modal.confirm('确认删除分类"' + data.cateName + '"？').then(() => {
    delDocCate(data.cateId).then(() => { ElMessage.success('删除成功'); loadCateTree() })
  })
}
function handleUpload() { uploadVisible.value = true }
function beforeUpload(file) {
  const maxSize = 50 * 1024 * 1024
  if (file.size > maxSize) { ElMessage.error('文件大小不能超过 50MB'); return false }
  return true
}
function handleUploadSuccess(res) {
  if (res.code === 200) { ElMessage.success('上传成功'); loadFileList(currentCateId.value) }
  else { ElMessage.error(res.msg || '上传失败') }
}
function handleUploadError() { ElMessage.error('上传失败') }
function handleSelectionChange(rows) { selectedRows.value = rows }
function handleDownload(row) {
  const url = `/common/download?fileName=${encodeURIComponent(row.filePath)}`
  const a = document.createElement('a')
  a.href = url; a.download = row.fileName; a.click()
}
function handleRename(row) {
  ElMessageBox.prompt('请输入新的文件名称', '重命名', {
    inputValue: row.fileName,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValidator: (val) => val && val.trim() ? true : '文件名不能为空',
  }).then(({ value }) => {
    updateDocFile({ fileId: row.fileId, fileName: value.trim() }).then(() => {
      ElMessage.success('重命名成功')
      loadFileList(currentCateId.value)
    })
  }).catch(() => {})
}
function handleMove(row) {
  moveFileIds.value = [row.fileId]; moveTargetCateId.value = ''; moveVisible.value = true
}
function handleBatchMove() {
  moveFileIds.value = selectedRows.value.map(r => r.fileId); moveTargetCateId.value = ''; moveVisible.value = true
}
function handleMoveCateClick(data) { moveTargetCateId.value = data.cateId }
function submitMove() {
  if (!moveTargetCateId.value) { ElMessage.warning('请选择目标分类'); return }
  moveDocFile({ fileIds: moveFileIds.value.join(','), fileCate: moveTargetCateId.value }).then(() => {
    ElMessage.success('移动成功'); moveVisible.value = false; loadFileList(currentCateId.value)
  })
}
function handleDelete(row) {
  proxy.$modal.confirm('确认删除"' + row.fileName + '"？').then(() => { delDocFile(row.fileId).then(() => { ElMessage.success('删除成功'); loadFileList(currentCateId.value) }) })
}
function loadFileList(cateId) {
  const params = cateId ? { fileCate: cateId } : {}
  getDocFileList(params).then(r => { fileList.value = r.rows; loading.value = false })
}
function loadCateTree() { getDocCateTree().then(r => { cateTree.value = r.data || r.rows || [] }) }
onMounted(() => { loadCateTree(); loadFileList() })
</script>
<style scoped>
.card-header { font-weight: 600; font-size: 16px; display: flex; justify-content: space-between; align-items: center; }
.custom-tree-node { flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-right: 8px; }
.tree-actions { display: none; }
.custom-tree-node:hover .tree-actions { display: inline; }
</style>
