<template>
  <div>
    <div class="preview-container">
      <div class="preview-list">
        <div
          class="preview-item"
          v-for="(item, index) in tempFileUrl"
          :key="index"
        >
          <div class="preview-item-img" v-if="item.type == 'image'">
            <el-image :src="item.url" fit="cover" />
          </div>
          <div class="preview-item-img" v-if="item.type == 'file'">
            <i class="el-icon-document van-uploader__file-icon"></i>
            <span
              style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;width: 64px; font-size: 13px; padding-top: 5px;line-height: 1.3 "
              >{{ item.name }}</span
            >
          </div>
          <div class="preview-item-close">
            <i class="el-icon-close" @click="onDelete(item)"></i>
          </div>
        </div>
      </div>
    </div>
    <div class="upload_section">
      <el-upload
        :action="ossUploadUrl"
        :on-success="handleSuccess"
        :on-exceed="handleExceed"
        :before-upload="beforeUpload"
        :show-file-list="false"
        accept="image/*"
        :limit="5"
        :data="dataObj"
      >
        <el-button
          size="mini"
          :loading="uploadLoading"
          icon="el-icon-picture"
          round
          >上传图片</el-button
        >
      </el-upload>

      <el-upload
        :action="ossUploadUrl"
        style="margin-left: 8px"
        :on-success="handleSuccess"
        :on-exceed="handleExceedFile"
        :before-upload="beforeUploadFile"
        :show-file-list="false"
        :limit="3"
        :data="dataObj"
        accept="image/*, *.xlsx, *.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document, *.txt, *.pdf"
      >
        <el-button
          size="mini"
          :loading="uploadFileLoading"
          icon="el-icon-document"
          round
          >上传附件</el-button
        >
      </el-upload>
    </div>
  </div>
</template>

<script>
import { policy } from "@/api/user";
export default {
  name: "FileUpload",
  props: ["fileUrl"],
  data() {
    return {
      tempFileUrl: this.fileUrl || [],
      type: "image",
      uploadLoading: false,
      uploadFileLoading: false,
      ossUploadUrl: "https://ks3-cn-beijing.ksyuncs.com/daya",
      dataObj: {
        policy: "",
        signature: "",
        key: "",
        KSSAccessKeyId: "",
        acl: "public-read",
        name: ""
      }
    };
  },
  watch: {
    fileUrl(val) {
      console.log(val);
      this.tempFileUrl = val;
    }
  },
  methods: {
    onClear() {
      this.tempFileUrl = [];
      this.$emit("update:fileUrl", []);
    },
    onDelete(item) {
      const index = this.tempFileUrl.indexOf(item);
      this.tempFileUrl.splice(index, 1);
      this.$emit("update:fileUrl", this.tempFileUrl);
    },
    async beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 5MB!");
      }
      this.uploadLoading = true;
      this.type = "image";
      try {
        let filename = file.name.replaceAll(" ", "_");
        let key = new Date().getTime() + filename;
        let obj = {
          filename,
          bucketName: "daya",
          postData: {
            filename,
            acl: "public-read",
            key,
            unknowValueField: []
          }
        };

        const res = await policy(obj);
        this.dataObj = {
          policy: res.data.policy,
          signature: res.data.signature,
          key,
          KSSAccessKeyId: res.data.kssAccessKeyId,
          acl: "public-read",
          name: filename
        };
        console.log(res, "policy", this.dataObj);

        return isLt2M;
      } catch {
        return false;
      }
    },
    async beforeUploadFile(file) {
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isLt2M) {
        this.$message.error("上传附件大小不能超过 5MB!");
      }
      this.uploadFileLoading = true;
      this.type = "file";

      try {
        let filename = file.name.replaceAll(" ", "_");
        let key = new Date().getTime();
        let obj = {
          filename,
          bucketName: "daya",
          postData: {
            filename,
            acl: "public-read",
            key,
            unknowValueField: []
          }
        };

        const res = await policy(obj);
        this.dataObj = {
          policy: res.data.policy,
          signature: res.data.signature,
          key,
          KSSAccessKeyId: res.data.kssAccessKeyId,
          acl: "public-read",
          name: filename
        };

        return isLt2M;
      } catch {
        return false;
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(`最多允许上传 5 张图片。`);
    },
    handleExceedFile(files, fileList) {
      this.$message.warning(`最多允许上传 3 个文件。`);
    },
    handleSuccess(response, file, fileList) {
      // console.log(response, file, fileList);
      this.uploadLoading = false;
      this.uploadFileLoading = false;

      let url = this.ossUploadUrl + "/" + this.dataObj.key;
      this.tempFileUrl.push({
        uid: file.uid,
        name: file.name,
        url,
        type: this.type,
        file: {
          name: file.name
        }
      });
      this.$emit("update:fileList", this.tempFileUrl);
    }
  }
};
</script>

<style lang="scss" scoped>
.upload_section {
  display: flex;
}

.preview-container::-webkit-scrollbar {
  display: none;
}
.preview-container {
  width: 100%;
  overflow: hidden;
  overflow-y: hidden;
  overflow-x: auto;
}
.preview-list {
  display: flex;
}
.preview-item {
  position: relative;
  margin: 0 8px 8px 0;
  border-radius: 4px;
  overflow: hidden;
}
.preview-item,
.preview-item-img {
  background: #f7f8fa;
  width: 64px;
  height: 64px;
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: center;
}

.preview-item-close {
  position: absolute;
  top: 0;
  right: 0;
  width: 14px;
  height: 14px;
  background-color: rgba(0, 0, 0, 0.7);
  border-radius: 0 0 0 12px;

  .el-icon-close {
    position: absolute;
    top: -2px;
    right: -2px;
    color: #fff;
    font-size: 16px;
    -webkit-transform: scale(0.5);
    transform: scale(0.5);
    cursor: pointer;
  }
}
</style>
