<template>
  <div class="upload-file">
    <div v-if="uploadType == 'image'">
      <el-upload
        action="#"
        :list-type="listType"
        :auto-upload="true"
        :accept="accept"
        :before-upload="beforeUpload"
        :multiple="multiple"
        :file-list="fileList"
        :on-remove="handleRemove"
        ref="uploadMutiple"
      >
        <i slot="default" class="el-icon-plus"></i>
        <div slot="file" slot-scope="{ file }">
          <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
          <span class="el-upload-list__item-actions">
            <span
              class="el-upload-list__item-preview"
              @click="handlePictureCardPreview(file)"
            >
              <i class="el-icon-zoom-in"></i>
            </span>
            <span class="el-upload-list__item-delete" @click="handleRemove(file)">
              <i class="el-icon-delete"></i>
            </span>
          </span>
        </div>
        <div class="el-upload__tip" slot="tip">只能上传jpg/jpeg/png文件</div>
      </el-upload>
      <div id="preview" @paste="handlePaste" style="margin-top:15px;cursor:pointer">
        <span
          ><i class="el-icon-s-opportunity" style="color: #fb894c"></i>点击此处
          将图片按Ctrl+V 粘贴至此处</span
        >
      </div>
    </div>
    <div v-else-if="uploadType == 'all'">
      <el-upload
        action="#"
        :list-type="listType"
        :auto-upload="true"
        :accept="accept"
        :before-upload="beforeUpload"
        :multiple="multiple"
        :file-list="fileList"
        :on-remove="handleRemove"
      >
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <div class="el-upload__tip" slot="tip">
          只能上传.doc, .xls, .xlsx, .ppt, .pdf, .csv文件
        </div>
      </el-upload>
    </div>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
var COS = require("cos-js-sdk-v5");
var cos = new COS({
  SecretId: "AKIDE6IpMi8fJQRCg1iuWzFajjRs43kbbets",
  SecretKey: "tXzuwMfplTTK3c9GFUyETilasvQfePu9",
});
var i = 0;
const oneKB = 1024;

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
export default {
  name: "upload-file",
  components: {},
  props: {
    uploadType: {
      //上传类型  值为  image/video,同时目录名称也是这样
      type: String,
      default() {
        return "image";
      },
    },
    listType: {
      //上传类型  值为  image/video,同时目录名称也是这样
      type: String,
      default() {
        return "picture-card";
      },
    },

    multiple: {
      // true 可以批量上传  false 不可以
      type: Boolean,
      default() {
        return true;
      },
    },
    fileCount: {
      //最大上传数量
      type: Number,
      default() {
        return 10;
      },
    },
    checkFile: {
      //返回promise方法,判读文件是否上传过,进行上传拦截
      type: Function,
      default() {
        return Promise.resolve();
      },
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => [
        ".jpg",
        ".jpeg",
        ".png",
        // ".doc",
        // ".xls",
        // ".xlsx",
        // ".ppt",
        // ".txt",
        // ".pdf",
        // ".csv",
      ],
    },
    size: {
      type: Number,
      default() {
        if (this.sizeCheck) {
          if (this.uploadType == "image") {
            return 2048;
          } else {
            return 102400;
          }
        }
      },
    },
    sizeCheck: {
      type: Boolean,
      default() {
        return true;
      },
    },
    onOversize: {
      type: Function,
      default() {
        alert(`请选择${this.size}KB内的文件！`);
      },
    },
  },
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      fileList: [],
      accept: "",
    };
  },
  filters: {},
  computed: {},
  mounted() {
    this.fileType.forEach((el) => {
      this.accept += el;
      this.accept += ",";
    });
  },
  methods: {
    handlePaste(event) {
      const items = (event.clipboardData || window.clipboardData).items;
      let file = null;
      if (!items || items.length === 0) {
        this.$message.error("当前浏览器不支持本地");
        return;
      }
      // 搜索剪切板items
      for (let i = 0; i < items.length; i++) {
        if (items[i].type.indexOf("image") !== -1) {
          file = items[i].getAsFile();
          break;
        }
      }
      if (!file) {
        this.$message.error("粘贴内容非图片");
        return;
      }
      if (this.fileList.length >= this.limit) {
        this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`); // 图片数量超出
        return;
      }
      this.$refs.uploadMutiple.handleStart(file); // 将粘贴过来的图片加入预上传队列
      this.$refs.uploadMutiple.submit(); // 提交图片上传队列
    },

    handleRemove(file, fileList) {
      console.log(file, fileList);
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    handleRemove(file) {
      var index = this.fileList.findIndex((v) => v.url === file.url);
      if (index > -1) {
        this.fileList.splice(index, 1);
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;

      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },
    handleCancel() {
      closeAllVideoFun();
      this.previewVisible = false;
    },
    handleChange(info) {
      if (info.file.status === "uploading") {
        this.loading = true;
        return;
      }
      if (info.file.status === "done") {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, (imageUrl) => {
          this.imageUrl = imageUrl;
          this.loading = false;
        });
      }
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    beforeUpload(file) {
      console.log(file);
      if (!this.multiple && this.fileList.length == 1) {
        this.$message.error("请删除之后再上传");
        return;
      }
      this.cosUpload(file);
      return false;
    },
    clearAll() {
      this.fileList = [];
    },
    cosUpload(file) {
      var that = this;
      let date = new Date();
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      let d = date.getDate();
      d = d < 10 ? "0" + d : d;
      var timeElse = new Date().getTime();
      var arr = file.name.split(".");

      var str = "";
      for (let i = 0; i < arr.length; i++) {
        if (i == arr.length - 1) {
        } else {
          if (i == arr.length - 2) {
            str += arr[i];
          } else {
            str += arr[i] + ".";
          }
        }
      }
      // console.log(str + '-' + timeElse + '.' + arr[arr.length - 1])
      cos.putObject(
        {
          Bucket: "live-1301855440",
          /* 必须 */
          Region: "ap-chongqing",
          /* 存储桶所在地域，必须字段 */
          Key:
            "CaoPanShou" +
            "/" +
            y +
            MM +
            d +
            "/" +
            str +
            "-" +
            timeElse +
            "." +
            arr[arr.length - 1],
          /* 必须 */
          StorageClass: "STANDARD",
          Body: file, // 上传文件对象
          onProgress: function (progressData) {
            //进度条方法

            that.percent = progressData.percent * 100;
          },
          onTaskReady: function (tid) {
            // console.log('onTaskReady', tid);
          },
          onTaskStart: function (info) {
            //开始上传
            // console.log('onTaskStart', info);
          },
        },
        function (err, data) {
          if (err) {
            that.loadingElse = false;
            that.$message.error("上传失败!!!" + err);
            return;
          }
          // alert('成功')
          that.loadingElse = false;
          if (that.multiple) {
            that.fileList.push({
              uid: file.name,
              name: file.name,
              status: "done",
              url: "//" + data.Location,
            });
          } else {
            that.fileList = [
              {
                uid: file.name,
                name: file.name,
                status: "done",
                url: "//" + data.Location,
              },
            ];
          }

          console.log(that.fileList);
        }
      );
    },
  },
};
</script>
