/**version-1.0*/
let tmixins;
import axios from "axios";
import SparkMD5 from "spark-md5";
import settingConfig from "@/settings.js";
import ObsClient from "esdk-obs-browserjs/src/obs";

let imFun = {
  axios,
  SparkMD5,
};

tmixins = {
  props: {
    auto: {
      type: Boolean,
      default: true,
    },
    url: {
      type: String,
      default: "/upload",
    },
    name: {
      type: String,
      default: "file",
    },
    limit: {
      type: Number,
      default: () => 100000,
    },
    size: {
      type: Number,
      default: 200,
    },
    accept: {
      type: String,
      default: "file",
    },
    chunkSize: {
      type: Number,
      default: 5, //5MB
    },
    confirmUpload: {
      type: Function,
    },
    pickPrivateProfile: {
      type: Boolean,
      default: true,
    },
    multi: {
      type: [String, Boolean],
      default: true,
    },
    uploadingLimit: {
      type: Number,
      default: 5, //5MB
    },
  },
  data() {
    return {
      show: false,
      loading: false,
      dialogVisible: false,
      dialogImageUrl: "",
      action: "",
      headers: {},
      fileList: [],
      picture: "picture",
      allImgNum: 0,
      imgNum: 0,
      imgSuccessNum: 0,
      imgErrorNum: 0,
      typeList: null,
      title: this.$t2("上传", "components.VabUpload.title"),
      dialogFormVisible: false,
      data: {},
      fileViewDialogVisible: false,
      fileViewInfo: {},
      total: 0,
      video: null,
      btn: false,
      filePartMap: {},
      uploading: false,
      hasReadyFile: false,
      showLocalUploadBtn: false,
      showPrivateUploadBtn: false,
      showPrivateProfileDialog: false,
      pasteList: [],
      pasteAreaStatus: false,
      option: {},
      editFileIndex: -1,
      showFileNameDialog: false,
      editFileName: null,
      editFileSuffix: null,
      beforeUploadFlag: false,
      uploadUrl: null,

      access_key_id: "HPUAQ1TAFXWGOKSNKCGW", // 你的ak
      secret_access_key: "Ns1nwPwikK67Acbhj3wlfUambjbdroqpk0TFv7qg", // 你的sk
      server: "https://obs.cn-south-1.myhuaweicloud.com", // 你的endPoint  记得加入https://
      Bucket: "gztw-file01", // 你的桶名
    };
  },
  beforeDestroy() {
    this.removePasteEvent();
  },
  filters: {
    btnText(btn) {
      return btn
        ? this.$t2("继续", "components.VabUpload.continue")
        : this.$t2("暂停", "components.VabUpload.pause");
    },
    totalText(total) {
      return total > 100 ? 100 : total;
    },
  },
  computed: {
    percentage() {
      if (this.allImgNum == 0) return 0;
      return ((this.imgNum / this.allImgNum, 2) * 100).toFixed(0);
    },
    fileMaxSize() {
      return this.formatFileSize(this.size * 1024 * 1024);
    },
    errorQuantity() {
      return this.fileList.filter((file) => file.status == "fail").length;
    },
    totalQuantity() {
      return this.fileList.length;
    },
    successQuantity() {
      return this.fileList.filter((file) => file.status == "success").length;
    },
    isMulti: function () {
      let isMulti = true;
      if (this.multi === "false" || this.multi === false || this.limit === 1) {
        isMulti = false;
      }
      return isMulti;
    },
  },
  methods: {
    updateUploadingStatus() {
      var target = this.$refs.upload;
      let uploading, hasReadyFile;
      if (target) {
        var fileList = target.uploadFiles;
        let n = fileList.find((item) => {
          // return item.percentage != 100;
          return item.status == "uploading" || item.status == "preUpload";
        });
        uploading = n == null ? false : true;

        let readyFiles = fileList.filter((file) => file.status == "ready");
        hasReadyFile = readyFiles.length > 0;
      } else {
        uploading = false;
        hasReadyFile = false;
      }

      this.uploading = uploading;
      this.hasReadyFile = hasReadyFile;
      this.checkPreUploadList();
      return uploading;
    },
    submitUpload() {
      let successDone = () => {
        this.$refs.upload.submit();
      };
      var files = this.$refs.upload.uploadFiles;
      let readyFiles = files.filter((file) => file.status == "ready");
      if (this.confirmUpload) {
        if (readyFiles.length) {
          this.confirmUpload({
            files: files,
            done: successDone,
          });
        }
      } else {
        successDone();
      }
    },
    handleProgress(event, file, fileList) {
      // this.loading = true
      // this.show = true
    },
    handleChange(file, fileList) {
      let maxSize = this.size * 1024 * 1024;
      if (file.size > maxSize) {
        fileList.map((item, index) => {
          if (item === file) {
            fileList.splice(index, 1);
          }
        });
        this.fileList = fileList;
        let errorText =
          "文件[" + file.name + "]大小超出限制" + this.fileMaxSize;
        this.$message({
          message: this.$t2(errorText, "components.VabUpload.warnMsg1", {
            fileName: file.name,
            fileMaxSize: this.fileMaxSize,
          }),
          type: "error",
          duration: 3 * 1000,
        });
        file.raw.status = "fail";
        return false;
      } else {
        this.fileList = fileList;
        this.allImgNum = fileList.length;
      }
      this.updateUploadingStatus();
    },
    handleSuccess(response, file, fileList) {
      if (file.percentage == 100) {
        this.imgNum = this.imgNum + 1;
        this.imgSuccessNum = this.imgSuccessNum + 1;
      }
      if (fileList.length === this.imgNum) {
        this.fileList = fileList;
      }

      setTimeout(() => {
        this.loading = false;
        this.show = false;
      }, 1000);
      this.updateUploadingStatus();
    },
    handleError(err, file, fileList) {
      this.imgNum = this.imgNum + 1;
      this.imgErrorNum = this.imgErrorNum + 1;
      setTimeout(() => {
        this.loading = false;
        this.show = false;
      }, 1000);
      this.updateUploadingStatus();
    },
    handleRemove(file, fileList) {
      this.imgNum = this.imgNum - 1;
      this.allNum = this.allNum - 1;
      this.updateUploadingStatus();
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleExceed(files, fileList) {
      let errorMsg = `当前限制选择 ${this.limit} 个文件，本次选择了
             ${files.length}
             个文件`;
      this.$message({
        message: this.$t2(errorMsg, "components.VabUpload.warnMsg2", {
          limit: this.limit,
          size: files.length,
        }),
        type: "error",
        duration: 5 * 1000,
      });
    },
    handleShow(option) {
      this.getFileServerInfo(option,()=>{
        this.title = this.$t2("上传", "components.VabUpload.title");
        // this.data = data;
        this.option = option;
        this.clearFileInfo();
        this.initPickUploadMode();
        this.pasteAreaStatus = false;
        this.dialogFormVisible = true;

        this.removePasteEvent();
        this.addPasteEvent();
      })

    },
    addPasteEvent() {
      document.addEventListener("click", this.blurPasteEvent);
      document.addEventListener("paste", this.pasteEvent);
    },
    removePasteEvent() {
      document.removeEventListener("click", this.blurPasteEvent);
      document.removeEventListener("paste", this.pasteEvent);
    },
    blurPasteEvent() {
      this.pasteAreaStatus = false;
    },
    handleClose() {
      let target = this.$refs.upload;
      (target.uploadFiles || []).forEach((uploadFile) => {
        if (uploadFile.status == "uploading" || uploadFile.status == "ready") {
          uploadFile.raw.abort &&
            uploadFile.raw.abort(
              this.$t2("取消上传", "components.VabUpload.cancelUpload")
            );
        }
      });
      this.picture = "picture";
      this.clearFileInfo();
      this.dialogFormVisible = false;
    },
    clearFileInfo() {
      this.fileList = [];
      this.allImgNum = 0;
      this.imgNum = 0;
      this.imgSuccessNum = 0;
      this.imgErrorNum = 0;
    },
    initUploadUrl() {
      let mineUploadUrl = window.BASE_FILEURL;
      return this.$http({
        url: mineUploadUrl,
        method: "post",
        data: {
          isAuth: false,
        },
        success: (res) => {
          this.uploadUrl = res.objx;
        },
      });
    },
    handleBeforeUpload(file, checkFile, callback) {
      /*if (checkFile !== false) {
        let target = this.$refs.upload;
        let nFile = target.getFile(file);
        if (!nFile) {
          return false;
        }
      }
      let mineUploadUrl = window.BASE_FILEURL;
      return await this.$http({
        url: mineUploadUrl,
        method: 'post',
        data: {
          isAuth: false
        },
        success: res => {
          this.uploadUrl = res.objx;
          callback && callback()
        }
      });*/
      callback && callback();
    },
    formatFileSize(fileSize) {
      return formatFileSize(fileSize);
    },
    //自定义上传
    async uploadSectionFile(param, isCustom, uploadConfig) {
      if (!this.uploadUrl) {
        await this.initUploadUrl();
      }
      let that = this;
      var fileObj = param.file;

      let source;

      var form = new FormData();
      // 文件对象
      form.append("file", fileObj);

      let target = that.$refs.upload;
      let file = target ? target.getFile(fileObj) : null;
      if (file) {
        file.status = "uploading";
      }

      let isLoading = uploadConfig?.isLoading === true;
      var uploadUrl = this.uploadUrl;
      if (uploadUrl) {
        var abort;
        let config = {
          isLoading: isLoading,
          headers: {
            "Content-Type": "multipart/form-data",
          },
          cancelToken: new imFun.axios.CancelToken(function executor(c) {
            if (!isCustom) {
              abort = c;
              if (file) file.abort = c;
            }
          }),
          onUploadProgress: (progressEvent) => {
            if (isCustom || file) {
              // progressEvent.loaded:已上传文件大小
              // progressEvent.total:被上传文件的总大小
              progressEvent.percent = Math.floor(
                (progressEvent.loaded * 100) / progressEvent.total
              );
              if (!isCustom) {
                param.onProgress(progressEvent, fileObj);
              }
              uploadConfig &&
                uploadConfig.onProgress &&
                uploadConfig.onProgress(progressEvent, fileObj);
            }
          },
          failMsg: false,
        }; //添加请求头

        let req = this.$http
          .post(uploadUrl, form, config)
          .then((res1) => {
            uploadConfig &&
              uploadConfig.callback &&
              uploadConfig.callback(res1, fileObj);
            if (!isCustom) {
              if (res1.type == "success") {
                param.onSuccess(res1, fileObj);
              } else {
                // param.onError(new Error(res1.content || '上传异常'));
                this.handleFileError(
                  new Error(
                    res1.content ||
                      this.$t2(
                        "上传异常",
                        "components.VabUpload.uploadException"
                      )
                  ),
                  fileObj
                );
              }
            }
          })
          .catch((error, a, b, c) => {
            // let {err} = error;
            try {
              // param.onError(err, fileObj);
              if (!isCustom) {
                this.handleFileError(error, fileObj);
              }
              uploadConfig &&
                uploadConfig.error &&
                uploadConfig.error(error, fileObj);
            } catch (tt) {}
          });
        req.abort = () => {
          abort(this.$t2("取消上传", "components.VabUpload.cancelUpload"));
        };
        //return req;
      }
    },
    singerUpload(uploadConfig) {
      let onUploadProgress = uploadConfig.onUploadProgress;
      let success = uploadConfig.success;
      let file = uploadConfig.file;
      this.handleBeforeUpload(file, false, () => {
        this.uploadSectionFile(
          {
            file: file,
          },
          true,
          uploadConfig
        );
      });
    },
    //begin
    fileParse(file, type = "base64", callback) {
      /*return new Promise(resolve => {

      });*/
      let fileRead = new FileReader();
      if (type === "base64") {
        fileRead.readAsDataURL(file);
      } else if (type === "buffer") {
        fileRead.readAsArrayBuffer(file);
      }
      fileRead.onload = (ev) => {
        callback(ev.target.result);
        // resolve(ev.target.result);
      };
    },
    changeFile(param) {
      if (!param.file || param.file.status == "fail") return;

      let target = this.$refs.upload;
      if (!target) return;
      let fileObj = target.getFile(param.file);
      fileObj.status = "preUpload";
      this.checkPreUploadList();
    },
    getFileServerInfoData(callback){
        this.$http({
          url: USER_PREFIX + "/logic_param/getFileServerInfo",
          method: "post",
          data: {paramCode: "obs"},
          failMsg: false,
          errorMsg: false,
          modal: false,
          success: (res) => {
            if(res.objx){
              callback && callback(res.objx);
            }else{
              callback && callback();
            }
          },
          error: (err) => {
            callback && callback();
          }
        })
    },
    getFileServerInfo(option,callback){
      if(option.obsConfig){
        let fileServerInfo = option.obsConfig;
        this.initObsClient(fileServerInfo);
        callback && callback();
      }else{
        this.getFileServerInfoData((res)=>{
          if(res?.obsConfig){
            let obsConfig = res.obsConfig;
            let access_key_id = obsConfig.access_key_id;
            if(access_key_id && access_key_id.indexOf("abc")===3){
              access_key_id = access_key_id.replace("abc","");
            }else{
              this.$message.error(this.$t1("上传服务信息[access_key_id]数据异常"))
              return
            }
            let secret_access_key = obsConfig.secret_access_key;
            if(secret_access_key && secret_access_key.indexOf("abc")===3){
              secret_access_key = secret_access_key.replace("abc","");
            }else{
              this.$message.error(this.$t1("上传服务信息[secret_access_key]数据异常"))
              return
            }
            this.initObsClient({
              ...obsConfig,
              access_key_id,
              secret_access_key
            });
            callback && callback();
          }else{
            this.$message.error(this.$t1("上传服务信息未维护"))
          }
        })
      }
    },
    //obs begin
    initObsClient(obsConfig) {
      this.obsConfig = obsConfig;
      this.obsClient = new ObsClient({
        access_key_id: obsConfig.access_key_id,
        secret_access_key: obsConfig.secret_access_key,
        server: obsConfig.server,
        // obsClient: ''
      });
    },
    getBucket(){
      return this.obsConfig.Bucket;
    },
    abortMultipartUpload(file, callback) {
      if (file.uploadId && file.status == "uploading") {
        this.obsClient
          .abortMultipartUpload({
            Bucket: this.getBucket(),
            Key: file.obsKey,
            UploadId: file.uploadId,
          })
          .then((result) => {
            if (result.CommonMsg.Status < 300) {
              callback && callback();
            }
          });
      } else {
        callback && callback();
      }
    },
    createUUID() {
      return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"
        .replace(/[xy]/g, function (c) {
          var r = (Math.random() * 16) | 0,
            v = c == "x" ? r : (r & 0x3) | 0x8;
          return v.toString(16);
        })
        .replaceAll("-", "");
    },
    handleUpload(file) {
      let target = this.$refs.upload;
      let fileObj = target.getFile(file);
      fileObj.status = "uploading";
      // this.initiateData.option = option;
      this.fileUrl = "";
      var _this = this;
      let fileSuffix = this.$commonFileUtil.getFileSuffix(file.name);
      let uuids = this.createUUID() + Date.now();
      fileObj.obsKey = uuids + "." + fileSuffix;
      const params = {
        Bucket: this.getBucket(),
        Key: fileObj.obsKey,
      };
      // let target = this.$refs.upload;
      // let fileObj = target.getFile(option.file);
      // fileObj.obsKey = uuids;
      setTimeout(() => {
        this.obsClient.initiateMultipartUpload(params).then((result) => {
          if (result.CommonMsg.Status < 300) {
            var uploadId = result.InterfaceResult.UploadId;
            // _this.initiateData.uploadId = uploadId;
            fileObj.uploadId = uploadId;
            /*
             * Step 2: upload a part
             */
            var etag = [];
            var uploadPromise = new Promise((resolve) => {
              var partLen = 5 * 1024 * 1024;
              var count = Math.ceil(file.size / partLen);
              var indexNum = 0;
                this.uploadPartMethod(
                  file,
                  uploadId,
                  indexNum,
                  partLen,
                  etag,
                  count,
                  resolve
                );
            });
            uploadPromise.then((result) => {
              const paramsEnd = {
                Bucket: this.getBucket(),
                Key: fileObj.obsKey,
                UploadId: uploadId,
                Parts: etag.sort((a, b) => a.PartNumber - b.PartNumber),
              };
              this.obsClient
                .completeMultipartUpload(paramsEnd)
                .then((result) => {
                  if (result.CommonMsg.Status < 300) {
                    let fileUrl = _this.getImageUrl(file);
                    let fileData = this.parseFileUrl(fileUrl, file);
                    target.handleProgress({ percent: 100 }, file);

                    target.handleSuccess(
                      {
                        type: "success",
                        objx: fileData,
                      },
                      file
                    );
                  } else {
                    this.handleFileError(
                      new Error(
                        result.CommonMsg.Message ||
                          this.$t2(
                            "上传异常",
                            "components.VabUpload.uploadException"
                          )
                      ),
                      file
                    );
                  }
                });
            });
          } else {
            this.handleFileError(
              new Error(
                result.CommonMsg.Message ||
                  this.$t2("上传异常", "components.VabUpload.uploadException")
              ),
              file
            );
          }
        });
      }, 20);
    },
    parseFileUrl(fileUrl,file) {
      if (!fileUrl) return null;
      let result = null;

      // 输入校验
      if (typeof fileUrl !== "string") {
        throw new TypeError("输入必须是字符串格式");
      }
      if (!fileUrl.trim()) {
        throw new Error("URL不能为空");
      }

      // 基本URL格式验证
      const urlRegex =
        /^(https?:\/\/)?([\w.-]+)(:\d+)?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i;
      if (!urlRegex.test(fileUrl)) {
        throw new Error("无效的URL格式");
      }

      // 提取域名部分
      const domainRegex = /^(https?:\/\/[^\/]+)/i;
      const domainMatch = fileUrl.match(domainRegex);
      if (!domainMatch) {
        throw new Error("URL缺少协议或域名部分");
      }
      const domain = domainMatch[0];

      // 提取完整路径
      const url = fileUrl.substring(domain.length);
      if (!url || url === "/") {
        throw new Error("URL缺少文件路径部分");
      }

      // 提取带扩展名的文件名
      const filenameRegex = /[^\/]+$/;
      const filenameMatch = url.match(filenameRegex);
      if (!filenameMatch) {
        throw new Error("无法从路径中提取文件名");
      }
      const fullFilename = filenameMatch[0];

      // 验证文件名格式（至少1字符+扩展名）
      const nameFormat = /^.+\..+$/;
      if (!nameFormat.test(fullFilename)) {
        throw new Error(`无效的文件名格式: ${fullFilename}`);
      }

      // 修复点：更可靠的文件名和扩展名分离
      const lastDotIndex = fullFilename.lastIndexOf(".");
      const filenameBase = fullFilename.substring(0, lastDotIndex); // 点之前部分
      const extension = fullFilename.substring(lastDotIndex + 1).toLowerCase(); // 点之后部分

      // 扩展名验证
      /* const validExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp'];
    if (!validExtensions.includes(extension)) {
      throw new Error(`不支持的扩展名类型: ${extension}`);
    } */

      let thumbnail = null,
        large = null,
        medium = null,
        source = null;
      if (this.$commonFileUtil.isPicture(extension)) {
        // thumbnail = url;
        // large = url;
        // medium = url;
        source = url;
      }

      result = {
        extension,
        domain,
        url,
        thumbnail,
        large,
        medium,
        source,
        fileSize: file?file.size:0,
        name: file?file.name:null
      };

      // 返回结构化对象
      return result;
    },
    uploadPartMethod(file, UploadId, indexNum, partLen, etag, count, resolve) {
      let target = this.$refs.upload;
      let fileObj = target.getFile(file);
      var _this = this;
      this.obsClient
        .uploadPart({
          Bucket: this.getBucket(),
          Key: fileObj.obsKey,
          UploadId,
          PartNumber: indexNum + 1,
          SourceFile: file,
          PartSize: partLen,
          Offset: partLen * indexNum,
        })
        .then((result) => {
          if (fileObj.status !== "uploading") {
            return;
          }
          if (result.CommonMsg.Status < 300) {
            etag.push({
              ETag: result.InterfaceResult.ETag,
              PartNumber: indexNum + 1,
            });
            indexNum++;
            if (indexNum < count) {
              let percentage = Math.ceil((indexNum / count) * 100);
              // _this.percentage = Math.ceil((indexNum / count) * 100);
              fileObj.percentage = percentage;
              // option.file.percent = percentage;
              // option.onProgress(option.file);

              let progressEvent = document.createEvent("Event");
              progressEvent.percent = percentage;
              target.handleProgress(progressEvent, file);

              _this.uploadPartMethod(
                file,
                UploadId,
                indexNum,
                partLen,
                etag,
                count,
                resolve
              );
            }
            if (indexNum == count) {
              // _this.percentage = 100;
              let percentage = 100;
              fileObj.percentage = percentage;
              /* option.file.percent = percentage;
              option.onProgress(option.file); */

              let progressEvent = document.createEvent("Event");
              progressEvent.percent = percentage;
              target.handleProgress(progressEvent, file);

              resolve("任务完成");
            }
          } else {
            this.handleFileError(
              new Error(
                result.CommonMsg.Message ||
                  this.$t2("上传异常", "components.VabUpload.uploadException")
              ),
              file
            );
          }
        })
        .catch((error) => {
          this.handleFileError(error, file);
        });
    },
    getImageUrl(file) {
      let target = this.$refs.upload;
      let fileObj = target.getFile(file);
      let Bucket= this.getBucket();
      let server = this.obsConfig.server
      let arr = server.split("//")
      let url = `${arr[0]}//${Bucket}.${arr[1]}/${fileObj.obsKey}`
      // let url = `https://gztw-file01.obs.cn-south-1.myhuaweicloud.com/${fileObj.obsKey}`;
      return url;
      console.log(url);
      /* let target = this.$refs.upload;
      let fileObj = target.getFile(file);
      const _this = this;
      this.obsClient.getObject(
        {
          Bucket: this.getBucket(),
          Key: fileObj.obsKey,
          SaveByType: "file",
        },
        function (error, response) {
          if (error) {
          } else if (response.CommonMsg.Status < 300) {
            const url = response.InterfaceResult.Content.SignedUrl;
            console.log(url);
            // this.imageUrl = url;
          }
        }
      ); */
    },
    //obs end

    checkPreUploadList() {
      let uploadingLimit = this.option.uploadingLimit || this.uploadingLimit;
      let target = this.$refs.upload;
      let fileList1 = (target.uploadFiles || []).filter((item) => {
        return item.status == "preUpload";
      });
      let fileList2 = (target.uploadFiles || []).filter((item) => {
        return item.status == "uploading";
      });
      if (fileList2.length < uploadingLimit && fileList1.length > 0) {
        let num = uploadingLimit - fileList2.length;
        if (num) {
          let toNum = Math.min(fileList1.length, num);
          for (let i = 0; i < toNum; i++) {
            let fileRaw = fileList1[i].raw;
            // this.uploadFile(fileRaw);
            this.handleUpload(fileRaw);
          }
        }
      }
    },
    async uploadFile(file) {
      if (!file || file.status == "fail") return;
      let target = this.$refs.upload;
      if (!target) return;
      let fileObj = target.getFile(file);
      if (fileObj.status != "preUpload") return;
      if (!this.uploadUrl) {
        await this.initUploadUrl();
      }
      this.total = 0;
      target.handleProgress({ percent: 0 }, file);

      // 解析为BUFFER数据
      // 我们会把文件切片处理：把一个文件分割成为好几个部分（固定数量/固定大小）
      // 每一个切片有自己的部分数据和自己的名字
      // HASH_1.mp4
      // HASH_2.mp4
      // ...

      this.fileParse(file, "buffer", (buffer) => {
        let spark = new imFun.SparkMD5.ArrayBuffer(),
          chunkSize = this.chunkSize * 1024 * 1024, // Read in chunks of 2MB
          chunks = Math.ceil(file.size / chunkSize),
          hash,
          suffix;
        spark.append(buffer);
        hash = spark.end();
        let nameSplit = /\.([0-9a-zA-Z]+)$/i.exec(file.name);

        suffix = nameSplit && nameSplit.length > 1 ? nameSplit[1] : "";

        let checkUrl = this.uploadUrl.replace(
          "/docfile/upload",
          "/docfile/check"
        );
        let checkData = {
          name: file.name,
          md5: hash,
        };
        let abort;
        let checkReq = this.$http({
          url: checkUrl,
          method: "post",
          cancelToken: new imFun.axios.CancelToken(function executor(c) {
            abort = c;
            file.abort = c;
          }),
          data: checkData,
          failMsg: false,
          modal: false,
          callback: (res) => {
            if (res.type == "success") {
              let resData = res.objx || {};
              let chunkParam = {
                fullFile: file,
                chunkSize: chunkSize,
                chunks: chunks,
                chunkIndex: 0,
                md5: hash,
                uuid: resData.uuid,
              };
              file.chunkParam = chunkParam;

              this.sendRequest(file);
            } else {
              this.handleFileError(
                new Error(
                  res.content ||
                    this.$t2("上传异常", "components.VabUpload.uploadException")
                ),
                file
              );
            }
          },
          error: (e) => {
            this.handleFileError(e, file);
          },
        });
        checkReq.abort = () => {
          abort(this.$t2("取消上传", "components.VabUpload.cancelUpload"));
        };
      });
    },
    async sendRequest(fullFile) {
      let that = this;
      let uploadUrl = this.uploadUrl;
      let chunkParam = fullFile.chunkParam;
      let target = that.$refs.upload;
      let abort;
      let config = {
        headers: {
          "Content-Type": "multipart/form-data",
        },
        cancelToken: new imFun.axios.CancelToken(function executor(c) {
          /* let target = that.$refs.upload;
          let filem = target.getFile(file);
          abort = c;
          filem.abort = c; */
          abort = c;
          fullFile.abort = c;
        }),
        onUploadProgress: (progressEvent) => {
          if (!target || !fullFile) return;
          let file = target.getFile(fullFile);
          if (file) {
            // progressEvent.loaded:已上传文件大小
            // progressEvent.total:被上传文件的总大小
            let start = chunkParam.start;
            let uploadedSize =
              start +
              Math.floor(
                (chunkParam.currentSize * progressEvent.loaded) /
                  progressEvent.total
              );
            let percent = Math.floor((uploadedSize * 100) / fullFile.size);
            if (percent == 100) {
              percent = 99;
            }
            progressEvent.percent = percent;
            target.handleProgress(progressEvent, fullFile);
          }
        },
        failMsg: false,
        modal: false,
      }; //添加请求头

      let chunkIndex = chunkParam.chunkIndex;
      let chunkSize = chunkParam.chunkSize;
      var start = chunkIndex * chunkSize,
        end =
          start + chunkSize >= fullFile.size
            ? fullFile.size
            : start + chunkParam.chunkSize;
      chunkParam.currentSize = end - start;
      chunkParam.start = start;
      chunkParam.end = end;

      let preFormData = {
        file: fullFile.slice(start, end),
        name: fullFile.name,
        chunks: chunkParam.chunks,
        chunk: chunkIndex,
        md5: chunkParam.md5,
        uuid: chunkParam.uuid,
        fileSize: fullFile.size,
      };

      let formData = new FormData();
      Object.keys(preFormData).forEach((key) => {
        formData.append(key, preFormData[key]);
      });

      let req = this.$http
        .post(uploadUrl, formData, config)
        .then((res1) => {
          if (res1.type == "success") {
            if (preFormData.chunk + 1 >= preFormData.chunks) {
              let mergeData = {};
              Object.keys(preFormData).forEach((key) => {
                if (key != "file" && key != "chunk") {
                  mergeData[key] = preFormData[key];
                }
              });
              let _param = {
                mergeData: mergeData,
                chunkParam: chunkParam,
              };
              this.mergeFile(_param);
            } else {
              chunkParam.chunkIndex = chunkParam.chunkIndex + 1;
              this.sendRequest(fullFile);
            }
          } else {
            this.handleFileError(
              new Error(
                res1.content ||
                  this.$t2("上传异常", "components.VabUpload.uploadException")
              ),
              fullFile
            );
          }
          return res1;
        })
        .catch((err) => {
          try {
            if (!abort) {
              this.handleFileError(err, fullFile);
            }
          } catch (tt) {}
        });
      req.abort = () => {
        abort(this.$t2("取消上传", "components.VabUpload.cancelUpload"));
      };
    },
    mergeFile(param) {
      let mergeData = param.mergeData;
      let chunkParam = param.chunkParam;
      let fullFile = chunkParam.fullFile;
      let mergeUrl = this.uploadUrl.replace(
        "/docfile/upload",
        "/docfile/merge"
      );
      let target = this.$refs.upload;
      this.$http({
        url: mergeUrl,
        method: "post",
        data: mergeData,
        failMsg: false,
        modal: false,
        cancelToken: new imFun.axios.CancelToken(function executor(c) {
          if (fullFile) fullFile.abort = c;
        }),
        callback: (res) => {
          if (!target || !fullFile) return;
          if (res.type == "success") {
            let file = target.getFile(fullFile);
            if (file) {
              target.handleProgress(
                {
                  percent: 100,
                },
                fullFile
              );
              target.handleSuccess(res, fullFile);
            }
          } else {
            this.handleFileError(
              new Error(
                res.content ||
                  this.$t2("上传异常", "components.VabUpload.uploadException")
              ),
              fullFile
            );
          }
        },
        error: (e) => {
          if (!target || !fullFile) return;
          if (fullFile) {
            let file = target.getFile(fullFile);
            if (file) {
              this.handleFileError(e, fullFile);
            }
          }
        },
      });
    },
    handleBtn() {
      let target = this.$refs.upload;
      let fileList = (target.uploadFiles || []).filter((item) => {
        return item.status == "uploading" || item.status == "ready";
      });
      if (this.btn) {
        //断点续传
        this.abort = false;
        this.btn = false;
        fileList.forEach((uploadFile) => {
          let nextChunk = uploadFile.raw.nextChunk;
          this.sendRequest(uploadFile.raw.partList, nextChunk);
        });
      } else {
        //暂停上传
        fileList.forEach((uploadFile) => {
          uploadFile.raw.abort(
            this.$t2("取消上传", "components.VabUpload.cancelUpload")
          );
        });
        this.btn = true;
        this.abort = true;
      }
    },
    //end
    getShowImage(file, fileName) {
      fileName = fileName || file.name;
      if (this.$commonFileUtil.isPictureFile(fileName)) {
        return file.showUrl || file.url;
      } else {
        return this.$commonFileUtil.getFileIconRequire(fileName);
      }
    },
    removeFile(sfile) {
      var target = this.$refs.upload;
      var index;
      var fileList = target.uploadFiles;
      for (let i = 0; i < fileList.length; i++) {
        let file = fileList[i];
        if (sfile.uid == file.uid) {
          index = i;
          if (sfile.status == "uploading") {
            // file.status == 'delete'
            //target.abort(file);
            this.abortMultipartUpload(file);
            /* file.raw.abort &&
              file.raw.abort(
                this.$t2("取消上传", "components.VabUpload.cancelUpload")
              ); */
          }
          break;
        }
      }

      target.uploadFiles.splice(index, 1);
      this.handleChange(sfile, target.uploadFiles);
    },
    submitImage() {
      var target = this.$refs.upload;
      var fileList = target.uploadFiles;
      let fileInfos = [];
      let fileDatas = [];
      for (let i = 0; i < fileList.length; i++) {
        let file = fileList[i];
        if (file.status == "uploading") {
          this.$message({
            message: this.$t2(
              "文件上传中",
              "components.VabUpload.fileUploading"
            ),
            type: "error",
            duration: 2000,
          });
          return;
        }
        if (file.status == "success") {
          let fileData = file.response.objx;
          fileData.name = file.name;
          let fileInfo = {
            name: file.name,
            fileData: fileData,
            file: file.raw,
          };
          fileInfos.push(fileInfo);
          fileDatas.push(fileData);
        }
      }
      this.handleClose();
      this.$emit("callback", fileInfos, fileDatas);
      this.callback && this.callback(fileDatas, fileInfos);
    },
    showViewDialog(lineData) {
      var data = lineData.fileData ? lineData.fileData : lineData;

      let thumbnail = data ? data.thumbnail || "" : "";

      var realUrl = data.domain + data.url;
      var showUrl = "";
      let fileName = lineData ? lineData.name || "" : "";
      if (!this.$commonFileUtil.isPictureFile(fileName)) {
        showUrl = this.$commonFileUtil.getFileIconRequire(fileName);
      } else if (thumbnail) {
        showUrl = data.domain + thumbnail;
      } else {
        showUrl = data.domain + data.url;
      }

      var preName = "";
      var suffix = "";
      var i = fileName.lastIndexOf(".");
      if (i >= 0) {
        suffix = fileName.substring(i + 1, fileName.length).toLowerCase();
      }
      this.fileViewInfo = {
        realUrl: realUrl,
        showUrl: showUrl,
        fileName: fileName,
        suffix: suffix,
        data: data,
      };
      this.fileViewDialogVisible = true;
    },
    getShowUrl(attachment, field) {
      let showUrl = null;
      let typeStr = Object.prototype.toString.call(attachment);
      if (typeStr == "[object Object]") {
        let showField = field ? field : "medium";
        let fullUrl =
          attachment.domain +
          (attachment[showField] ? attachment[showField] : attachment.url);
        showUrl = this.$commonFileUtil.getShowUrl(fullUrl);
      } else {
        showUrl = this.$commonFileUtil.getShowUrl(attachment);
      }
      return showUrl;
    },
    addPrivateFiles(rows) {
      var target = this.$refs.upload;
      let uploadFiles = target.uploadFiles;
      let sourceSns = uploadFiles
        .filter((row) => {
          return !!(
            row.response &&
            row.response.objx &&
            row.response.objx.sourceSn
          );
        })
        .map((row) => row.response.objx.sourceSn);

      let newFiles = rows
        .filter((row) => !row.dirs && !sourceSns.includes(row.sn))
        .map((row) => {
          let item = {
            status: "success",
            name: row.fileName,
            size: row.fileSize,
            percentage: 100,
            uid: row.fileSn,
            raw: {
              lastModified: "",
              lastModifiedDate: new Date(),
              name: row.fileName,
              size: row.fileSize,
              type: "",
              uid: row.fileSn,
              webkitRelativePath: "",
            },
            response: {
              time: "",
              type: "success",
              objx: {
                thumbnail: row.thumbnail,
                extension: row.extension,
                large: row.large,
                fileSize: row.fileSize,
                domain: row.domain,
                source: row.source,
                medium: row.medium,
                url: row.url,
                sourceSn: row.sn,
              },
              content: "success",
              rmid: null,
            },
            url: row.domain + row.url,
            showUrl: this.getShowUrl(row),
          };
          return item;
        });
      uploadFiles.push(...newFiles);
    },
    confirmPrivateProfileDialog(rows) {
      this.addPrivateFiles(rows);
    },
    initPrivateUploadBt() {
      if (settingConfig.privateProfileCode && this.pickPrivateProfile) {
        this.$http({
          url: USER_PREFIX + "/file_store_area/getByCode",
          method: "post",
          data: { stringOne: settingConfig.privateProfileCode },
          failMsg: false,
          errorMsg: false,
          success: (res) => {
            this.showPrivateUploadBtn = res.objx ? true : false;
          },
        });
      } else {
        this.showPrivateUploadBtn = false;
      }
    },
    initPickUploadMode() {
      this.showLocalUploadBtn = false;
      this.showPrivateUploadBtn = false;
      this.$http({
        url: USER_PREFIX + "/system_parameter/getByCode",
        method: "post",
        data: { code: "pickUploadMode" },
        success: (res) => {
          let value = !res.objx || !res.objx.value ? "2" : res.objx.value;
          if (value == "0") {
            //启用本地上传，个人文档上传
            this.showLocalUploadBtn = true;
            this.initPrivateUploadBt();
          } else if (value == "1") {
            //启用个人文档上传
            this.initPrivateUploadBt();
          } else if (value == "2") {
            //启用本地上传
            this.showLocalUploadBtn = true;
          }
        },
      });
    },
    pasteEvent(e) {
      // e.preventDefault();
      e.stopPropagation();
      if (!this.pasteAreaStatus) {
        return;
      }
      if (!(e.clipboardData && e.clipboardData.items)) {
        return;
      }
      let files = Array.from(e.clipboardData.files);
      let getFileSuffix = this.$commonFileUtil.getFileSuffix;
      if (files.length) {
        let fileList = files.map((rawFile) => {
          let name = rawFile.name;
          let index = name.lastIndexOf(".");
          let fileSuffix = getFileSuffix(name);
          let fileName =
            index >= 0 ? name.substring(0, index).toString() : name.toString();
          let file = {
            name: rawFile.name,
            size: rawFile.size,
            raw: rawFile,
            showUrl: URL.createObjectURL(rawFile),
            fileName: fileName,
            fileSuffix: fileSuffix,
          };
          return file;
        });
        this.pasteList.push(...fileList);
      }
    },
    deletePasteFile(index) {
      this.pasteList.splice(index, 1);
    },
    confirmPasteFile() {
      let target = this.$refs.upload;
      let innerTarget = target.$refs["upload-inner"];
      let pasteList = this.$baseLodash.cloneDeep(this.pasteList);
      let files = pasteList.map((item) => {
        let name = item.name;
        let fileRaw = item.raw;
        fileRaw.fileName = name;
        return fileRaw;
      });
      innerTarget.uploadFiles(files);
      this.$nextTick(() => {
        target.uploadFiles.forEach((uploadFile) => {
          let fileRaw = uploadFile.raw;
          if (fileRaw.fileName) {
            uploadFile.name = fileRaw.fileName;
            delete fileRaw.fileName;
          }
        });
      });
      this.pasteList = [];
    },
    changeFileName(file) {
      if (file.fileSuffix) {
        file.name = (file.fileName + "." + file.fileSuffix).toString();
      } else {
        file.name = file.fileName.toString();
      }
    },
    handleFileError(err, rawFile) {
      let target = this.$refs.upload;
      if (!target) return;
      const file = target.getFile(rawFile);
      const fileList = target.uploadFiles;

      file.status = "fail";
      file.failMsg = err && err.message ? err.message : null;

      // fileList.splice(fileList.indexOf(file), 1);

      target.onError(err, file, target.uploadFiles);
      target.onChange(file, target.uploadFiles);
      this.updateUploadingStatus();
    },
    choosePasteArea(e) {
      e.stopPropagation();
      this.pasteAreaStatus = true;
    },
    openFileNameDialog(row, index) {
      this.editFileName = row.fileName?.toString();
      this.editFileSuffix = row.fileSuffix?.toString();
      this.editFileIndex = index;
      this.showFileNameDialog = true;
    },
    confirmFileNameDialog() {
      if (!this.editFileName) {
        this.$message({
          message: this.$t2("文件名不能为空", "components.VabUpload.warnMsg3"),
          type: "error",
          showClose: true,
          duration: 3000,
        });
        return;
      }
      let editFileIndex = this.editFileIndex;
      let file = this.pasteList[editFileIndex];
      file.fileName = this.editFileName.toString();
      file.name = (file.fileName + "." + file.fileSuffix).toString();
      this.showFileNameDialog = false;
    },
  },
};


function formatFileSize(fileSize) {
  fileSize = fileSize || 0;
  if (fileSize < 1024) {
    return fileSize + "B";
  } else if (fileSize < 1024 * 1024) {
    var temp = fileSize / 1024;
    temp = temp.toFixed(2);
    return temp + "KB";
  } else if (fileSize < 1024 * 1024 * 1024) {
    var temp = fileSize / (1024 * 1024);
    temp = temp.toFixed(2);
    return temp + "MB";
  } else {
    var temp = fileSize / (1024 * 1024 * 1024);
    temp = temp.toFixed(2);
    return temp + "GB";
  }
}``

export const mixins = tmixins;
