<template>
  <a-modal v-model:open="isOpen" :title="title" :closable="false" :mask-closable="false" v-bind="$attrs">
    <a-upload-dragger v-model:fileList="selectList" :before-upload="beforeUpload" :name="multiple ? 'files' : 'file'"
      :placeholder="placeholder" style="width: 100%;">
      <p class="ant-upload-drag-icon">
        <i class="anticon anticon-inbox"></i>
      </p>
      <p class="ant-upload-text">点击或拖拽文件到此区域上传</p>
    </a-upload-dragger>

    <template #footer>
      <a-button @click="downloadTemplate" v-if="templateUrl">
        <DownloadOutlined />下载模板
      </a-button>
      <a-button @click="closeModal">
        <CloseCircleOutlined />关闭
      </a-button>
      <a-button type="primary" @click="customRequest" :loading="$store.loading">
        <CloudUploadOutlined />上传
      </a-button>
    </template>
  </a-modal>
</template>

<script>
import { message } from 'ant-design-vue';

export default {
  name: "PaasUploadModal",
  inheritAttrs: false, // 禁用自动继承，手动控制透传
  props: {
    placeholder: {
      type: String,
      default: "",
    },
    open: { type: Boolean, required: true },
    url: { type: String, required: true },
    params: { type: Object, default: () => ({}) },
    title: { type: String, default: "文件上传" },
    multiple: { type: Boolean, default: false },
    types: { type: String, default: "" },
    success: { type: Function, default: (data) => { } },
    templateUrl: { type: String, default: "" }
  },
  data() {
    return {
      loading: false,
      isOpen: this.open,
      fileList: [],
      selectList: [],
    };
  },
  watch: {
    open(val) {
      this.isOpen = val;
    }
  },
  methods: {
    // 使用全局上传方法
    customRequest() {
      const formData = new FormData();
      if (this.multiple) {
        this.fileList.forEach((file) => {
          formData.append("files", file);
        });
      } else {
        formData.append("file", this.fileList[0]);
      }
      Object.keys(this.params).forEach((key) => {
        formData.append(key, this.params[key]);
      });
      // 调用全局的 $upload 方法
      this.$upload(this.url, formData)
        .then((res) => {
          if (res.data.code == this.$success) {
            this.fileList = [];
            this.selectList = [];
            message.success(res.data.msg);
            this.success(res.data.data);
            this.closeModal();
          }
        })
        .catch(() => {
          message.error("文件上传失败！");
        });
    },
    // 选择文件之前
    beforeUpload(file) {
      this.fileList.push(file);
      return false; // 阻止自动上传
    },
    // 关闭弹窗
    closeModal() {
      this.selectList = [];
      this.fileList = [];
      this.isOpen = false; // 更新本地 isOpen
      this.$emit("update:open", false); // 通知父组件更新 open 状态
    },
    // 下载模板
    downloadTemplate() {
      if (this.templateUrl) {
        window.open(this.templateUrl, "_blank");
      }
    }
  }
};
</script>

<style scoped>
/* 样式自定义 */
</style>
