<template>
  <div class="app-container">
    <!-- Tab 切换 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="我的文件" name="my"></el-tab-pane>
      <el-tab-pane label="共享文件" name="share"></el-tab-pane>
      <el-tab-pane label="与我相关" name="related"></el-tab-pane>
    </el-tabs>

    <!-- 左右分栏布局 -->
    <div class="file-layout">
      <!-- 左侧边栏 -->
      <div class="file-sidebar">
        <!-- 搜索框 -->
        <div class="sidebar-section">
          <el-input
            v-model="queryParams.fileName"
            prefix-icon="el-icon-search"
            placeholder="按名称搜索"
            clearable
            size="mini"
            @change="handleQuery"
            @clear="handleQuery"
          ></el-input>
        </div>

        <!-- 文件类型列表 -->
        <div class="sidebar-section sidebar-file-types">
          <div class="sidebar-label">文件类型</div>
          <div class="file-type-list">
            <div
              v-for="opt in fileTypeOptions"
              :key="opt.value"
              class="type-list-item"
              :class="{ active: (queryParams.fileType || '') === opt.value }"
              @click="handleTypeTabClick(opt.value)"
            >{{ opt.label }}</div>
          </div>
        </div>
      </div>

      <!-- 右侧主区域 -->
      <div class="file-main">
        <!-- 工具栏 -->
        <div class="main-toolbar">
          <el-button icon="el-icon-sort" size="mini" @click="toggleQuery">高级搜索</el-button>
          <el-button v-if="activeTab === 'my'" type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">上传文件</el-button>
          <el-button v-if="activeTab === 'my'" type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
        </div>

        <!-- 高级搜索 -->
        <div v-show="showQuery" class="advanced-search">
          <el-form :model="queryParams" inline size="mini" class="advanced-search-form">
            <el-form-item label="订单编号">
              <el-input v-model="queryParams.orderNo" placeholder="订单编号" clearable @change="handleQuery" style="width:140px;"></el-input>
            </el-form-item>
            <el-form-item label="所属部门">
              <el-input v-model="queryParams.dept" placeholder="所属部门" clearable @change="handleQuery" style="width:140px;"></el-input>
            </el-form-item>
            <el-form-item label="文件类型">
              <el-select v-model="queryParams.fileType" placeholder="文件类型" clearable @change="handleQuery" style="width:120px;">
                <el-option v-for="item in dict.type.sys_file_type" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="可见范围" v-if="activeTab === 'my'">
              <el-select v-model="queryParams.scopeType" placeholder="可见范围" clearable @change="handleQuery" style="width:120px;">
                <el-option label="公开" :value="1" />
                <el-option label="私有" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="上传时间">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                clearable
                style="width:240px;"
                @change="handleQuery"
              ></el-date-picker>
            </el-form-item>
          </el-form>
        </div>

        <!-- 文件表格 -->
        <div class="file-table-wrapper">
          <KLPTable v-loading="loading" :data="fileList" @selection-change="handleSelectionChange" highlight-current-row @row-click="handleRowClick">
            <el-table-column type="selection" width="50" align="center" v-if="activeTab === 'my'" />
            <el-table-column label="文件名称" align="center" prop="fileName" :show-overflow-tooltip="true" min-width="160">
              <template slot-scope="scope">
                <el-link type="primary" @click="handleShowInfo(scope.row)">{{ scope.row.fileName }}</el-link>
              </template>
            </el-table-column>
            <el-table-column label="上传人" align="center" prop="createBy" width="100" />
            <el-table-column label="所属部门" align="center" prop="dept" width="120" :show-overflow-tooltip="true" />
            <el-table-column label="订单编号" align="center" prop="orderNo" width="130" :show-overflow-tooltip="true" />
            <el-table-column label="文件类型" align="center" width="100">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.sys_file_type" :value="scope.row.fileType"/>
              </template>
            </el-table-column>
            <el-table-column label="文件大小" align="center" width="90">
              <template slot-scope="scope">
                <span>{{ formatFileSize(scope.row.fileSize) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="可见范围" align="center" width="80">
              <template slot-scope="scope">
                <el-tag :type="scope.row.scopeType === 1 ? 'success' : 'warning'" size="small">
                  {{ scope.row.scopeType === 1 ? '公开' : '私有' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="上传时间" align="center" width="155">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="浏览次数" align="center" width="75">
              <template slot-scope="scope">
                <span>{{ scope.row.viewCount != null ? scope.row.viewCount : 0 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="140" fixed="right">
              <template slot-scope="scope">
                <div class="action-cell">
                  <el-button type="text" size="mini" icon="el-icon-view" @click.stop="handleShowInfo(scope.row)">详情</el-button>
                  <el-button v-if="canEdit(scope.row)" type="text" size="mini" icon="el-icon-edit" @click.stop="handleUpdate(scope.row)">编辑</el-button>
                </div>
              </template>
            </el-table-column>
          </KLPTable>

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

    <!-- 上传/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="open" width="650px" append-to-body @close="handleDialogClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="文件名称" prop="fileName">
          <el-input v-model="form.fileName" placeholder="请输入文件名称" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="上传文件" v-if="!isEdit">
          <el-upload
            ref="upload"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :file-list="uploadFileList"
            :before-upload="handleBeforeUpload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :auto-upload="false"
            :limit="1"
            class="upload-demo"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击选取</em></div>
          </el-upload>
        </el-form-item>
        <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="所属部门" prop="dept">
          <el-input v-model="form.dept" placeholder="请输入所属部门" />
        </el-form-item>
        <el-form-item label="文件类型" prop="fileType">
          <el-select v-model="form.fileType" placeholder="请选择文件类型" style="width:100%">
            <el-option v-for="item in dict.type.sys_file_type" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="可见范围" prop="scopeType">
          <el-radio-group v-model="form.scopeType" @change="handleScopeChange">
            <el-radio :label="1">公开（所有人可见）</el-radio>
            <el-radio :label="2">私有（指定用户可见）</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="可见用户" v-if="form.scopeType === 2">
          <user-select v-model="form.visibleUsers" :multiple="true" placeholder="请选择可见用户" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :rows="3" />
        </el-form-item>
      </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-dialog :title="infoTitle" :visible.sync="infoVisible" width="1100px" append-to-body top="5vh" @close="handleInfoClose">
      <div v-if="infoFile" class="info-dialog-body">
        <div class="info-preview">
          <ImagePreview v-if="infoFileCategory === 'image'" :src="infoFile.filePath" />
          <PdfPreview v-else-if="infoFileCategory === 'pdf'" :src="infoFile.filePath" />
          <DocxPreview v-else-if="infoFileCategory === 'docx'" :src="infoFile.filePath" />
          <XlsxPreview v-else-if="infoFileCategory === 'xlsx'" :src="infoFile.filePath" />
          <XlsPreview v-else-if="infoFileCategory === 'xls'" :src="infoFile.filePath" />
          <div v-else class="info-preview-empty">
            <el-empty description="暂不支持预览此文件类型" />
          </div>
        </div>
        <div class="info-meta">
          <el-descriptions :column="1" border size="small">
            <el-descriptions-item label="文件名称">{{ infoFile.fileName }}</el-descriptions-item>
            <el-descriptions-item label="文件类型">
              <dict-tag :options="dict.type.sys_file_type" :value="infoFile.fileType"/>
            </el-descriptions-item>
            <el-descriptions-item label="文件大小">{{ formatFileSize(infoFile.fileSize) }}</el-descriptions-item>
            <el-descriptions-item label="文件后缀">{{ infoFile.suffix || '-' }}</el-descriptions-item>
            <el-descriptions-item label="浏览次数">{{ infoFile.viewCount != null ? infoFile.viewCount : 0 }} 次</el-descriptions-item>
            <el-descriptions-item label="订单编号">{{ infoFile.orderNo || '-' }}</el-descriptions-item>
            <el-descriptions-item label="所属部门">{{ infoFile.dept || '-' }}</el-descriptions-item>
            <el-descriptions-item label="可见范围">
              <el-tag :type="infoFile.scopeType === 1 ? 'success' : 'warning'" size="small">
                {{ infoFile.scopeType === 1 ? '公开' : '私有' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="上传人">{{ infoFile.createBy }}</el-descriptions-item>
            <el-descriptions-item label="上传时间">{{ parseTime(infoFile.createTime) }}</el-descriptions-item>
            <el-descriptions-item label="备注">{{ infoFile.remark || '-' }}</el-descriptions-item>
          </el-descriptions>
          <!-- 评论区域 -->
          <div class="info-comment">
            <div class="comment-bar" @click="commentExpanded = !commentExpanded">
              <span><i class="el-icon-chat-dot-round"></i> 评论 ({{ comments.length }})</span>
              <span class="comment-toggle">{{ commentExpanded ? '收起' : '展开' }} <i :class="commentExpanded ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span>
            </div>
            <div v-show="commentExpanded" class="comment-body">
              <div v-if="commentLoading" class="comment-hint"><i class="el-icon-loading"></i> 加载中...</div>
              <div v-else-if="comments.length === 0" class="comment-hint comment-empty">暂无评论</div>
              <div v-else class="comment-list">
                <div v-for="item in comments" :key="item.commentId" class="comment-item">
                  <div class="comment-meta">
                    <span class="comment-dept">{{ item.dept }}</span>
                    <span class="comment-user">{{ item.createBy }}</span>
                    <span class="comment-time">{{ parseTime(item.createTime) }}</span>
                  </div>
                  <div class="comment-text">{{ item.content }}</div>
                </div>
              </div>
              <div class="comment-input-area">
                <el-input v-model="commentInput" type="textarea" :rows="2" placeholder="输入评论..." resize="none" />
                <el-button type="primary" size="mini" @click="handleAddComment" :disabled="!commentInput.trim()" style="margin-top:6px;">发送</el-button>
              </div>
            </div>
          </div>
          <div style="margin-top:12px;text-align:right;">
            <el-button type="warning" plain size="mini" icon="el-icon-download" @click="handleExportInfo">导出</el-button>
            <el-button type="primary" size="mini" icon="el-icon-download" @click="downloadFile(infoFile)">下载</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFile, getFile, addFile, updateFile, delFile, exportFile, listVisibleUser, addVisibleUser, delVisibleUser, listVisibleUserByFileId, listRelatedToMe, incrementView } from '@/api/system/file'
import { listFileComment, addFileComment } from '@/api/system/fileComment'
import { getToken } from '@/utils/auth'
import UserSelect from '@/components/KLPService/UserSelect/index'
import ImagePreview from '@/components/FilePreview/preview/image/index.vue'
import PdfPreview from '@/components/FilePreview/preview/pdf/index.vue'
import DocxPreview from '@/components/FilePreview/preview/docx/index.vue'
import XlsxPreview from '@/components/FilePreview/preview/xlsx/index.vue'
import XlsPreview from '@/components/FilePreview/preview/xls/index.vue'

export default {
  name: 'SysFile',
  dicts: ['sys_file_type'],
  components: {
    UserSelect,
    ImagePreview,
    PdfPreview,
    DocxPreview,
    XlsxPreview,
    XlsPreview
  },
  data() {
    return {
      // 当前激活tab
      activeTab: 'my',
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示高级搜索
      showQuery: false,
      // 总条数
      total: 0,
      // 文件列表
      fileList: [],
      // 弹出层标题
      dialogTitle: '',
      // 是否显示弹出层
      open: false,
      // 是否编辑
      isEdit: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        fileName: undefined,
        orderNo: undefined,
        dept: undefined,
        fileType: undefined,
        scopeType: undefined
      },
      // 表单
      form: {
        fileId: undefined,
        fileName: undefined,
        filePath: undefined,
        fileSize: undefined,
        suffix: undefined,
        orderNo: undefined,
        dept: undefined,
        fileType: undefined,
        scopeType: 1,
        visibleUsers: [],
        remark: undefined
      },
      // 可见用户原始数据（编辑时回显）
      originalVisibleUsers: [],
      // 表单校验
      rules: {
        fileName: [
          { required: true, message: '文件名称不能为空', trigger: 'blur' }
        ],
        fileType: [
          { required: true, message: '请选择文件类型', trigger: 'change' }
        ]
      },
      // 上传相关
      uploadUrl: process.env.VUE_APP_BASE_API + '/system/oss/upload',
      uploadHeaders: {
        Authorization: 'Bearer ' + getToken()
      },
      uploadFileList: [],
      // 文件详情弹窗
      infoVisible: false,
      infoTitle: '',
      infoFile: null,
      // 评论
      comments: [],
      commentExpanded: false,
      commentInput: '',
      commentLoading: false
    }
  },
  computed: {
    /** 文件类型筛选选项 */
    fileTypeOptions() {
      const dict = this.dict.type.sys_file_type || []
      return [{ value: '', label: '全部' }, ...dict]
    },
    /** 详情弹窗中根据文件后缀决定预览组件 */
    infoFileCategory() {
      if (!this.infoFile) return null
      const raw = this.infoFile.suffix || this.infoFile.fileName || ''
      const ext = (raw.includes('.') ? raw.split('.').pop() : raw).toLowerCase()
      if (['png', 'jpg', 'jpeg', 'bmp', 'webp'].includes(ext)) return 'image'
      if (ext === 'pdf') return 'pdf'
      if (ext === 'docx') return 'docx'
      if (ext === 'xlsx') return 'xlsx'
      if (ext === 'xls') return 'xls'
      return 'other'
    }
  },
  created() {
    this.getList()
  },
  watch: {
    infoFile(val) {
      if (val) {
        this.loadComments()
      } else {
        this.comments = []
        this.commentExpanded = false
      }
    }
  },
  methods: {
    /** 切换tab */
    handleTabClick(tab) {
      this.resetQuery()
    },
    /** 查询文件列表 */
    getList() {
      this.loading = true
      const params = this.addDateRange(this.queryParams, this.dateRange)
      // 根据tab设置额外参数
      if (this.activeTab === 'my') {
        params.createBy = this.$store.getters.name
      } else if (this.activeTab === 'share') {
        params.scopeType = 1
      }

      // 根据tab选择不同的API
      let request
      if (this.activeTab === 'related') {
        request = listRelatedToMe(params)
      } else {
        request = listFile(params)
      }

      request.then(response => {
        this.fileList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 格式化文件大小 */
    formatFileSize(size) {
      if (!size) return '0 B'
      if (size < 1024) return size + ' B'
      if (size < 1024 * 1024) return (size / 1024).toFixed(2) + ' KB'
      return (size / 1024 / 1024).toFixed(2) + ' MB'
    },
    /** 是否可编辑 */
    canEdit(row) {
      if (this.activeTab === 'related') return false
      if (this.activeTab === 'share') return false
      return row.createBy === this.$store.getters.name
    },
    /** 取消按钮 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 对话框关闭回调 */
    handleDialogClose() {
      this.reset()
    },
    /** 表单重置 */
    reset() {
      this.form = {
        fileId: undefined,
        fileName: undefined,
        filePath: undefined,
        fileSize: undefined,
        suffix: undefined,
        orderNo: undefined,
        dept: undefined,
        fileType: undefined,
        scopeType: 1,
        visibleUsers: [],
        remark: undefined
      }
      this.uploadFileList = []
      this.originalVisibleUsers = []
      this.isEdit = false
      this.resetForm('form')
    },
    /** 可见范围切换 */
    handleScopeChange(val) {
      if (val === 1) {
        this.form.visibleUsers = []
      }
    },
    /** 搜索 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 切换高级搜索 */
    toggleQuery() {
      this.showQuery = !this.showQuery
    },
    /** 文件类型筛选切换 */
    handleTypeTabClick(value) {
      this.queryParams.fileType = value || undefined
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮 */
    resetQuery() {
      this.dateRange = []
      this.showQuery = false
      this.queryParams = {
        pageNum: 1,
        pageSize: 20,
        fileName: undefined,
        orderNo: undefined,
        dept: undefined,
        fileType: undefined,
        scopeType: undefined
      }
      this.getList()
    },
    /** 多选框 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fileId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增/上传 */
    handleAdd() {
      this.reset()
      this.isEdit = false
      this.open = true
      this.dialogTitle = '上传文件'
    },
    /** 修改 */
    handleUpdate(row) {
      this.reset()
      this.isEdit = true
      const fileId = row.fileId || this.ids[0]
      getFile(fileId).then(response => {
        const data = response.data
        this.form = {
          fileId: data.fileId,
          fileName: data.fileName,
          filePath: data.filePath,
          fileSize: data.fileSize,
          suffix: data.suffix,
          orderNo: data.orderNo,
          dept: data.dept,
          fileType: data.fileType,
          scopeType: data.scopeType,
          visibleUsers: [],
          remark: data.remark
        }
        if (data.scopeType === 2) {
          listVisibleUserByFileId(fileId).then(res => {
            const rows = res.rows || []
            this.form.visibleUsers = rows.map(r => r.userId)
            this.originalVisibleUsers = [...this.form.visibleUsers]
          })
        }
        this.open = true
        this.dialogTitle = '编辑文件'
      })
    },
    /** 上传前校验 */
    handleBeforeUpload(file) {
      if (!this.form.fileName) {
        this.form.fileName = file.name
      }
      const ext = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase()
      this.form.suffix = ext
      this.form.fileSize = file.size
    },
    /** 上传成功 */
    handleUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.form.filePath = response.data.url
        this.form.fileName = this.form.fileName || response.data.fileName
        this.$modal.msgSuccess('文件上传成功')
        this.doSubmit()
      } else {
        this.$modal.msgError(response.msg || '上传失败')
      }
    },
    /** 上传失败 */
    handleUploadError(err, file, fileList) {
      this.$modal.msgError('文件上传失败')
    },
    /** 提交表单 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.isEdit) {
            this.doSubmit()
          } else {
            if (this.$refs.upload && this.$refs.upload.uploadFiles.length > 0) {
              this.$refs.upload.submit()
            } else {
              this.$modal.msgWarning('请选择要上传的文件')
            }
          }
        }
      })
    },
    /** 执行提交 */
    doSubmit() {
      const data = { ...this.form }
      const visibleUsers = data.visibleUsers
      delete data.visibleUsers

      if (data.fileId) {
        updateFile(data).then(response => {
          this.saveVisibleUsers(data.fileId, visibleUsers)
          this.$modal.msgSuccess('修改成功')
          this.open = false
          this.getList()
        }).catch(() => {})
      } else {
        addFile(data).then(response => {
          const newFileId = response.data
          if (newFileId && visibleUsers && visibleUsers.length > 0) {
            this.saveVisibleUsers(newFileId, visibleUsers)
          }
          this.$modal.msgSuccess('新增成功')
          this.open = false
          this.getList()
        }).catch(() => {})
      }
    },
    /** 保存可见用户 */
    saveVisibleUsers(fileId, visibleUsers) {
      if (!visibleUsers || visibleUsers.length === 0) {
        if (this.originalVisibleUsers.length > 0) {
          delVisibleUser(this.originalVisibleUsers.join(','))
        }
        return
      }
      const toAdd = visibleUsers.filter(u => !this.originalVisibleUsers.includes(u))
      const toDel = this.originalVisibleUsers.filter(u => !visibleUsers.includes(u))

      if (toDel.length > 0) {
        listVisibleUserByFileId(fileId).then(res => {
          const rows = res.rows || []
          const delIds = rows.filter(r => toDel.includes(r.userId)).map(r => r.visibleId)
          if (delIds.length > 0) {
            delVisibleUser(delIds.join(','))
          }
        })
      }
      toAdd.forEach(userId => {
        addVisibleUser({ fileId, userId })
      })
    },
    /** 删除 */
    handleDelete(row) {
      const fileIds = row && row.fileId ? row.fileId : this.ids.join(',')
      this.$modal.confirm('是否确认删除所选文件？').then(() => {
        return delFile(fileIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 导出 */
    handleExport() {
      this.download('system/file/export', {
        ...this.queryParams
      }, `file_${new Date().getTime()}.xlsx`)
    },
    /** 详情弹窗关闭 */
    handleInfoClose() {
      this.infoFile = null
    },
    /** 打开详情弹窗 */
    handleShowInfo(row) {
      this.infoFile = row
      this.infoTitle = '文件详情 - ' + row.fileName
      this.infoVisible = true
      incrementView(row.fileId)
    },
    /** 点击行选中 */
    handleRowClick(row) {
      // 行点击不做跳转，仅高亮
    },
    /** 加载评论列表 */
    loadComments() {
      this.commentLoading = true
      listFileComment(this.infoFile.fileId).then(res => {
        this.comments = res.data || []
        this.commentLoading = false
      }).catch(() => {
        this.commentLoading = false
      })
    },
    /** 发送评论 */
    handleAddComment() {
      const content = this.commentInput.trim()
      if (!content) return
      addFileComment({ fileId: this.infoFile.fileId, content }).then(() => {
        this.commentInput = ''
        this.loadComments()
      })
    },
    /** 导出（详情弹窗中） */
    handleExportInfo() {
      this.download('system/file/export', {
        ...this.queryParams
      }, `file_${new Date().getTime()}.xlsx`)
    },
    /** 下载文件 */
    downloadFile(row) {
      if (row.filePath) {
        window.open(row.filePath, '_blank')
      }
    }
  }
}
</script>

<style scoped>
/* 左右分栏 */
.file-layout {
  display: flex;
  align-items: stretch;
  gap: 0;
  height: calc(100vh - 140px);
}

/* 左侧边栏 */
.file-sidebar {
  width: 220px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  padding-right: 12px;
  padding-top: 4px;
  overflow-y: auto;
}

.sidebar-section {
  margin-bottom: 12px;
}

.sidebar-label {
  font-size: 13px;
  font-weight: 500;
  color: #606266;
  margin-bottom: 6px;
  padding-left: 2px;
}

/* 文件类型列表（纵向） */
.sidebar-file-types {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.file-type-list {
  flex: 1;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.type-list-item {
  padding: 8px 12px;
  font-size: 13px;
  color: #606266;
  cursor: pointer;
  user-select: none;
  border-bottom: 1px solid #f2f2f2;
  transition: all 0.15s;
}

.type-list-item:last-child {
  border-bottom: none;
}

.type-list-item:hover {
  color: #5F7BA0;
  background: #f5f7fa;
}

.type-list-item.active {
  color: #fff;
  background: #5F7BA0;
  font-weight: 500;
}

.file-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
  padding-top: 4px;
}

.main-toolbar {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

/* 高级搜索 */
.advanced-search {
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px 16px;
  margin-bottom: 8px;
}

.advanced-search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.advanced-search-form /deep/ .el-form-item {
  margin-bottom: 0;
}

/* 表格区域 */
.file-table-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.file-table-wrapper .KLPTable {
  flex: 1;
}

/* 上传区域 */
.upload-demo {
  width: 100%;
}

/* 操作列按钮对齐 */
.action-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 2px;
  white-space: nowrap;
}

/* 详情弹窗主体 */
.info-dialog-body {
  display: flex;
  gap: 16px;
  min-height: 400px;
}

.info-preview {
  flex: 1;
  min-width: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafafa;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: auto;
  padding: 8px;
}

.info-preview-empty {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
}

.info-meta {
  width: 320px;
  flex-shrink: 0;
  overflow-y: auto;
}

/* 详情弹窗评论区 */
.info-comment {
  margin-top: 12px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.comment-bar {
  padding: 8px 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  font-size: 13px;
  color: #606266;
  user-select: none;
}

.comment-bar:hover {
  background: #f5f7fa;
}

.comment-toggle {
  color: #909399;
  font-size: 12px;
}

.comment-body {
  max-height: 220px;
  overflow-y: auto;
  border-top: 1px solid #ebeef5;
}

.comment-hint {
  padding: 16px;
  text-align: center;
  color: #909399;
  font-size: 13px;
}

.comment-list {
  padding: 4px 0;
}

.comment-item {
  padding: 8px 12px;
  border-bottom: 1px solid #f2f2f2;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-meta {
  display: flex;
  gap: 8px;
  align-items: center;
  font-size: 12px;
  margin-bottom: 4px;
}

.comment-dept {
  color: #409eff;
  font-weight: 500;
}

.comment-user {
  color: #606266;
}

.comment-time {
  color: #c0c4cc;
}

.comment-text {
  font-size: 13px;
  color: #303133;
  line-height: 1.5;
  word-break: break-all;
}

.comment-input-area {
  padding: 8px 12px;
  border-top: 1px solid #f2f2f2;
}
</style>

<!-- 表格选中行高亮 -->
<style>
.file-main .el-table .current-row > td {
  background-color: #ecf5ff !important;
}
</style>
