<template>
  <div class="app-container">
    <div class="portal-header">
      <h2 class="portal-title">规章制度</h2>
      <el-button type="primary" icon="Plus" @click="handleUploadDoc" v-hasPermi="['efinder:file:upload']">上传文件</el-button>
    </div>

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="文件名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入文件名�? clearable style="width: 240px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="docList" stripe>
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column label="文件名称" min-width="300" :show-overflow-tooltip="true">
        <template #default="scope">
          <el-link type="primary" :underline="false" @click="handlePreview(scope.row)">
            <svg-icon :icon-class="getFileIcon(scope.row.type)" class="file-icon" />
            {{ scope.row.name }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="文件类型" width="100" align="center" prop="type" />
      <el-table-column label="文件大小" width="120" align="center" prop="size" />
      <el-table-column label="上传时间" width="160" align="center" prop="date">
        <template #default="scope">
          <span>{{ parseTime(scope.row.date) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160" align="center">
        <template #default="scope">
          <el-button link type="primary" icon="Download" @click="handleDownload(scope.row)">下载</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['efinder:file:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-empty v-if="!loading && docList.length === 0" description="暂无规章制度" />

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

    <el-dialog title="上传文件" v-model="uploadVisible" width="500px" append-to-body>
      <el-upload
        ref="uploadRef"
        :action="uploadUrl"
        :headers="uploadHeaders"
        :data="uploadData"
        :before-upload="beforeUpload"
        :on-success="uploadSuccess"
        :on-error="uploadError"
        :auto-upload="false"
        drag
        multiple
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，�?em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">支持 PDF、Word、Excel 等格�?/div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitUpload">开始上�?/el-button>
          <el-button @click="uploadVisible = false">�?�?/el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Gzzd">
import { getFileList, folderList, downloadFile, deleteFile } from "@/api/efinder/finder"
import { getToken } from "@/utils/auth"
import { parseTime } from "@/utils/goldenwater"

const { proxy } = getCurrentInstance()
const router = useRouter()

const docList = ref([])
const total = ref(0)
const loading = ref(true)
const showSearch = ref(true)
const uploadVisible = ref(false)
const categoryFolderId = ref(null)

const uploadRef = ref(null)
const uploadUrl = ref(import.meta.env.VITE_SERVICE_BASE_TITLE + "/efinder/file/upload")
const uploadHeaders = ref({ Authorization: "Bearer " + getToken() })
const uploadData = ref({})

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    name: undefined,
    pid: null
  }
})

const { queryParams } = toRefs(data)

function getDocList() {
  loading.value = true
  queryParams.value.pid = categoryFolderId.value
  getFileList(queryParams.value).then(response => {
    docList.value = response.rows || response.data || []
    total.value = response.total || docList.value.length
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

function handleQuery() {
  queryParams.value.pageNum = 1
  getDocList()
}

function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

function handleUploadDoc() {
  uploadData.value = { pid: categoryFolderId.value }
  uploadVisible.value = true
  nextTick(() => {
    if (uploadRef.value) {
      uploadRef.value.clearFiles()
    }
  })
}

function submitUpload() {
  proxy.$refs.uploadRef.submit()
}

function beforeUpload(file) {
  const isLtSize = file.size / 1024 / 1024 < 100
  if (!isLtSize) {
    proxy.$modal.msgError("上传文件大小不能超过 100MB")
    return false
  }
  return true
}

function uploadSuccess(response) {
  if (response.code === 200) {
    proxy.$modal.msgSuccess("上传成功")
    uploadVisible.value = false
    getDocList()
  } else {
    proxy.$modal.msgError(response.msg)
  }
}

function uploadError() {
  proxy.$modal.msgError("上传失败")
}

function handlePreview(row) {
  const fileType = row.type ? row.type.toLowerCase() : ""
  router.push({ path: "/efinder/viewer", query: { fileId: row.id, fileType, fileName: row.name } })
}

function handleDownload(row) {
  downloadFile(row.id).then(res => {
    const blob = new Blob([res])
    const link = document.createElement("a")
    link.href = URL.createObjectURL(blob)
    link.download = row.name
    link.click()
    URL.revokeObjectURL(link.href)
    proxy.$modal.msgSuccess("下载成功")
  })
}

function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除"' + row.name + '"?').then(() => {
    return deleteFile(row.id)
  }).then(() => {
    getDocList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

function getFileIcon(fileType) {
  const map = {
    pdf: "pdf", doc: "word", docx: "word",
    xls: "excel", xlsx: "excel",
    ppt: "ppt", pptx: "ppt",
    txt: "txt"
  }
  return map[fileType] || "file"
}

onMounted(async () => {
  const res = await folderList({ fdCate: "gzzd", pageSize: 1 })
  const folder = (res.rows && res.rows[0]) || (res.data && res.data[0])
  if (folder) {
    categoryFolderId.value = folder.id
  }
  getDocList()
})
</script>

<style lang="scss" scoped>
.portal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.portal-title {
  font-size: 20px;
  font-weight: 600;
  margin: 0;
}

.file-icon {
  margin-right: 4px;
  font-size: 16px;
  vertical-align: middle;
}
</style>
