<template>
  <div class="upload-container">
    <el-button
      icon="el-icon-upload"
      size="mini"
      type="primary"
      @click="openImgUp"
    >
      图片上传
    </el-button>
    <PicLibrary
      v-if="pic_model_show"
      :img-height="-1"
      :limit="100"
      :is-check="true"
      :modal="model"
      :is-show="pic_model_show"
      @cancel="pic_model_show = false"
      @confirm="uploadSuccess"
    />
  </div>
</template>

<script>
  import { getEnToken } from "@/utils/accessToken";
  import { UploadDel, uploadToken } from "@/api/common";
  // import UploadQiniu from '@/component/common/UploadQiniu.vue'
  import PicLibrary from "@/component/common/PicLibrary.vue";
  import { apiUrl } from "@/config/settings";
  export default {
    name: "EditorSlideUpload",
    components: {
      // UploadQiniu,
      PicLibrary,
    },
    props: {
      color: {
        type: String,
        default: "#1890ff",
      },
      model:{
        type: Boolean,
        default: true,
      }
    },
    data() {
      return {
        img_url: apiUrl.QINIU_URL,
        QiniuData: {
          key: "", // 图片名字处理
          token: "", // 七牛云token
        },
        domain: "https://upload-z2.qiniup.com", // 七牛云的上传地址（华南区）
        dialogVisible: false,
        pic_model_show: false,
        imgArr: [],
        imgList: [],
        listObj: {},
        fileList: [],
      };
    },
    methods: {
      openImgUp() {
        this.imgArr = [];
        this.imgList = [];
        this.pic_model_show = true;
        // this.dialogVisible = true
      },
      uploadSuccess(fileList) {
        const imgArr = fileList.map((item) => {
          return {
            name: item.name,
            url: item.content,
          };
        });
        this.imgArr = this.imgArr.concat(imgArr);
        // this.imgList = this.imgArr
        this.$emit("successCBK", this.imgArr);
      },
      // uploadRemove (file, fileList) {
      //   this.imgArr = fileList.map(item => {
      //     return {
      //       name: item.name,
      //       url: item.content
      //     }
      //   })
      //   this.imgList = this.imgArr
      // },
      // confirmImg () {
      //   this.$emit('successCBK', this.imgArr)
      //   this.dialogVisible = false
      // },
      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;
        }
        this.$emit("successCBK", arr);
        this.listObj = {};
        this.fileList = [];
        this.dialogVisible = false;
      },
      handleSuccess(response, 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) {
            this.listObj[objKeyArr[i]].url = `${this.img_url}/${response.key}`;
            this.listObj[objKeyArr[i]].hasSuccess = true;
            return;
          }
        }
      },
      async handleRemove(file) {
        const data = await UploadDel({
          bucket: this.qiniu_key,
          key: file.response.key,
        });

        /* ==================== */
        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;
          }
        }
      },
      async beforeUpload(file) {
        this.QiniuData.key = `${getEnToken()}/${file.name}`;
        await this.getQiniuToken(this.QiniuData.key, file);
        // return new Promise((resolve, reject) => {
        //   const img = new Image()
        //   img.src = _URL.createObjectURL(file)
        //   img.onload = function () {
        //     _self.listObj[fileName] = { hasSuccess: false, uid: file.uid, width: this.width, height: this.height }
        //   }
        //   resolve(true)
        // })
      },
      // 请求后台拿七牛云token
      async getQiniuToken(key, file) {
        const fileName = file.uid;
        this.listObj[fileName] = {};
        const data = await uploadToken({
          bucket: this.qiniu_key,
          key: key,
        });

        this.QiniuData.token = data.data;
        /* ==================== */
        const _URL = window.URL || window.webkitURL;
        const img = new Image();
        img.src = _URL.createObjectURL(file);
        img.onload = () => {
          this.listObj[fileName] = {
            hasSuccess: false,
            uid: file.uid,
            width: this.width,
            height: this.height,
          };
        };
      },
    },
  };
</script>

<style lang="scss" scoped>
  .editor-slide-upload {
    margin-bottom: 20px;
    .el-upload--picture-card {
      width: 100%;
    }
  }
</style>
