<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--文件夹数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="folderName"
            placeholder="请输入文件夹名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="fileOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
  <span class="custom-tree-node" style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
    <span style="display: flex; align-items: center;">
      <!-- 文件夹图标 -->
      <svg x="1750230337349" class="icon" viewBox="0 0 1024 1024"
           xmlns="http://www.w3.org/2000/svg" p-id="1538" width="1em" height="1em">
        <path
          d="M918.673 883H104.327C82.578 883 65 867.368 65 848.027V276.973C65 257.632 82.578 242 104.327 242h814.346C940.422 242 958 257.632 958 276.973v571.054C958 867.28 940.323 883 918.673 883z"
          fill="#FFE9B4" p-id="1539"></path>
        <path
          d="M512 411H65V210.37C65 188.597 82.598 171 104.371 171h305.92c17.4 0 32.71 11.334 37.681 28.036L512 411z"
          fill="#FFB02C" p-id="1540"></path>
        <path
          d="M918.673 883H104.327C82.578 883 65 865.42 65 843.668V335.332C65 313.58 82.578 296 104.327 296h814.346C940.422 296 958 313.58 958 335.332v508.336C958 865.32 940.323 883 918.673 883z"
          fill="#FFCA28" p-id="1541"></path>
      </svg>

      <!-- 文件夹名称 -->
       <span style="margin-left: 6px;">{{ data.label}}</span>
    </span>

      <!-- 文件操作 -->
     <span class="tree-node-actions" @click.stop="">
  <el-dropdown placement="bottom-end" trigger="click"  @visible-change="(visible) => { if (visible) getLevel(data.id); }"
  >
    <el-button size="small" type="text" icon="el-icon-setting" style="margin-left: auto;"></el-button>
    <template #dropdown>
    <el-dropdown-menu style="min-width: 120px;">
  <!-- 新增按钮：仅当层级小于4时显示 -->
  <el-button
    v-if="levels[data.id] !== undefined && levels[data.id] >= 0 && levels[data.id] < 4"
    size="mini"
    type="primary"
    plain
    style="width: 60px; border: none; text-align: center;"
    @click="handleAddFolder(data)">
    新增
  </el-button>

      <!-- 修改按钮始终显示 -->
  <el-button
    size="mini"
    type="primary"
    plain
    style="width: 60px;border: none; text-align: center;"
    @click="handleUpdateFolderName(data)">
    修改
  </el-button>

      <!-- 删除按钮始终显示 -->
  <el-button
    size="mini"
    type="primary"
    plain
    style="width: 60px; border:none; text-align: center;"
    @click="handleDeleteFolder(data)">
    删除
  </el-button>
</el-dropdown-menu>
      </template>
  </el-dropdown>
</span>
    </span>
            </template>
          </el-tree>
          >
        </div>
      </el-col>
      <!--文件数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
          <el-form-item label="文件名称" prop="fileName">
            <el-input
              v-model="queryParams.fileName"
              placeholder="请输入文件名称"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="文件状态"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in dict.type.sys_file_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="dateRange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['system:file:import']"
            >上传文件
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['system:file:export']"
            >导出文件
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-delete"
              size="mini"
              @click="handleDelete"
              v-hasPermi="['system:file:remove']"
            >删除文件
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-download"
              size="mini"
              @click="importTemplate"
            >下载模板
            </el-button>
          </el-col>
          <!-- 超级用户上传模板按钮 -->
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleUploadTemplate"
            >上传模板
            </el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

<!-- 文件列表 --->
        <el-table v-loading="loading" :data="fileList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="文件编号" type="index" width="50" :index="indexMethod" align="center" key="filelId"
                           prop="fileId" v-if="columns[0].visible"/>
          <el-table-column label="文件名称" align="center" key="fileName" prop="fileName" v-if="columns[1].visible"
                           :show-overflow-tooltip="true"/>
          <el-table-column label="文件类型" align="center" key="fileType" prop="fileType" v-if="columns[2].visible"
                           :show-overflow-tooltip="true"/>
          <el-table-column label="所属文件夹" align="center" key="folderId" prop="folderId" v-if="columns[3].visible"
                           :show-overflow-tooltip="true" :formatter="getFolderName"/>
          <el-table-column label="创建者" align="center" key="ceateBy" prop="createBy" v-if="columns[4].visible"
                           width="120"/>
          <el-table-column label="状态" align="center" key="status" v-if="columns[5].visible">
            <template #default="{ row }">
  <el-switch
    v-model="row.status"
    :active-value="'0'"
    :inactive-value="'1'"
    @change="handleStatusChange(row)"
    active-text="正常"
    inactive-text="停用"
    active-color="#13ce66"
    inactive-color="#ff4949"
  />
