<template>
   
  <div>
    <el-upload
      :disabled="disabled"
      :action="ossUploadUrl"
      :data="useOss ? dataObj : null"
      list-type="picture-card"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :http-request="handleUploadSuccess"
      :on-preview="handlePreview"
      :limit="maxCount"
      :on-exceed="handleExceed"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script>
import { policy } from "@/api/oss";
import { getUploadSign, onOnlyFileUpload } from "@/utils/oss-file-upload";
export default {
  name: "multiUpload",
  props: {
    //图片属性数组
    value: Array,
    //最大上传图片数量
    maxCount: {
      type: Number,
      default: 5,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    bucket_name: {
      type: String,
      default: "mall",
    },
  },
  data() {
    return {
      dataObj: {
        policy: "",
        signature: "",
        key: "",
        KSSAccessKeyId: "",
        // dir: "",
        acl: "public-read",
        name: "",
      },
      dialogVisible: false,
      dialogImageUrl: null,
      useOss: true, //使用oss->true;使用MinIO->false
      // ossUploadUrl: "https://ks3-cn-beijing.ksyuncs.com/" + this.bucket_name,
      ossUploadUrl: `https://${this.bucket_name}.ks3-cn-beijing.ksyuncs.com`,
      minioUploadUrl: "http://localhost:8080/minio/upload",
    };
  },
  computed: {
    fileList() {
      let fileList = [];
      for (let i = 0; i < this.value.length; i++) {
        fileList.push({ url: this.value[i] });
      }
      return fileList;
    },
  },
  methods: {
    emitInput(fileList) {
      let value = [];
      for (let i = 0; i < fileList.length; i++) {
        value.push(fileList[i].url);
      }
      this.$emit("input", value);
    },
    handleRemove(file, fileList) {
      this.emitInput(fileList);
    },
    handlePreview(file) {
      this.dialogVisible = true;
      this.dialogImageUrl = file.url;
    },
    beforeUpload(file) {
      let _self = this;
      if (!this.useOss) {
        //不使用oss不需要获取策略
        return true;
      }
      return new Promise((resolve, reject) => {
        // console.log(file, "file");
        let key = new Date().getTime() + file.name;
        let obj = {
          filename: file.name,
          bucketName: this.bucket_name,
          postData: {
            filename: file.name,
            acl: "public-read",
            key: key
          },
        };
          getUploadSign(obj).then(response => {
            _self.dataObj.policy = response.data.policy;
            _self.dataObj.signature = response.data.signature;
            _self.dataObj.KSSAccessKeyId = response.data.kssAccessKeyId;
            _self.dataObj.key = key;
            _self.dataObj.name = key;
            _self.dataObj.acl = "public-read";
            var ks3Options = {
              KSSAccessKeyId: response.data.kssAccessKeyId,
              policy: response.data.policy,
              signature: response.data.signature,
              key: key,
              acl: "public-read", //此处需要与policy中的acl值保持一致，默认值：private。
              uploadDomain:
                "https://ks3-cn-beijing.ksyuncs.com/" + this.bucket_name, //北京region
              autoStart: true,
            };
            var pluploadOptions = {
              drop_element: document.body,
            };
            var tempUpload = new ks3FileUploader(ks3Options);
            resolve(true);
          })
          .catch((err) => {
            console.log(err);
            reject(false);
          });
      });
    },
    async handleUploadSuccess(info, file) {
      // let url = this.ossUploadUrl + "/" + this.dataObj.key;
      // if (!this.useOss) {
      //   //不使用oss直接获取图片路径
      //   url = res.data.url;
      // }
      // this.fileList.push({ name: file.name, url: url });
      // this.emitInput(this.fileList);
      try {
        const objInfo = {
          policy: info.data.policy,
          signature: info.data.signature,
          key: info.data.key,
          KSSAccessKeyId: info.data.kssAccessKeyId,
          acl: "public-read",
          name: info.data.key,
          file: info.file
        };
        console.log(objInfo, 'objInfo')
        const uploadUrl = await onOnlyFileUpload(this.ossUploadUrl, objInfo)
        this.fileList.push({ name: info.file.name, url: uploadUrl });
        this.emitInput(this.fileList);
      } catch (err) {
        console.log(err, 'err')
      }
    },
    handleExceed(files, fileList) {
      this.$message({
        message: "最多只能上传" + this.maxCount + "张图片",
        type: "warning",
        duration: 1000,
      });
    },
  },
};
</script>
<style></style>
