<template>
  <!-- :before-upload="beforeUpload"     :headers="headers"    action="/api-web/uploadFile"-->
  <div>
    <el-upload
      :action="ossUploadUrl"
      :data="dataObj"
      :on-preview="handlePictureCardPreview"
      :show-file-list="false"
      multiple
      accept=".png, .jpg, .jpeg, .gif"
      :before-upload="beforeUpload"
      :on-success="successed"
      :on-remove="handleRemove"
      :on-exceed="handError"
      :limit="max"
    >
      <el-button :loading="uploading" type="primary">上传图片</el-button>
      <div v-if="max" class="el-upload__tip" slot="tip">
        最多只能上传{{ max }}张图片
      </div>
    </el-upload>
    <div class="img-container">
      <div class="list" v-if="uploaded.length > 0">
        <div v-for="(item, index) in uploaded" :key="item.url" class="item">
          <div class="ctrl-bar">
            <i class="el-icon-circle-close" @click="remove(index)"></i>
          </div>
          <el-image
            :src="item.url"
            :preview-src-list="uploaded.map(item => item.url)"
            class="img"
          >
          </el-image>
          <!-- <el-input
            v-model="item.name"
            placeholder="请输入图片名称"
            clearable
          /> -->
        </div>
      </div>
      <!-- <empty v-else /> -->
    </div>
  </div>
</template>

<script>
import copy from "copy-to-clipboard";
import { getToken } from "@/utils/auth";
import load from "@/utils/loading";
import { policy } from "@/api/appTenant";
export default {
  name: "uploadImageList",
  props: {
    buttonText: {
      type: String,
      default: "点击上传"
    },
    tips: {
      type: String,
      default: ""
    },
    uploaded: {
      type: Array,
      default: () => []
    },
    accept: {
      type: String,
      default: ""
    },
    max: {
      type: Number,
      default: 5
    },
    bucket_name: {
      type: String,
      default: "daya"
    }
  },
  watch: {
    value: {
      handler() {
        if (this.value) {
          this.filelist = [
            {
              name: this.value,
              url: this.value
            }
          ];
        } else {
          this.remove();
        }
      },
      immediate: true
    }
  },
  data() {
    return {
      filelist: [],
      headers: {
        Authorization: getToken()
      },
      // ossUploadUrl: "https://ks3-cn-beijing.ksyuncs.com/" + this.bucket_name,
      ossUploadUrl: `https://${this.bucket_name}.ks3-cn-beijing.ksyuncs.com`,
      dataObj: {
        policy: "",
        signature: "",
        key: "",
        KSSAccessKeyId: "",
        // dir: "",
        acl: "public-read",
        name: ""
        // bucket_name: props.bucket_name
      },
      uploading: false
    };
  },
  methods: {
    async beforeUpload(file) {
      console.log(file);
      this.uploading = true;
      try {
        let fileName = file.name.replaceAll(" ", "_");

        let key = new Date().getTime() + fileName;
        file.key = key;
        let obj = {
          filename: fileName,
          bucketName: this.bucket_name,
          postData: {
            filename: fileName,
            acl: "public-read",
            key: key,
            unknowValueField: []
          }
        };

        const res = await policy(obj);
        this.dataObj = {
          policy: res.data.policy,
          signature: res.data.signature,
          key: key,
          KSSAccessKeyId: res.data.kssAccessKeyId,
          // dir: "",
          acl: "public-read",
          name: fileName
          // bucket_name: props.bucket_name
        };
      } catch (e) {
        console.log(e);
      }
      return true;
    },
    successed(response, file, fileList) {
      this.uploading = false;
      let url = this.ossUploadUrl + "/" + file.raw.key;
      if (url) {
        this.uploaded.push({
          url,
          name: file.name.split(".").shift(),
          clientShow: "YES"
        });
      } else {
        this.$message.error(res.data?.message || res.msg || "上传失败");
      }
      console.log(response, file, fileList);
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    remove(index) {
      this.uploaded.splice(index, 1);
    },
    handError(files, fileList) {
      this.$message.error(
        `当前限制选择 ${this.max} 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    }
  }
};
</script>

<style lang="less" scoped>
.upload-text {
  display: inline-block;
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.dialog-footer {
  text-align: right;
}
.img-container {
  margin: 10px auto;
}
.item {
  width: 150px;
  margin-top: 10px;
  margin-right: 10px;
  display: inline-block;
  position: relative;
}
.img {
  width: 150px;
  height: 150px;
}
.ctrl-bar {
  background-color: rgba(0, 0, 0, 0.45);
  height: 30px;
  position: absolute;
  top: 0;
  width: 100%;
  z-index: 1;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 0 15px;
  i {
    color: #fff;
    cursor: pointer;
  }
}
</style>