</template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[6].visible" width="160">
            <template v-slot="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-download"
                @click="handleDownload(scope.row)"
                v-hasPermi="['system:file:remove']"
              >下载
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改文件配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="文件名称" prop="fileName">
              <el-input v-model="form.fileName" placeholder="请输入文件名称" maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建者" prop="createBy">
              <el-input v-model="form.createBy" placeholder="请输入创建者" maxlength="20"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="归属文件夹" prop="folderId">
              <treeselect v-model="form.folderId" :options="fileOptions" :show-count="true"
                          placeholder="请选择归属文件夹"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="文件类型" prop="fileType">
              <el-select v-model="form.fileType" placeholder="请选择文件类型" clearable>
                <el-option label="PDF文档" value="pdf"/>
                <el-option label="Word文档" value="docx"/>
                <el-option label="Excel表格" value="xlsx"/>
                <el-option label="旧版Excel" value="xls"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-table-column label="状态" prop="status" v-if="columns[4].visible">
            <template v-slot="{row}">
              <el-switch
                v-model="row.status"
                :active-value="'0'"
                :inactive-value="'1'"
                @change="handleStatusChange(row)"
                active-text="正常"
                inactive-text="停用"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </template>
          </el-table-column>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </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="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept="allowedFileTypes.join(',')"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-error="handleFileError"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport"/>
            是否更新已经存在的文件数据
          </div>
          <span>仅允许导入{{ allowedFileTypes.join('、') }}格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getToken} from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
  addFolder,
  delFolder,
  folderTreeSelect,
  getFolder,
  updateFolder,
  checkFolderDeletable,
  folderTreeSelectByDeptId
} from "@/api/system/folder";
import {addFile, delFile, download, listFile, updateFile} from "@/api/system/file";
import dict from "@/utils/dict";
import {parseTime} from "@/utils/xzl";
import {updateFileStatus} from "@/api/system/file";
import {saveAs} from "file-saver";

