<style></style>
<style lang="scss" scoped></style>
<template>
  <div class="upload-file">
    <el-upload
      v-loading="percent != 0 && percent != 1 "
      :multiple="multiple"
      action="https://live-1301855440.cos.ap-chongqing.myqcloud.com/"
      :before-upload="beforeUpload"
      :accept="
        uploadType == 'script'
          ? '.doc,.txt,.pdf,.xlsx'
          : uploadType + '/' + (uploadType == 'image' ? 'jpeg,image/png' : 'mp4')
      "
      :file-list="fileList"
      :on-remove="removeFile"
    >
      <el-button size="small" type="primary" v-if="fileList.length == 0">点击上传</el-button>
      <div class="el-upload__tip" slot="tip" style="color: red">
        {{
          uploadType == "image"
            ? "请上传jpg,jpeg,png格式的图片,并且大小在" + size / 1024 + "m之内"
            : uploadType == "video"
            ? "请上传mp4格式,大小在" + size / 1024 + "m之内"
            : ""
        }}
      </div>
    </el-upload>
  </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";
      },
    },
    multiple: {
      // true 可以批量上传  false 不可以
      type: Boolean,
      default() {
        return true;
      },
    },
    fileCount: {
      //最大上传数量
      type: Number,
      default() {
        return 10;
      },
    },
    checkFile: {
      //返回promise方法,判读文件是否上传过,进行上传拦截
      type: Function,
      default() {
        return Promise.resolve();
      },
    },
    disabled: {
      type: Boolean,
      default() {
        return false;
      },
    },
    value: {
      required: true,
      default() {
        return "";
      },
    },
    size: {
      type: Number,
      default() {
        if (this.uploadType == "image") {
          return 2048;
        } else {
          return 512000;
        }
      },
    },
    sizeCheck: {
      type: Boolean,
      default() {
        return true;
      },
    },
    onOversize: {
      type: Function,
      default() {
        alert(`请选择${this.size}KB内的文件！`);
      },
    },
  },
  data() {
    return {
      fileList: [],
      loadingElse: false,
      imageUrl: "",
      percent: 0,
      previewVisible: false,
      previewImage: "",
      md5: "",
    };
  },
  filters: {},
  computed: {},
  mounted() {},
  watch: {
  },
  methods: {
    handleCancel() {
      this.previewVisible = false;
    },
    handleChange(file, fileList) {},
    removeFile(file) {
      // console.log(file)
      var index = this.fileList.findIndex((v) => v.signature === file.signature);
      this.fileList.splice(index, 1);
      // this.$emit("removeUpload", file);
      this.$emit("update:value", this.fileList);
    },
    showProgress(e) {
      console.log(e);
    },
    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) {
      this.percent = 0;
      this.loadingElse = true;
      const fileOvesize = file.size > this.size * oneKB;
      // console.log(fileOvesize)
      if (fileOvesize && this.sizeCheck) {
        this.onOversize();
        this.loadingElse = false;
        return;
      } else {
        this.checkFile(file)
          .then((res) => {
            this.cosUpload(file);
          })
          .catch(() => {
            this.loadingElse = false;
          });
        return new Promise(function (resolve, reject) {
          reject();
        });
      }
    },
    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:
            that.uploadType +
            "/" +
            y +
            "-" +
            MM +
            "-" +
            d +
            "/" +
            str +
            "-" +
            timeElse +
            "." +
            arr[arr.length - 1],
          /* 必须 */
          StorageClass: "STANDARD",
          Body: file, // 上传文件对象
          onProgress: function (progressData) {
            //进度条方法
            console.log(progressData);
            that.percent = progressData.percent;
          },
          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.fileList.length < that.fileCount) {
            that.fileList.push({
              uid: file.name,
              name: file.name,
              status: "done",
              url: "//" + data.Location,
              signature: JSON.parse(data.ETag),
            });

            // that.$emit('overUpload', that.fileList.map(item => {
            //                 return item.url
            //               }))
            // that.$emit("overUpload", that.fileList);

            if (that.multiple) {
              that.$emit("update:value", that.fileList);
            } else {
              that.$emit(
                "update:value",
                that.fileList.map((item) => {
                  return item.url;
                })[0]
              );
            }
          } else {
            that.$message.error("上传已达上限" + that.fileCount + "张");
          }
        }
      );
    },
  },
};
</script>
<style scoped></style>
