<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card shadow="never">
          <template #header>
            <span>附件目录</span>
            <el-button link type="primary" icon="Plus" style="float:right" @click="handleAddFolder" />
          </template>
          <el-tree :data="folderTree" node-key="id" :props="treeProps" highlight-current @node-click="handleNodeClick" />
        </el-card>
      </el-col>
      <el-col :span="18">
        <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 @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-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-upload :action="uploadUrl" :headers="uploadHeaders" :on-success="handleUploadSuccess" :show-file-list="false" accept="*">
              <el-button type="primary" plain icon="Upload">上传文件</el-button>
            </el-upload>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['pms:accessory:remove']">删除</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
        </el-row>
        <el-table v-loading="loading" :data="accessoryList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="文件名称" align="center" prop="name" min-width="200" show-overflow-tooltip />
          <el-table-column label="文件大小" align="center" prop="fileSize" width="100" />
          <el-table-column label="文件类型" align="center" prop="fileType" width="80" />
          <el-table-column label="操作" align="center" width="260">
            <template #default="scope">
              <el-button link type="primary" icon="Download" @click="handleDownload(scope.row)">下载</el-button>
              <el-button link type="primary" icon="Edit" @click="handleRename(scope.row)">重命名</el-button>
              <el-button link type="primary" icon="Rank" @click="handleMove(scope.row)">移动</el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['pms:accessory:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-col>
    </el-row>

    <el-dialog title="移动到文件夹" v-model="moveOpen" width="400px" append-to-body>
      <el-tree :data="folderTree" node-key="id" :props="treeProps" highlight-current @node-click="handleMoveTarget" />
      <template #footer>
        <el-button type="primary" @click="submitMove">确 定</el-button>
        <el-button @click="moveOpen = false">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PmsAccessory">
import { listAccessory, getAccessory, delAccessory, selectFolder, saveFile, updateAccessory, saveMove } from '@/api/pms/accessory'
import { getToken } from '@/utils/auth'

const { proxy } = getCurrentInstance()
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const multiple = ref(true)
const total = ref(0)
const accessoryList = ref([])
const folderTree = ref([])
const currentFolder = ref(undefined)

const uploadUrl = ref(import.meta.env.VITE_SERVICE_BASE_TITLE + '/pms/accessory/upload')
const uploadHeaders = ref({ Authorization: 'Bearer ' + getToken() })

const treeProps = { children: 'children', label: 'name' }
const moveOpen = ref(false)
const moveRow = ref({})

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

const { queryParams } = toRefs(data)

function getFolderTree() {
  selectFolder().then(response => {
    folderTree.value = response.data || []
  })
}

function getList() {
  loading.value = true
  listAccessory({ ...queryParams.value, folderId: currentFolder.value }).then(response => {
    accessoryList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

function handleNodeClick(data) {
  currentFolder.value = data.id
  getList()
}

function handleQuery() { queryParams.value.pageNum = 1; getList() }
function resetQuery() { proxy.resetForm("queryRef"); handleQuery() }

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  multiple.value = !selection.length
}

function handleUploadSuccess(response) {
  proxy.$modal.msgSuccess("上传成功")
  getList()
}

function handleDownload(row) {
  window.open(import.meta.env.VITE_SERVICE_BASE_TITLE + '/pms/accessory/download/' + row.id)
}

function handleDelete(row) {
  const delIds = row.id || ids.value
  proxy.$modal.confirm('是否确认删除该附件？').then(() => {
    return delAccessory(delIds)
  }).then(() => { getList(); proxy.$modal.msgSuccess("删除成功") }).catch(() => {})
}

let moveTargetId = null

function handleRename(row) {
  proxy.$modal.prompt('请输入新名称', '重命名', { inputValue: row.name, inputPattern: /\S/, inputErrorMessage: '名称不能为空' }).then(({ value }) => {
    updateAccessory({ id: row.id, name: value }).then(() => {
      getList()
      proxy.$modal.msgSuccess("重命名成功")
    })
  }).catch(() => {})
}

function handleMove(row) {
  moveRow.value = row
  moveTargetId = null
  moveOpen.value = true
}

function handleMoveTarget(data) {
  moveTargetId = data.id
}

function submitMove() {
  if (!moveTargetId) {
    proxy.$modal.msgWarning("请选择目标文件夹")
    return
  }
  saveMove({ id: moveRow.value.id, parentId: moveTargetId }).then(() => {
    moveOpen.value = false
    getList()
    proxy.$modal.msgSuccess("移动成功")
  })
}

function handleAddFolder() {
  proxy.$modal.prompt('请输入文件夹名称', '新增文件夹', { inputPattern: /\S/, inputErrorMessage: '名称不能为空' }).then(({ value }) => {
    saveFile({ name: value, isFolder: true, parentId: currentFolder.value }).then(() => {
      getFolderTree()
      proxy.$modal.msgSuccess("新增成功")
    })
  }).catch(() => {})
}

onMounted(() => {
  getFolderTree()
  getList()
})
</script>
