<template>
   
  <div>
    <el-upload
      :disabled="disabled"
      :action="ossUploadUrl"
      :data="useOss ? dataObj : null"
      list-type="picture"
      :multiple="false"
      :show-file-list="showFileList"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :http-request="handleUploadSuccess"
      :on-preview="handlePreview"
    >
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">
        只能上传jpg/png文件，且不超过10MB
      </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="fileList[0].url" alt="" />
    </el-dialog>
  </div>
</template>
<script>
import { policy } from "@/api/oss";
import { getUploadSign, onOnlyFileUpload } from "@/utils/oss-file-upload";
export default {
  name: "singleUpload",
  props: {
    value: String,
    disabled: {
      type: Boolean,
      default: false,
    },
    bucket_name: {
      type: String,
      default: "mall",
    },
  },
  computed: {
    imageUrl() {
      return this.value;
    },
    imageName() {
      if (this.value != null && this.value !== "") {
        return this.value.substr(this.value.lastIndexOf("/") + 1);
      } else {
        return null;
      }
    },
    fileList() {
      return [
        {
          name: this.imageName,
          url: this.imageUrl,
        },
      ];
    },
    showFileList: {
      get: function () {
        return (
          this.value !== null && this.value !== "" && this.value !== undefined
        );
      },
      set: function (newValue) {},
    },
  },
  data() {
    return {
      dataObj: {
        policy: "",
        signature: "",
        key: "",
        KSSAccessKeyId: "",
        // dir: "",
        acl: "public-read",
        name: "",
      },
      dialogVisible: false,
      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",
    };
  },
  methods: {
    emitInput(val) {
      this.$emit("input", val);
    },
    handleRemove(file, fileList) {
      this.emitInput("");
    },
    handlePreview(file) {
      this.dialogVisible = true;
    },
    beforeUpload(file) {
      let _self = this;
      if (!this.useOss) {
        //不使用oss不需要获取策略
        return true;
      }
      console.log(file, "掉用beforeUpload");

      return new Promise((resolve, reject) => {
        let key = new Date().getTime() + file.name;
        // let key = `20150115/${file.name}`
        let obj = {
          filename: file.name,
          bucketName: this.bucket_name,
          postData: {
            filename: file.name,
            acl: "public-read",
            key: key,
            unknowValueField: [],
          },
        };

          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,
            };
            console.log(ks3Options, "ks3Options");
            var pluploadOptions = {
              drop_element: document.body,
            };
            var tempUpload = new ks3FileUploader(ks3Options);
            resolve(true);
          })
          .catch((err) => {
            console.log(err);
            reject(false);
          });
      });
    },
    async handleUploadSuccess(info) {
      console.log(info, 'info')
      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.showFileList = true;
      this.fileList.pop();
      this.fileList.push({ name: info.file.name, url: uploadUrl });
      this.emitInput(uploadUrl);
      } catch (err) {
        console.log(err, 'err')
      }

    },
  },
};
</script>
<style></style>
