<template>
  <div>
    <el-upload ref="upload" :on-exceed='handleExceed' :class="{'disabled':disabled,'hiden':faNode[nodeKey].length>(item.attrs.limit-1||0)}" v-bind="$attrs" v-on="$listeners" action="fakeaction" :auto-upload="true" :http-request="uploadFunc" :file-list="faNode[nodeKey]" :on-preview="handlePreview" :on-remove="handleRemove" :disabled="disabled">
      <el-button size="small" v-if="$attrs['list-type']!='picture-card'&&!disabled" type="primary">{{item.buttonText||'上传文件'}}</el-button>
      <i class="el-icon-plus" v-if="$attrs['list-type']=='picture-card'" />
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>

</template>

<script>
let OSS = require("ali-oss");
import { getCredit } from "@/components/api/index.js";
let client;
export let progress; // 上传进度
export default {
  name: "mgUpload",
  components: {},
  props: {
    item: {
      type: Object,
      required: true,
    },
    faNode: {
      type: Object,
      required: true,
    },
    nodeKey: {
      type: String,
      required: true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      dataOss: {},
      addressOss: "",
    };
  },
  created() {
    this.faNode[this.nodeKey] = this.faNode[this.nodeKey] || [];
    this.getAliToken();
  },
  computed: {},
  methods: {
    getAliToken() {
      // client = new OSS({
      //   region: "oss-cn-hangzhou",
      //   accessKeyId: "LTAI4G3NeRF3iddKMNVcAcge",
      //   accessKeySecret: "c2MUhMNXbI3tJwdSLemTIyxti4cgRs",
      //   bucket: "magicargo-platform-test1",
      // });
      getCredit().then((res) => {
        client = new OSS(res.data);
      });
    },
    async upload(ObjName, fileUrl) {
      try {
        let result = await client.multipartUpload(`${ObjName}`, fileUrl, {
          progress: function (p) {
            progress = p * 100;
          },
        });
        return result;
      } catch (e) {
        console.log(e);
      }
    },
    getFileNameUUID() {
      function rx() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
      }
      return `${+new Date()}_${rx()}${rx()}`;
    },
    uploadFunc(param) {
      let objName = this.getFileNameUUID();
      let obj = param.file.name;
      let index = obj.lastIndexOf(".");
      obj = obj.substring(index, obj.length);
      objName = this.getFileNameUUID() + param.file.name;
      let tenantId = "";
      if (this.$store && this.$store.getters.useTenant) {
        let fileDir = this.item.fileDir || "platform/",
          platform = this.item.platform || "/form";
        tenantId =
          fileDir + "tenant-" + this.$store.getters.useTenant + "/" + platform;
      } else {
        let fileDir = this.item.fileDir || "platform/";
        tenantId = fileDir + "system/ueditor";
      }
      let url = `${tenantId}/${objName}`;
      this.upload(url, param.file).then((res) => {
        if (res && res.name) {
          console.log(res);
          const img = {
            uid: param.file.uid,
            name: param.file.name,
            size: param.file.size,
            fileName: res.name,
            url:
              "//magicargo-platform-test1.oss-cn-hangzhou.aliyuncs.com/" +
              res.name,
          };
          this.faNode[this.nodeKey].push(img);
          this.$forceUpdate();
        } else {
          console.log(param, "param");
          let uid = param.file.uid; // 关键作用代码，去除文件列表失败文件
          let idx = this.$refs.upload.uploadFiles.findIndex(
            (item) => item.uid === uid
          );
          this.$refs.upload.uploadFiles.splice(idx, 1);
          this.$message.error("上传失败");
        }
      });
    },
    handleRemove(file, fileList) {
      this.$set(this.faNode, this.nodeKey, fileList);
      this.$forceUpdate();
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 ${this.item.attrs.limit} 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
  },
};
</script>
<style lang="less" scoped>
/deep/ .disabled {
  .el-upload {
    display: block;
    margin-bottom: -5px;
  }
}
/deep/ .hiden {
  .el-upload {
    display: none;
    margin-bottom: -5px;
  }
}
</style>
