<template>
  <div>
    <div class="upload-btn">
      <el-upload
          v-model:file-list="fileList"
          class="upload-demo"
          :action="uploadUrl"
          :show-file-list="false"
          :data="{
              rescue_id: props.rescueId
            }"
          :on-success="onSuccess"
      >
        <el-button type="primary">上传附件</el-button>
      </el-upload>
    </div>
    <el-table :data="fileData" border style="width: 100%">
      <el-table-column property="file_org_name" label="文件名称" />
      <el-table-column property="file_length" label="文件大小" width="150">
        <template #default="scope">
          <span class="file-size">{{ formatFileSize(scope.row.file_length) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" align="center">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleDownload(scope.row.tsy_id)">下载</el-button>
          <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              :icon="InfoFilled"
              icon-color="#626AEF"
              title="是否确认删除?"
              @confirm="handleDelete(scope.row.tsy_id)"
          >
            <template #reference>
              <el-button link type="primary" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import {regFileDelete, regFileList} from "@/api/task.js"
import {InfoFilled} from '@element-plus/icons-vue'

const uploadUrl = import.meta.env.VITE_APP_BASE_API + '/rs/rescue/reg/file/upload.htm'

const fileList = ref([])
const fileData = ref([])

const props = defineProps({
  rescueId: {
    type: String, // 根据实际情况定义类型
    default: ''
  }
})

// 查看附件列表
const getFileList = () => {
  regFileList({rescue_id: props.rescueId}).then(res => {
    fileData.value = res.array
  })
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 文件上传成功回调
const onSuccess = () => {
  regFileList({rescue_id: props.rescueId}).then(res => {
    fileData.value = res.array
  })
}

// 文件下载
const handleDownload = async (fileId) => {
  window.open(`${import.meta.env.VITE_APP_BASE_API}/rs/rescue/reg/file/download.htm?file_id=${fileId}`)
}

// 文件删除
const handleDelete = (fileId) => {
  regFileDelete({
    file_id: fileId
  }).then(res => {
    regFileList({rescue_id: props.rescueId}).then(res => {
      fileData.value = res.array
    })
  })
}

onMounted(() => {
  if (props.rescueId) {
    getFileList()
  }
})
</script>

<style scoped lang="scss">
.upload-btn {
  text-align: right;
  margin-bottom: 20px;
}
</style>