export default {
  name: "File",
  dicts: ['sys_file_status', 'sys_user_sex'],
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件表格数据
      fileList: [],
      // 弹出层标题
      title: "",
      // 文件夹树选项
      fileOptions: [],
      // 是否显示弹出层
      open: false,
      // 文件夹名称
      folderName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      //父文件夹名称
      parentFolderCache: [],
      // 用于缓存每个文件夹的 level 值
      levels: [],
      // 新增字段：用于缓存选中的文件夹ID
      selectedFolderId: null,
      // 文件上传参数
      allowedFileTypes: ['.xlsx', '.xls', '.pdf', '.docx'],
      // 表单参数
      form: {
        fileId: null,
        folderId: null,
        fileName: null,
        fileType: '',
        fileSize: null,
        filePath: null,
        status: '0', // 默认启用
        remark: null
      },
      // 配置 el-tree 组件的数据结构映射规则
      defaultProps: {
        // 指定数据对象中表示子节点数组的字段名
        children: "children",
        // 指定数据对象中表示节点显示文本的字段名
        label: "label"
      },
      // 文件导入参数
      upload: {
        // 是否显示弹出层（文件导入）
        open: false,
        // 弹出层标题（文件导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的文件数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/file/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileName: undefined,
        fileType: undefined,
        status: undefined,
        folderId: undefined
      },
      // 列信息
      columns: [
        {key: 0, label: `文件编号`, visible: true},
        {key: 1, label: `文件名称`, visible: true},
        {key: 2, label: `文件类型`, visible: true},
        {key: 3, label: `所属文件夹`, visible: true},
        {key: 4, label: `创建者`, visible: true},
        {key: 5, label: `状态`, visible: true},
        {key: 6, label: `创建时间`, visible: true}
      ],
      // 表单校验
      rules: {
        fileName: [
          {required: true, message: "文件名称不能为空", trigger: "blur"},
          {min: 2, max: 20, message: '文件名称长度必须介于 2 和 20 之间', trigger: 'blur'}
        ],
        createBy: [
          {required: true, message: "创建人不能为空", trigger: "blur"},
          {min: 1, max: 10, message: '创建人长度必须介于 1 和 10 之间', trigger: 'blur'}
        ],
        fileType: [
          {required: true, message: "文件类型不能为空", trigger: "change"},
          {
            validator: (rule, value, callback) => {
              const allowed = ['pdf', 'docx', 'xlsx', 'xls'];
              if (!value || !allowed.includes(value)) {
                callback(new Error('请选择合法的文件类型'));
              } else {
                callback();
              }
            },
            trigger: "change"
          }
        ],
        status: [
          {required: true, message: "请选择状态", trigger: "change"}
        ]
      }
    };
  },
  watch: {
    // 根据名称筛选文件夹树
    folderName(val) {
      this.$refs.tree.filter(val);
    }

  },
  created() {
    this.getList();
    this.getFileTree();
    this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });
  },
  methods: {
    parseTime,
    dict,
    /** 查询文件列表 */
    getList() {
      this.loading = true;
      listFile(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.fileList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 查询文件夹下拉树结构 */
    // getFileTree() {
    //   folderTreeSelect().then(response => {
    //     this.fileOptions = response.data;
    //     console.log(this.fileOptions)
    //   });
    // },

    getFileTree(deptId){
      folderTreeSelectByDeptId(deptId).then(response => {
        this.fileOptions = response.data;
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.folderId = data.id;
      this.selectedFolderId = data.id;
      this.handleQuery();
    },
    // 文件状态修改
    handleStatusChange(row) {
      const text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '"文件吗？').then(() => {
        return updateFileStatus(row.fileId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(() => {
        // 如果接口失败，回滚状态
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        fileId: null,
        folderId: null,
        fileName: null,
        fileType: null,
        fileSize: null,
        filePath: null,
        downloadCount: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fileId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.fileId != null) {
            updateFile(this.form).then(() => {
              this.$modal.msgSuccess('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            addFile(this.form).then(() => {
              this.$modal.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/folder/export', {
        ...this.queryParams
      }, `file_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      if (!this.selectedFolderId) {
        this.$message.warning('请先选择一个文件夹');
        return;
      }
      this.upload.title = "文件导入";
      this.upload.open = true;
      this.$refs.upload.clearFiles();
    },

    /** 提交文件表单 */
    async submitFileForm() {
      const fileList = this.$refs.upload.uploadFiles;
      if (fileList.length === 0) {
        this.$message.warning('请选择要上传的文件');
        return;
      }
      const file = fileList[0];
      const formData = new FormData();
      formData.append('file', file.raw);
      formData.append('updateSupport', this.upload.updateSupport);
      formData.append('folderId', this.selectedFolderId);
      this.upload.isUploading = true;
      try {
        const response = await addFile(formData);
        this.handleFileSuccess(response, file, fileList);
      } catch (error) {
        this.handleFileError(error, file, fileList);
      } finally {
        this.upload.isUploading = false;
      }
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/folder/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.$refs.upload.clearFiles();
      if (response.code === 200) {
        this.$message.success('文件导入成功');
        this.getList();
      } else {
        this.$message.error(response.msg || '文件导入失败');
      }
    },
    handleFileError(error, file, fileList) {
      this.$message.error('文件上传失败，请重试');
    },
    getFolderName(row, column, cellValue, index) {
      return row.folderName
    },
    indexMethod(index) {
      // 支持分页：当前页码 * 每页条数 + 当前行索引
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
    },

    // 新增文件夹
    handleAddFolder(data) {
      this.$prompt('请输入新文件夹名称', '新增文件夹', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /.+/,
        inputErrorMessage: '文件夹名称不能为空'
      }).then(({value}) => {
        const newFolder = {
          parentId: data.id,
          folderName: value
        };
        addFolder(newFolder).then(() => {
          this.$modal.msgSuccess("新增成功");
          this.getFileTree(); // 刷新树
        });
      }).catch(() => {
        this.$message.info("已取消新增");
      });
    },

    // 获取文件夹层级
    getLevel(folderId) {
      if (this.levels[folderId] !== undefined) {
        return this.levels[folderId];
      }
      getFolder(folderId).then(res => {
        const level = res.data?.level;
        this.$set(this.levels, folderId, level); // Vue.set 确保响应式更新
      }).catch(() => {
        this.$set(this.levels, folderId, -1); // 错误情况设为 -1
      });
    },

    // 修改文件夹名称
    handleUpdateFolderName(data) {
      this.$prompt('请输入新的文件夹名称', '修改文件夹', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: data.label,
        inputPattern: /.+/,
        inputErrorMessage: '文件夹名称不能为空'
      }).then(({value}) => {
        updateFolder({folderId: data.id, folderName: value}).then(() => {
          this.$modal.msgSuccess("修改成功");
          this.getFileTree(); // 刷新树
        });
      });
    },

    // 删除文件夹
    handleDeleteFolder(data) {
      this.$confirm(`是否确认删除文件夹 “${data.label}”？`, '提示', {
        type: 'warning'
      }).then(() => {
        checkFolderDeletable(data.id).then(res => {
          if (res.data.hasChildren || res.data.fileCount > 0) {
            const msg = res.data.hasChildren
              ? "该文件夹包含子文件夹，确定要删除吗？"
              : `该文件夹中有 ${res.data.fileCount || 0} 个文件，确定要删除吗？`;

            this.$confirm(msg, '二次确认', {
              type: 'warning'
            }).then(() => {
              delFolder(data.id).then(() => {
                this.$modal.msgSuccess("删除成功");
                this.getFileTree(); // 刷新树
                this.getList(); // 刷新文件列表
              });
            });
          } else {
            delFolder(data.id).then(() => {
              this.$modal.msgSuccess("删除成功");
              this.getFileTree(); // 刷新树
              this.getList(); // 刷新文件列表
            });
          }
        }).catch(() => {
          this.$message.info("已取消删除");
        });
      }).catch(() => {
        this.$message.info("操作已取消");
      });
    },
    handleDelete() {
      if (this.ids.length === 0) {
        this.$message.warning('您未选择文件，请选择要删除的文件');
        return;
      }
      delFile(this.ids).then(() => {
        this.$modal.msgSuccess("删除成功");
        this.getList(); // 刷新文件列表
      });
    },
    //  handleDownload(row) {
    //   // if (!row || !row.fileId) {
    //   //   this.$message.error('文件 ID 无效，无法下载')
    //   //   return
    //   // }
    //   try {
    //     // this.loading = true
    //     const response =  download(row.fileId)
    //     console.log(response)
    //     this.parseBlob(response, row.fileId)
    //     // if (response.status === 200) {
    //     //   this.parseBlob(response, '文件名.pdf')
    //     //   // const blob = new Blob([response.data], {type: 'application/octet-stream'})
    //     //   // saveAs(blob, row.fileName)
    //     //   this.$message.success('文件下载成功')
    //     // } else {
    //     //   this.$message.error('文件下载失败，响应状态码异常')
    //     // }
    //   } catch (error) {
    //     console.error('文件下载出错:', error)
    //     this.$message.error('文件下载失败，请重试')
    //   }
    // },
    async handleDownload(row) {
      try {
        // 等待Promise解析，获取响应对象
        const response = await download(row.fileId) // fileId替换为实际的文件标识
        console.log(response)
        // 使用若依封装的download方法（推荐，自动处理下载）
        // const fileName = response.headers['content-disposition']
        //   ? decodeURIComponent(response.headers['content-disposition'].split('filename=')[1])
        //   : 'defaultFileName'
        this.parseBlob(response, row.fileName)

        // 或者手动处理（了解原理）
        /* const blob = response.data
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = fileName
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url) */
      } catch (error) {
        this.$modal.msgError('下载失败：' + error.message)
      }
    },
    parseBlob(blob, fileName) {
      const url = window.URL.createObjectURL(new Blob([blob]))
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', fileName) // 设置下载文件名
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url) // 释放内存
    }
  }
};
</script>
