<template>
  <el-dialog
    class="upload-file-dialog"
    :visible.sync="modalIsShow"
    title="上传文件"
    top="10vh"
    width="710px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @opened="visibleChange"
  >
    <div class="file-upload-body">
      <upload-file-view
        input-width="270px"
        :format="format"
        :upload-url="uploadUrl"
        @valid-error="validError"
        @upload-success="uploadSuccess"
        ref="UploadFileView"
      ></upload-file-view>
      <el-button @click="toPreview" style="margin-left: 10px;">预览</el-button>
    </div>
    <div slot="footer" style="text-align: right">
      <el-button type="primary" @click="confirm">保存</el-button>
      <el-button type="danger" @click="cancel" plain>返回</el-button>
    </div>
  </el-dialog>
</template>

<script>
import UploadFileView from "./UploadFileView";
import { attachmentPreview } from "@/modules/login/api";

export default {
  name: "upload-file-dialog",
  components: { UploadFileView },
  props: {
    paperAttachment: {
      type: Object,
      default() {
        return {};
      }
    },
    format: {
      type: Array,
      default() {
        return ["xls", "xlsx"];
      }
    }
  },
  data() {
    return {
      modalIsShow: false,
      attachment: {},
      // import
      uploadUrl: "/api/print/basic/sys/saveAttachment"
    };
  },
  methods: {
    visibleChange() {
      this.$refs.UploadFileView.setAttachmentName(
        `${this.paperAttachment.filename || ""}`
      );
      this.attachment = { ...this.paperAttachment };
    },
    // upload-handler
    validError(errorData) {
      this.$message.error(errorData.message);
    },
    uploadSuccess(data) {
      this.$message.success("上传成功！");
      let infos = {
        attachmentId: data.id,
        filename: data.filename
      };
      this.attachment = Object.assign(this.attachment, infos);
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    confirm() {
      this.$emit("confirm", this.attachment);
      this.cancel();
    },
    async toPreview() {
      if (!this.attachment.attachmentId) {
        this.$message.error("请先上传附件!");
        return;
      }
      const data = await attachmentPreview(this.attachment.attachmentId);
      window.open(data.url);
    }
  }
};
</script>

<style lang="css" scoped>
.file-upload-body {
  min-height: 150px;
}
</style>
