<template>
  <div class="uploadWrapper">
    <div v-if="!forbid">
      <el-upload
        ref="upload"
        class="upload"
        multiple
        :file-list="fileList"
        :action="uploadFileUrl"
        :headers="headers"
        :on-change="handleChange"
        :on-remove="handleRemove"
        :before-remove="beforeRemove"
        :on-success="handleUploadSuccess"
        :on-preview="handlePreview"
      >
        <el-button size="small" type="primary" :disabled="forbid"
          >点击上传</el-button
        >
        <template v-slot:file="{ file }">
          <div class="public-flex-between">
            <div @click="handlePreview(file)" class="name">{{ file.name }}</div>

            <!-- 自定义删除按钮，通过条件判断是否显示 -->
            <el-button
              v-if="!forbid"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleRemove(file)"
            ></el-button>
          </div>
        </template>
      </el-upload>
    </div>
    <div v-else>
      <ul class="fileBox" v-if="fileList.length > 0">
        <li
          class="fileItemLi"
          v-for="(item, index) in fileList"
          :key="index"
          @click="handlePreview(item)"
        >
          {{ item.newUploadName }}
        </li>
      </ul>
      <ul v-else>
        (空)
      </ul>
    </div>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import {
  listFileBusinessId,
  listFileById,
  delFile,
  downloadFileById,
} from "@/api/system/file";
export default {
  props: {
    // 新增：接收外部传入的“是否为详情模式”
    isDetail: {
      type: Boolean,
      default: false
    },
    // 原有 props（如果有）...
  },
  data() {
    return {
      forbid: false,
      fileList: [],
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
    };
  },
  mounted() {
    // 初始化时，若为详情模式 → 直接隐藏上传按钮
    if (this.isDetail) {
      this.forbid = true;
    }
    if (this.id) {
      this.getListFileBusinessId(this.id);
    }
  },
  methods: {
    // 根据附件业务ID()获取附件详情信息列表
    getListFileBusinessId(id, uploadType) {
      if (id) {
        listFileBusinessId(id, uploadType).then((response) => {
          if (response.data.length > 0) {
            let list = response.data;
            for (let i in list) {
              list[i].name = list[i].newUploadName;
            }
            this.fileList = list;
            this.$emit("getFileList", this.fileList);
          }
        });
      }
    },
    // 根据附件业务ID()获取附件详情信息列表
    getListFileById(id, uploadType) {
      if (id) {
        listFileById(id, uploadType).then((response) => {
          if (response.data.length > 0) {
            let list = response.data;
            for (let i in list) {
              list[i].name = list[i].newUploadName;
            }
            this.fileList = list;
            this.$emit("getFileList", this.fileList);
          }
        });
      }
    },
    handleButton() {
      this.forbid = true;
    },
    handleForbid() {
      this.forbid = false;
    },
    handleChange(file, fileList) {
      //   console.log("----", file, fileList);
    },
    handleRemove(file, fileList) {
      let that = this;
      that.$modal
        .confirm('确定移除"' + file.name + '"？')
        .then(function () {
          that.fileList = fileList;
          if (file.id) {
            const id = file.id;
            delFile(id).then((response) => {
              // 给父组件传值
              that.$emit("getFileList", that.fileList);
            });
          }
        })
        .catch(() => {
          console.log("取消");
          return false;
        });
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleUploadSuccess(res, file, fileList) {
      let that = this;
      if (fileList.every((item) => item.status == "success")) {
        fileList.map((item) => {
          if (item.response) {
            item.response.file.name = item.response.file.newUploadName;
            if (!this.fileList) {
              this.fileList = [];
            }
            this.fileList.push(item.response.file);
            that.$emit("getFileList", this.fileList);
          }
        });
      }
    },
    //点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
      window.open(file.uploadPath, '_blank');
      /*downloadFileById(file.id).then((response) => {
        const url = window.URL.createObjectURL(new Blob([response])); // 'https://dgt.dgtis.com/oneportal/fileServer/vendor//contractFile/c6503f4c14354692b207553df8f02480.pdf';
        window.open(url, '_blank');
        // const link = document.createElement("a");
        // link.href = url;
        // link.setAttribute("download", file.newUploadName);
        // document.body.appendChild(link);
        // link.click();
      });*/
    },
  },
};
</script>
<style lang="scss">
.uploadWrapper ::v-deep .el-upload-list__item {
  transition: none !important;
}
.name {
  cursor: pointer;
}
.fileItemLi {
  cursor: pointer;
  color: #1890ff;
}
.fileItemLi:hover {
  background: #f5f7fa;
  border-radius: 5px;
}
.fileBox {
}
</style>
