<template>
  <section>
    <el-col :span="8">
      <el-upload
        :disabled="display"
        class="upload-demo"
        ref="upload"
        :multiple="multiple"
        action="#"
        :accept="accept"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-change="handleChange"
        :file-list="fileList"
        :limit="limit"
        :on-exceed="handleExceed"
        :http-request="handleUpload"
        :auto-upload="false"
      >
        <el-button v-show="!display" slot="trigger" size="small" type="primary"
          >选取文件</el-button
        >
        <el-button
          v-show="!display"
          style="margin-left: 10px"
          size="small"
          type="success"
          @click="submitUpload"
          >开始上传</el-button
        >
      </el-upload>
    </el-col>
    <!-- 图片预览 -->
    <el-dialog
      title="图片预览"
      :append-to-body="true"
      :visible.sync="previewVisible"
      width="50%"
    >
      <img
        :src="previewPath"
        :alt="previewName"
        style="width: 100%; height: 100%"
      />
    </el-dialog>
  </section>
</template>

<script>
import { uploadUrl, downloadUrl, uploadFiles } from "@/api/file";
import { getFileExt } from "@/api/util";
export default {
  name: "upload-component-v2",
  props: {
    title: {
      type: String,
      default: "附件",
    },
    accept: {
      type: String,
      default: "",
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    limit: {
      type: Number,
      default: 5,
    },
    display: {
      type: Boolean,
      default: false,
    },
    fileObjList: {
      type: Array,
      default: () => [],
    },
    displayTitle: {
      type: Boolean,
      default: true,
    },
    displayStar: {
      type: Boolean,
      default: true,
    },
    value: {
      type: Array,
      default: () => [],
    },
  },
  watch: {
    fileList(newVal) {
      this.$emit("uploadSuccess", newVal);
    },
    fileObjList(newVal) {
      this.fileList = newVal;
    },
  },
  data() {
    return {
      fileList: [],
      uploadUrl: uploadUrl,
      previewPath: "",
      previewName: "",
      previewVisible: false,
      uploadFileList: [], //已经上传过的文件列表
    };
  },
  methods: {
    handleUpload(file) {
      function getBase64(file) {
        return new Promise((resolve, reject) => {
          const reader = new FileReader();
          reader.readAsDataURL(file);
          reader.onload = () => resolve(reader.result);
          reader.onerror = (error) => reject(error);
        });
      }

      return getBase64(file.file).then((res) => {
        //需要return才会显示上传成功状态，不加return不好使
        // 开始上传
        const formData = new FormData();
        formData.append("file", file.file);
        uploadFiles(formData).then(({ data }) => {
          if (data && data.code === "200") {
            data.data.forEach((item) => {
              let fileData = this.fileList.find(
                (file) => file.name === item.originFileName
              );
              fileData.fileName = item.originFileName;
              fileData.url = item.fileUrl;
              this.uploadFileList.push(fileData);
            });

            this.$emit("input", this.uploadFileList);
            this.$message.success("上传成功");
          } else {
            this.$message.error("上传失败");
          }
        });
      });
    },
    // 上传
    submitUpload() {
      this.$refs.upload.submit();
      // // 判断是否有文件
      // if (this.fileList.length === 0) {
      //   return this.$message.warning("请选取文件后再上传");
      // }
      // // 判断是否有重复文件
      // let arr1 = this.fileList.map((i) => i.name);
      // let arr2 = [...new Set(arr1)];
      // if (arr1.length !== arr2.length) {
      //   return this.$message.warning("请去掉重复文件后再上传");
      // }
      // // 开始上传
      // const formData = new FormData();
      // this.fileList.forEach((file) => {
      //   formData.append("file", file.raw);
      // });
      // uploadFiles(formData).then(({ data }) => {
      //   if (data && data.code === "200") {
      //     data.data.forEach((item) => {
      //       let fileData = this.fileList.find(
      //         (file) => file.name === item.originFileName
      //       );
      //       fileData.url = item.fileUrl;
      //     });
      //     this.$message.success("上传成功");
      //   } else {
      //     this.$message.error("上传失败");
      //   }
      // });
    },
    // 移除
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    // 预览
    handlePreview(file) {
      if (!file || !file.name || !file.url) {
        this.$message.error("没有可预览的文件！");
        return;
      }
      let ext = getFileExt(file.name);
      if (ext === "jpg" || ext === "jpeg" || ext === "png" || ext === "gif") {
        this.previewPath = downloadUrl + file.url;
        this.previewName = file.name;
        this.previewVisible = true;
      } else {
        // 弹出新页面显示下载文件
        window.open(downloadUrl + file.url, "_blank");
      }
    },
    // 改变上传内容
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    // 超限
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 ${this.limit} 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
  },
};
</script>

<style scoped></style>
