<template>
  <div class="upload-container">
    <el-button
      :disabled="disabled"
      icon="el-icon-upload"
      size="mini"
      :style="{ background: color, borderColor: color }"
      @click="dialogVisible = true"
      type="primary"
      >上传图片
    </el-button>
    <el-dialog append-to-body :visible.sync="dialogVisible">
      <el-upload
        :disabled="disabled"
        class="editor-slide-upload"
        :action="ossUploadUrl"
        :data="dataObj"
        :multiple="false"
        :file-list="fileList"
        :show-file-list="true"
        list-type="picture-card"
        :on-remove="handleRemove"
        :http-request="handleSuccess"
        :before-upload="beforeUpload"
      >
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </el-dialog>
  </div>
</template>

<script>
import { policy } from "@/api/oss";
import { getUploadSign, onOnlyFileUpload } from "@/utils/oss-file-upload";
export default {
  name: "editorSlideUpload",
  props: {
    color: {
      type: String,
      default: "#1890ff",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    bucket_name: {
      type: String,
      default: "mall",
    },
  },
  data() {
    return {
      dialogVisible: false,
      listObj: {},
      fileList: [],
      dataObj: {
        policy: "",
        signature: "",
        key: "",
        KSSAccessKeyId: "",
        // dir: "",
        acl: "public-read",
        name: "",
      },
      // ossUploadUrl: "https://ks3-cn-beijing.ksyuncs.com/mall",
      ossUploadUrl: `https://mall.ks3-cn-beijing.ksyuncs.com`,
    };
  },
  methods: {
    checkAllSuccess() {
      return Object.keys(this.listObj).every(
        (item) => this.listObj[item].hasSuccess
      );
    },
    handleSubmit() {
      const arr = Object.keys(this.listObj).map((v) => this.listObj[v]);
      if (!this.checkAllSuccess()) {
        this.$message(
          "请等待所有图片上传成功 或 出现了网络问题，请刷新页面重新上传！"
        );
        return;
      }
      console.log(arr);
      this.$emit("successCBK", arr);
      this.listObj = {};
      this.fileList = [];
      this.dialogVisible = false;
    },
    async handleSuccess(info) {
      // const uid = file.uid;

      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)
        // console.log(uploadUrl, 'uploadUrl')
        this.listObj[info.file.uid].url = uploadUrl;
        this.listObj[info.file.uid].hasSuccess = true;
      } catch (err) {
        console.log(err, 'err')
      }
      // for (let i = 0, len = objKeyArr.length; i < len; i++) {
      //   if (this.listObj[objKeyArr[i]].uid === uid) {
      //     this.listObj[objKeyArr[i]].url =
      //       this.ossUploadUrl + "/" + this.listObj[objKeyArr[i]].key;
      //     this.listObj[objKeyArr[i]].hasSuccess = true;
      //     return;
      //   }
      // }
    },
    handleRemove(file) {
      const uid = file.uid;
      const objKeyArr = Object.keys(this.listObj);
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          delete this.listObj[objKeyArr[i]];
          return;
        }
      }
    },
    beforeUpload(file) {
      console.log(file, "试试批量上传");
      const _self = this;
      const fileName = file.uid;
      this.listObj[fileName] = {};
      return new Promise((resolve, reject) => {
        let key = new Date().getTime() + file.name;
        let obj = {
          filename: key,
          bucketName: this.bucket_name,
          postData: {
            filename: key,
            acl: "public-read",
            key: key
          },
        };
        // policy(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 = file.name;
        //     _self.dataObj.acl = "public-read";
        //     _self.listObj[fileName] = {
        //       hasSuccess: false,
        //       uid: file.uid,
        //       width: this.width,
        //       height: this.height,
        //       name: file.name,
        //       key: key,
        //     };

        //     resolve(true);
        //   })
        //   .catch((err) => {
        //     console.log(err);
        //     reject(false);
        //   });
        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";
            _self.listObj[fileName] = {
              hasSuccess: false,
              uid: file.uid,
              width: this.width,
              height: this.height,
              name: key,
              key: key,
            };
            resolve(true);
          })
          .catch((err) => {
            console.log(err);
            reject(false);
          });
      });
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.upload-container .editor-slide-upload {
  margin-bottom: 20px;
}
</style>
