<template>
  <div class="ace-upload-box">
    <div class="upper-box">
      <el-select v-model="secretLevel" :size="size" class="ace-upload-secretLevel-selector" v-if="this.showSecretLevel">
        <el-option v-for="item in secretLevels" :key="'secretLevel' + item.value" :label="item.name" :value="item.value"> </el-option>
      </el-select>

      <div class="operation-box" v-show="isAllowUpload">
        <!-- 选择文件 -->

        <div :id="targetId"></div>

        <!-- 打包下载按钮 -->
      </div>

      <el-divider direction="vertical" v-if="showDownloadZip && allowUpload"></el-divider>

      <el-button v-if="showDownloadZip" @click="downloadZippedHandle">打包下载</el-button>

      <el-divider direction="vertical" v-if="configuration.enableReview"></el-divider>

      <div class="initiating-process" v-if="configuration.enableReview">
        <el-button icon="el-icon-s-check" v-if="showReviewBtn" type="success" :size="size" @click="startReviewHandle">发起审查</el-button>

        <el-button icon="el-icon-view" :size="size" @click="viewReviewHandle">查看审查</el-button>

        <add-review-dialog ref="addReview" :need-review-files="needReviewFiles"></add-review-dialog>

        <view-review ref="viewReview"></view-review>
      </div>
    </div>

    <div class="lower-box" v-if="showReviewBtn">
      <p class="prompt-text">上传的文件中存在未审查文件，需要通过审查流程后才可下载。（可以点击“发起审查”按钮，发起审查流程）</p>
    </div>
  </div>
</template>
<script>
import WebUploader from "webuploader";
import AddReviewDialog from "./AddReviewDialog";
import ViewReview from "./ViewReview";
import { getAppName } from "@/utils";
export default {
  name: "Uploader",
  components: {
    AddReviewDialog,
    ViewReview,
  },
  provide() {
    return {
      upload: this,
    };
  },
  props: {

    appName: {
      type: String,
      default: () => getAppName(),
    },
    configurationKey: {
      type: String,
      default: function () {
        return "";
      },
    },
    formId: {
      type: String,
      default: function () {
        return "";
      },
    },
    allowUpload: {
      type: Boolean,
      default: function () {
        return true;
      },
    },
    allowDownload: {
      type: Boolean,
      default: function () {
        return true;
      },
    },
    allowDelete: {
      type: Boolean,
      default: function () {
        return true;
      },
    },
    maxSecretLevel: {
      type: Number,
      default: function () {
        return 1;
      },
    },
    defaultSecretLevel: {
      type: Number,
      default: function () {
        return 0;
      },
    },
    size: {
      type: String,
      default: "small",
    },
  },
  computed: {
    deleteAuth() {
      if (this.configuration.deleteOperationKey) {
        return this.$isAuth(this.configuration.deleteOperationKey);
      }
      return true;
    },
    uploadAuth() {
      if (this.configuration.deleteOperationKey) {
        return this.$isAuth(this.configuration.uploadOperationKey);
      }
      return true;
    },
    downloadAuth() {
      if (this.configuration.deleteOperationKey) {
        return this.$isAuth(this.configuration.downloadOperationKey);
      }
      return true;
    },
    isAllowUpload: function () {
      return this.allowUpload && this.configuration.allowUpload && this.uploadAuth;
    },
    //是否显示密级选择
    showSecretLevel() {
      return this.loadingComplete && this.allowUpload && this.configuration.allowUpload && this.configuration.enableSecretLevel && this.uploadAuth;
    },
    showDownloadZip() {
      return (
        (this.files.length > 0 || this.newFiles.length > 0) && //文件长度大于0  或新上传文件长度大于0
        !this.enableReview && //并且没有开启审查功能
        this.allowDownload && //并且前端属性允许下载为true
        this.configuration.allowDownload && //附件配置里允许下载
        this.downloadAuth
      );
    },
  },
  watch: {
    defaultSecretLevel(val) {
      this.secretLevel = val;
    },
    configurationKey: function () {
      this.load();
    },
    formId: function () {
      this.load();
    },
    allowUpload: function (val) {
      if (this.fileUploader != null) {
        this.fileUploader.setAllowUpload(val);
      }
    },
    allowDelete: function (val) {
      if (this.fileUploader != null) {
        this.fileUploader.setAllowDelete(val);
      }
    },
    allowDownload: function (val) {
      if (this.fileUploader != null) {
        this.fileUploader.setAllowDownload(val);
      }
    },
    maxSecretLevel(val) {
      if (this.fileUploader != null) {
        this.initSecretLevelsByMaxSecretLevel(this.originalSecretLevels, val);
      }
    },
  },
  data() {
    return {
      httpRequestUrl: this.$httpRequestUrl ? "http://" + this.$httpRequestUrl : window.location.origin,
      pickerId: "",
      enableReview: false,
      needReviewFiles: [],
      reviewLoading: false,
      showReviewBtn: false,
      targetId: this.$attrs.id === undefined ? this.getUuid() : this.$attrs.id,
      fileUploader: null,
      configuration: {},
      loadingComplete: true,
      secretLevels: [], //可选密级集合
      originalSecretLevels: [], //从服务端获取到的原始密级
      secretLevel: "",
      files: [],
      newFiles: [],
      webUploader: null, // webUploader 实例
      maxPreviewSize: null,
      userSecretLevel: null, //当前用户的密级
    };
  },
  created() {
    // this.$nextTick(function () {
    //   this.loadingComplete = false
    //   this.load()
    // })
  },
  mounted() {
    this.loadingComplete = false;
    this.load();
  },
  methods: {
    //根据最大密级初始化密级选项
    initSecretLevelsByMaxSecretLevel(secretLevels, max) {
      if (max == -1 || secretLevels.length === 0) {
        //如果最大密级为-1或后端返回的密级集合的长度为0 则不用筛选数据直接赋值
        this.secretLevels = secretLevels;
        return;
      }
      //为了方便后期操作置空数组
      this.secretLevels = [];
      //如果密级不为-1 则将大于或等于对应密级的值返回
      secretLevels.forEach((item) => {
        if (item.value >= max) {
          this.secretLevels.push(item);
        }
      });
      // if (this.secretLevelSelect !== undefined) {
      //     this.secretLevelSelect.options.length = 0
      //     if (
      //         this.secretLevels !== undefined ||
      //         this.secretLevels != null
      //     ) {
      //         for (var j = 0; j < this.secretLevels.length; j++) {
      //             var item = this.secretLevels[j]
      //             if (this.parent.maxSecretLevel !== undefined) {
      //                 if (this.parent.maxSecretLevel > item.value) {
      //                     continue
      //                 }
      //             }
      //             var opt = document.createElement('option')
      //             opt.value = item.value
      //             opt.text = item.name
      //             this.secretLevelSelect.add(opt)
      //         }
      //     }
      // }
    },
    adornUrl(actionName, paramsQuery) {
      const baseURL = this.$httpRequestUrl ? "http://" + this.$httpRequestUrl : window.location.origin;
      const url = baseURL + "/fileserver/" + actionName + "?appName=" + this.appName + "&token=" + this.$cookie.get("token");
      if (!paramsQuery) {
        return url;
      }
      return url + "&" + paramsQuery;
    },
    viewReviewHandle() {
      this.$refs.viewReview.init();
    },
    startReviewHandle() {
      this.needReviewFiles = [];
      this.fileUploader.files.forEach((item, index) => {
        if (item.needReview == 1) {
          this.needReviewFiles.push(item);
        }
      });
      this.$nextTick(() => {
        this.$refs.addReview.visible = true;
      });
    },
    downloadZippedHandle() {
      this.fileUploader.downloadZipped();
    },
    refresh() {
      this.load();
    },
    getUuid() {
      var s = [];
      var hexDigits = "0123456789abcdef";
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23] = "-";

      var uuid = s.join("");
      return uuid;
    },
    load() {
      window.ace = {
        adornFileUploaderUrl: this.$http.adornFileUploaderUrl,
      };
      this.fileUploader = this.createFileUploader(this, {
        allowUploadChanged: this.allowUploadChanged,
        allowDeleteChanged: this.allowDeleteChanged,
        allowDownloadChanged: this.allowDownloadChanged,
        fileAdded: this.fileAdded,
        fileDeleting: this.fileDeleting,
        fileDeleteError: this.fileDeleteError,
        fileDeleted: this.fileDeleted,
        spaceAllocating: this.spaceAllocating,
        spaceAllocated: this.spaceAllocated,
        spaceAllocateError: this.spaceAllocateError,
        uploadProgress: this.uploadProgress,
        uploadComplete: this.uploadComplete,
        uploadSuccess: this.uploadSuccess,
        uploadError: this.uploadError,
        uploadFinished: this.uploadFinished,
        initError: this.initError,
        initSuccess: this.initSuccess,
        error: this.error,
      });
    },
    allowUploadChanged(val) {
      this.$emit("allowUploadChanged", val);
    },
    allowDeleteChanged(val) {
      this.$emit("allowDeleteChanged", val);
    },
    allowDownloadChanged(val) {
      this.$emit("allowDownloadChanged", val);
    },
    fileAdded(file) {
      //刚上传的文件 needReview 设置为0
      if (this.fileUploader.configuration.enableReview) {
        file.needReview = 1;
      } else {
        file.needReview = 0;
      }
      this.$emit("fileAdded", file);
    },
    fileDeleting(file) {
      this.$emit("fileDeleting", file);
    },
    fileDeleteError(file, code, msg) {
      this.$emit("fileDeleteError", file, code, msg);
    },
    fileDeleted(file) {
      this.$emit("fileDeleted", file);
      this.files = this.files.filter((item) => {
        return file.yfId !== item.yfId;
      });
      this.newFiles = this.newFiles.filter((item) => {
        return file.yfId !== item.yfId;
      });
      let hasUnapprovedFiles = false;
      //条件1：是否开启了附件审查选项
      if (this.configuration.enableReview) {
        //条件2: 有新上传的文件
        //条件3：有未审查的文件
        hasUnapprovedFiles = this.newFiles.length > 0 || this.hasUnapprovedFiles(this.files);
      }
      this.showReviewBtn = hasUnapprovedFiles;
    },
    spaceAllocating(file) {
      this.$emit("spaceAllocating", file);
    },
    spaceAllocated(file) {
      this.$emit("spaceAllocated", file);
    },
    spaceAllocateError(file, code, msg) {
      this.$emit("spaceAllocateError", file, code, msg);
    },
    uploadProgress(file, percentage) {
      this.$emit("uploadProgress", file, percentage);
    },
    uploadComplete(file) {
      this.$emit("uploadComplete", file);
    },
    uploadSuccess(file, response) {
      this.$emit("uploadSuccess", file, response);
      this.newFiles.push(file);
      //判断当前附件是否开启了 流程审查
      if (this.configuration.enableReview) {
        this.showReviewBtn = true;
      }
    },
    uploadError(file, reason) {
      this.$emit("uploadError", file, reason);
    },
    uploadFinished() {
      this.$emit("uploadFinished");
    },
    initError(code, msg) {
      this.$emit("initError", code, msg);
    },
    initSuccess(webUploader, files, secretLevels, configuration) {
      this.$emit("initSuccess", webUploader, files, secretLevels, configuration);
    },
    error(type) {
      var reason;
      switch (type) {
        case "Q_EXCEED_NUM_LIMIT":
          reason = "文件个数超过最大限制";
          break;
        case "Q_EXCEED_SINGLE_SIZE_LIMIT":
          reason = "单个文件大小超过最大限制";
          break;
        case "Q_EXCEED_SIZE_LIMIT":
          reason = "文件大小超过最大限制";
          break;
        case "Q_TYPE_DENIED":
          reason = "文件类型不支持";
          break;
        case "NO_FILES":
          reason = "没有文件可供下载";
          break;
        default:
          reason = "未知";
          break;
      }
      this.$emit("error", type, reason);
    },
    /**
     * 判断是否存在未审查文件
     * @param {Object} files 从 fileConfiguration/load 接口获取到的文件对象
     */
    hasUnapprovedFiles(files) {
      //遍历判断文件中是否有需要审查的文件
      let hasNeedReview = false;
      if (files.length === 0) return false;
      files.forEach((item) => {
        if (item.needReview == 1) {
          hasNeedReview = true;
        }
      });
      return hasNeedReview;
    },
    createFileUploader(parent, events) {
      let _this = this;
      var fileUploader = {
        parent: parent,
        getUuid: function () {
          var s = [];
          var hexDigits = "0123456789abcdef";
          for (var i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
          }
          s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
          s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
          s[8] = s[13] = s[18] = s[23] = "-";

          var uuid = s.join("");
          return uuid;
        },
        events: events
          ? {
              allowUploadChanged: events.allowUploadChanged,
              allowDeleteChanged: events.allowDeleteChanged,
              allowDownloadChanged: events.allowDownloadChanged,
              fileAdded: events.fileAdded,
              fileDeleting: events.fileDeleting,
              fileDeleteError: events.fileDeleteError,
              fileDeleted: _this.fileDeleted,
              spaceAllocating: events.spaceAllocating,
              spaceAllocated: events.spaceAllocated,
              spaceAllocateError: events.spaceAllocateError,
              uploadProgress: events.uploadProgress,
              uploadComplete: events.uploadComplete,
              uploadSuccess: events.uploadSuccess,
              uploadError: events.uploadError,
              uploadFinished: events.uploadFinished,
              initError: events.initError,
              initSuccess: events.initSuccess,
              error: events.error,
            }
          : {},
        initWebUploader: function () {
          var fu = this;
          if (fu.webUploaderInitializing) {
            fu.onWebUploaderInitialized(fu.doInitWebUploader);
          } else {
            fu.doInitWebUploader();
          }
        },
        doInitWebUploader: function () {
          var fu = this;
          fu.webUploaderInitializing = true;
          var option = {
            // {Selector} [可选] [默认值：undefined] 指定Drag And Drop拖拽的容器，如果不指定，则不启动。
            dnd: undefined,
            // {Selector} [可选] [默认值：false] 是否禁掉整个页面的拖拽功能，如果不禁用，图片拖进来的时候会默认被浏览器打开。
            disableGlobalDnd: false,
            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick: "#" + fu.pickerId,
            // {Boolean} [可选] [默认值：false] 设置为 true 后，不需要手动调用上传，有文件选择即开始上传。
            auto: true,
            // {Boolean} [可选] [默认值：false] 是否允许在文件传输时提前把下一个文件准备好。 对于一个文件的准备工作比较耗时，比如图片压缩，md5序列化。 如果能提前在当前文件传输期处理，可以节省总体耗时。
            prepareNextFile: false,
            // {Boolean} [可选] [默认值：false] 是否要分片处理大文件上传。
            chunked: true,
            //  {Boolean} [可选] [默认值：5242880] 如果要分片，分多大一片？ 默认大小为5M.
            chunkSize: fu.configuration.chunkSize,
            // {Boolean} [可选] [默认值：2] 如果某个分片由于网络问题出错，允许自动重传多少次？
            chunkRetry: 3,
            // {Object} [可选] [默认值：{}] 文件上传请求的参数表，每次发送都会发送此对象中的参数。
            formData: {
              configurationKey: fu.parent.configurationKey,
              appName: _this.appName,
            },
            // swf文件路径
            swf: "webuploader/Uploader.swf",
            // 文件接收服务端。
            server: _this.adornUrl("fileUpload/uploadReview"),
          };
          // {Arroy} [可选] [默认值：null] 指定接受哪些类型的文件。 由于目前还有ext转mimeType表，所以这里需要分开指定。
          if (fu.configuration.accept !== undefined) {
            var acceptArr = fu.configuration.accept.split("|");
            if (acceptArr.length == 3) {
              option.accept = {
                title: acceptArr[0],
                extensions: acceptArr[1],
                mimeTypes: acceptArr[2],
              };
            }
          }
          // compress {Object} [可选] 配置压缩的图片的选项。如果此选项为false, 则图片在上传前不进行压缩。
          if (fu.configuration.enableImageCompress !== undefined && fu.configuration.enableImageCompress === true) {
            option.compress = {};
            if (fu.configuration.compressedImageWidth !== undefined) {
              option.compress.width = fu.configuration.compressedImageWidth;
            }
            if (fu.configuration.compressedImageHeight !== undefined) {
              option.compress.height = fu.configuration.compressedImageHeight;
            }
            if (fu.configuration.compressImageSize !== undefined) {
              option.compress.compressSize = fu.configuration.compressImageSize;
            }
          } else {
            option.compress = false;
          }
          // {Boolean} [可选] [默认值：3] 上传并发数。允许同时最大上传进程数。
          // option.threads = 3
          // {Object} [可选] [默认值：'file'] 设置文件上传域的name。
          // option.fileVal = 'file'
          // {Object} [可选] [默认值：'POST'] 文件上传方式，POST或者GET。
          // option.method = 'POST'
          // {Object} [可选] [默认值：false] 是否已二进制的流的方式发送文件，这样整个上传内容php://input都为文件内容， 其他参数在$_GET数组中。
          // option.sendAsBinary = false
          // {int} [可选] [默认值：undefined] 验证文件总数量, 超出则不允许加入队列。
          if (fu.configuration.fileNumLimit !== undefined) {
            option.fileNumLimit = fu.configuration.fileNumLimit;
          }
          // {int} [可选] [默认值：undefined] 验证文件总大小是否超出限制, 超出则不允许加入队列。
          if (fu.configuration.fileSizeLimit !== undefined) {
            option.fileSizeLimit = fu.configuration.fileSizeLimit;
          }
          // {int} [可选] [默认值：undefined] 验证单个文件大小是否超出限制, 超出则不允许加入队列。
          if (fu.configuration.fileSingleSizeLimit !== undefined) {
            option.fileSingleSizeLimit = fu.configuration.fileSingleSizeLimit;
          }
          // {Boolean} [可选] [默认值：undefined] 去重， 根据文件名字、文件大小和最后修改时间来生成hash Key。
          option.duplicate = false;
          //  {String, Array} [可选] [默认值：undefined] 默认所有 Uploader.register 了的 widget 都会被加载，如果禁用某一部分，请通过此 option 指定黑名单。
          // option.disableWidgets
          var uploader = WebUploader.create(option);
          this.webUploader = uploader;
          _this.webUploader = uploader;
          uploader.fileUploader = fu;
          // 当有文件被加入队列之前触发
          uploader.on("beforeFileQueued", function (file) {
            if (fu.configuration.fileNumLimit !== undefined) {
              if (fu.files.length + 1 > fu.configuration.fileNumLimit) {
                fu.events.error("Q_EXCEED_NUM_LIMIT");
                return false;
              }
            }
            if (fu.configuration.fileSingleSizeLimit !== undefined) {
              if (file.size > fu.configuration.fileSingleSizeLimit) {
                fu.events.error("Q_EXCEED_SINGLE_SIZE_LIMIT");
                return false;
              }
            }
            if (fu.configuration.fileSizeLimit !== undefined) {
              if (fu.configuration.fileSizeLimit < fu.totalSize + file.size) {
                fu.events.error("Q_EXCEED_SIZE_LIMIT");
                return false;
              }
            }
            if (this.options.accept != null) {
              if (this.options.accept.extensions != null) {
                var extensions = this.options.accept.extensions.split(",");
                if (extensions.index(file.ext) < 0) {
                  fu.events.error("Q_TYPE_DENIED");
                  return false;
                }
              }
            }
            var handler = true;
            file.yfId = fu.getUuid();
            file.formId = fu.parent.formId;
            file.isOwnFile = true;
            file.fileName = file.name;
            file.fileSize = file.size;
            file.fileSizeText = fu.getFileSizeText(file.fileSize);
            file.webUploader = fu;
            file.download = function () {
              this.webUploader.downloadFile(this);
            };
            file.delete = function () {
              this.webUploader.deleteFile(this);
            };
            file.getDownloadUrl = function () {
              return this.webUploader.getDownloadFileUrl(this);
            };
            file.getPreviewUrl = function () {
              return this.webUploader.getPreviewUrl(this);
            };
            file.getThumbnailUrl = function () {
              return this.webUploader.getThumbnailUrl(this);
            };
            file.secretLevel = _this.secretLevel;
            file.secretLevelText = fu.getSecretLevelText(file.secretLevel);
            fu.files.push(file);
            fu.totalSize = file.size;
            if (fu.events.fileAdded !== undefined) {
              fu.events.fileAdded(file);
            }
            if (fu.events.spaceAllocating !== undefined) {
              fu.events.spaceAllocating(file);
            }
            $.ajax({
              file: file,
              contentType: "application/json;charset=utf-8",
              type: "post",
              async: false,
              url: _this.adornUrl("fileRepository/allocateSpace"),
              data: JSON.stringify({
                fileName: file.name,
                formId: file.formId,
                secretLevel: file.secretLevel,
                md5: file.md5 === undefined ? "" : file.md5,
                contentType: file.type,
                fileSize: file.size,
                chunks: file.chunks === undefined ? 1 : file.chunks,
                yfId: file.yfId,
                configurationKey: fu.parent.configurationKey,
                appName: _this.appName,
              }),
              success: function (data) {
                if (data && data.code === 40000) {
                  this.file.yfId = data.id;
                  if (data.spaceNeedWarn == 1) {
                    _this.$message({
                      message: "当前存储已超过预警阀值，请管理员检查存储空间",
                      type: "warning",
                      duration: 1500,
                    });
                  }
                  if (fu.events.spaceAllocated != null) {
                    fu.events.spaceAllocated(this.file);
                  }
                } else {
                  _this.$alert("分配空间错误：" + data.msg, "上传文件错误提示", {
                    confirmButtonText: "确定",
                  });
                  if (fu.events.spaceAllocateError != null) {
                    fu.events.spaceAllocateError(this.file, data.code, data.msg);
                  }
                  handler = false;
                }
              },
            });
            return handler;
          });

          // 当有文件添加进来的时候
          uploader.on("fileQueued", function (file) {});

          // 文件上传过程中创建进度条实时显示。
          uploader.on("uploadProgress", function (file, percentage) {
            if (fu.events.uploadProgress !== undefined) {
              fu.events.uploadProgress(file, percentage);
            }
          });

          uploader.on("uploadSuccess", function (file, response) {
            file.exists = true;
            //上传成功返回的  needReview  如果不存在，则设置为0
            if (response.needReview) {
              file.needReview = response.needReview;
            }
            //code!==40000 处理
            if (response.code !== 40000 && fu.events.uploadError) {
              fu.events.uploadError(file, response);
            } else {
              file.response = response;
              if (fu.events.uploadSuccess !== undefined) {
                fu.events.uploadSuccess(file, response);
              }
            }
          });

          uploader.on("uploadError", function (file, reason) {
            if (fu.events.uploadError !== undefined) {
              fu.events.uploadError(file, reason);
            }
          });

          uploader.on("uploadComplete", function (file) {
            if (fu.events.uploadComplete !== undefined) {
              fu.events.uploadComplete(file);
            }
          });

          uploader.on("uploadFinished", function () {
            this.reset();
            if (fu.events.uploadFinished !== undefined) {
              fu.events.uploadFinished();
            }
          });

          uploader.on("uploadBeforeSend", function (obj, data, header) {
            data.yfId = obj.file.yfId;
            data.configurationKey = this.fileUploader.parent.configurationKey;
          });

          uploader.on("error", function (type) {
            if (fu.events.error !== undefined) {
              fu.events.error(type);
            }
          });

          this.webUploaderInitializing = false;
          if (this.onWebUploaderInitialized) {
            this.onWebUploaderInitialized();
          }
        },
        getFileSizeText: function (fileSize) {
          var str = fileSize + "B";
          if (fileSize > 1073741824) {
            str = (((fileSize / 1024 / 1024 / 1024) * 100) / 100).toFixed(2) + "GB";
          } else if (fileSize > 1048576) {
            str = (((fileSize / 1024 / 1024) * 100) / 100).toFixed(2) + "MB";
          } else if (fileSize > 1024) {
            str = (((fileSize / 1024) * 100) / 100).toFixed(2) + "KB";
          }
          return str;
        },
        getSecretLevelText: function (secretLevel) {
          for (var i = 0; i < this.secretLevels.length; i++) {
            var t = this.secretLevels[i];
            if (t.value == secretLevel) {
              return t.name;
            }
          }
          return "未知";
        },
        downloadZipped: function () {
          var fu = this;
          _this.$http({
              method: "get",
              url: _this.adornUrl("fileInfo/getFileCountByFormId", "configurationKey=" + fu.parent.configurationKey + "&formId=" + fu.parent.formId),
            })
            .then(({ data }) => {
              if (data && data.code === 40000) {
                if (data.count > 0) {
                  window.open(_this.adornUrl("fileDownload/downloadZipped", "configurationKey=" + fu.parent.configurationKey + "&downloadToken=" + fu.downloadToken), "_blank");
                } else {
                  if (fu.events.error != null) {
                    fu.events.error("NO_FILES");
                  }
                }
              }
            });
          //   $.ajax({
          //     type: 'get',
          //     url: _this.adornUrl(
          //       'fileInfo/getFileCountByFormId',
          //       'configurationKey=' +
          //         fu.parent.configurationKey +
          //         '&formId=' +
          //         fu.parent.formId
          //     ),
          //     success: function (data) {
          //       if (data && data.code === 40000) {
          //         if (data.count > 0) {
          //           window.open(
          //             _this.adornUrl(
          //               'fileDownload/downloadZipped',
          //               'configurationKey=' +
          //                 fu.parent.configurationKey +
          //                 '&downloadToken=' +
          //                 fu.downloadToken
          //             ),
          //             '_blank'
          //           )
          //         } else {
          //           if (fu.events.error != null) {
          //             fu.events.error('NO_FILES')
          //           }
          //         }
          //       }
          //     },
          //   })
        },
        setAllowUpload: function (val) {
          var fu = this;
          fu.parent.allowUpload = val;
          var picker = document.getElementById(fu.pickerId);
          var selSecretLevel = document.getElementById(fu.parent.targetId + "-secret-level");
          if (val) {
            if (picker != null) {
              picker.className = "webuploader-pick-allow-upload";
            }
            fu.destroy();
            fu.initWebUploader();
            // 重置密级控件样式
            if (selSecretLevel != null) {
              selSecretLevel.className = "select-secret-level";
            }
          } else {
            if (picker != null) {
              picker.className = "webuploader-pick-not-allow-upload";
            }
            fu.destroy();
            // 重置密级控件样式
            if (selSecretLevel != null) {
              selSecretLevel.className = "select-secret-level-not-allow-upload";
            }
          }
          if (fu.events.allowUploadChanged !== undefined) {
            fu.events.allowUploadChanged(val);
          }
        },
        setAllowDelete: function (val) {
          this.parent.allowDelete = val;
          if (this.events.allowDeleteChanged !== undefined) {
            this.events.allowDeleteChanged(val);
          }
        },
        setAllowDownload: function (val) {
          const fu = this;
          this.parent.allowDownload = val;
          var btnDownloadZipped = document.getElementById(fu.parent.targetId + "-download-zipped");
          if (val) {
            // 重置打包下载按钮样式
            if (btnDownloadZipped != null) {
              btnDownloadZipped.className = "btn-download-zipped";
            }
          } else {
            // 重置打包下载按钮样式
            if (btnDownloadZipped != null) {
              btnDownloadZipped.className = "btn-download-zipped-not-allow-download";
            }
          }
          if (this.events.allowDownloadChanged !== undefined) {
            this.events.allowDownloadChanged(val);
          }
        },
        setMaxSecretLevel: function (val) {
          //   console.log(this.parent.maxSecretLevel);

          this.parent.maxSecretLevel = val;
          this.initSecretLevelSelect();
        },
        isAllowUpload: function () {
          return this.parent.allowUpload && this.configuration.allowUpload && _this.uploadAuth;
        },
        isAllowDelete: function () {
          return this.parent.allowDelete && this.configuration.allowDelete && _this.deleteAuth;
        },
        isAllowDownload: function () {
          return this.parent.allowDownload && this.configuration.allowDownload && _this.downloadAuth;
        },
        deleteFile: function (file) {
          if (this.isAllowDelete()) {
            if (this.events.fileDeleting != null) {
              this.events.fileDeleting(file);
            }
            try {
              this.webUploader.cancelFile(file);
            } catch (e) {
              console.error("删除文件错误", e);
            }
            for (var i = 0; i < this.files.length; i++) {
              var f = this.files[i];
              if (f.id == file.id) {
                this.files.splice(i, 1);
                this.totalSize -= f.fileSize;
                break;
              }
            }
            var fileDeleting = file;
            //var fileDeleted = this.events.fileDeleted;
            var fileDeleteError = this.events.fileDeleteError;
            // 根据file的状态判断是否需要通过远端删除
            if (file.exists) {
              _this
                .$http({
                  method: "post",
                  url: _this.adornUrl("fileInfo/deleteByFileId"),
                  data: {
                    configurationKey: this.parent.configurationKey,
                    fileId: file.yfId,
                    appName: _this.appName,
                  },
                })
                .then(({ data }) => {
                  if (data && data.code === 40000) {
                    _this.fileDeleted(fileDeleting);
                  } else {
                    _this.fileDeleteError(fileDeleting, data.code, data.msg);
                  }
                });
              //   $.ajax({
              //     contentType: 'application/json;charset=utf-8',
              //     type: 'post',
              //     url: _this.adornUrl('fileInfo/deleteByFileId'),
              //     data: JSON.stringify({
              //       configurationKey: this.parent.configurationKey,
              //       fileId: file.yfId,
              //       appName: getAppName(),
              //     }),
              //     success: function (data) {
              //       if (data && data.code === 40000) {
              //         _this.fileDeleted(fileDeleting)
              //       } else {
              //         _this.fileDeleteError(fileDeleting, data.code, data.msg)
              //       }
              //     },
              //   })
            } else {
              _this.fileDeleted(fileDeleting);
            }
          }
        },
        load: function () {
          //加载完毕置为 false ,这个时候将 DOM 元素隐藏，避免报错

          var fu = this;
          if (fu.loading) {
            fu.onLoaded(fu.doLoad);
          } else {
            fu.doLoad();
          }
        },
        doLoad: function () {
          var fu = this;
          fu.loading = true;
          var div = document.getElementById(this.parent.targetId);
          if (div == null) {
            // alert('目标div不存在');
            return;
          }
          div.innerText = "";
          div.fileUploader = this;
          _this
            .$http({
              method: "post",
              url: _this.adornUrl("fileConfiguration/load"),
              data: {
                configurationKey: this.parent.configurationKey,
                formId: this.parent.formId,
                appName: _this.appName,
              },
            })
            .then(({ data }) => {
              if (data && data.code === 40000) {
                //获取到已经上传的文件
                /**
                 * 先判断附件配置中是否开启了密级
                 */
                if (data.fileConfiguration.enableSecretLevel === 1) {
                  _this.initSecretLevelsByMaxSecretLevel(data.secretLevels, _this.maxSecretLevel);
                  //存放在原始秘籍 方便后期最大秘籍改变时使用
                  _this.originalSecretLevels = data.secretLevels;
                  //设置默认密级
                  _this.secretLevel = _this.defaultSecretLevel !== 0 ? _this.defaultSecretLevel : data.secretLevels[0].value;
                  //这里需要获取当前用户密级
                  try {
                    let userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
                    if (userInfo) {
                      _this.userSecretLevel = userInfo.user.secretLevel;
                      _this.files = data.fileInfos.filter((fileInfo) => fileInfo.secretLevel >= _this.userSecretLevel);
                      //新增文件删除文件等操作会对fu.files进行操作
                      fu.files = _this.files;
                    } else {
                      throw new Error("没有获取到用户信息");
                    }
                  } catch (e) {
                    //   console.log("附件上传组件无法获取到当前用户的信息，因此系统无法正确加载此组件。");
                    _this.$alert("附件上传中没有获取到当前用户的信息，因此系统无法正确加载此组件。", "附件上传", {
                      type: "error",
                    });
                    return false;
                  }
                } else {
                  _this.files = data.fileInfos;
                  fu.files = _this.files;
                }

                //判断是否开启了附件审查
                if (data.fileConfiguration.enableReview) {
                  //判断是否含有未审查的文件
                  _this.showReviewBtn = _this.hasUnapprovedFiles(data.fileInfos);
                }
                //h获取到最大文件预览大小
                _this.maxPreviewSize = data.fileConfiguration.maxPreviewSize;
                fu.secretLevels = data.secretLevels;
                fu.downloadToken = data.downloadToken;
                fu.initLayout(data.fileConfiguration, _this.files, data.secretLevels);
              } else {
                if (fu.events.initError !== undefined) {
                  fu.events.initError(data.code, data.msg);
                }
              }

              fu.loading = false;
              _this.loadingComplete = true;
              if (fu.onLoaded) {
                fu.onLoaded();
              }
            });
        },
        // initSecretLevelSelect: function () {
        //   if (this.secretLevelSelect !== undefined) {
        //     this.secretLevelSelect.options.length = 0
        //     if (this.secretLevels !== undefined || this.secretLevels != null) {
        //       for (var j = 0; j < this.secretLevels.length; j++) {
        //         var item = this.secretLevels[j]
        //         if (this.parent.maxSecretLevel !== undefined) {
        //           if (this.parent.maxSecretLevel > item.value) {
        //             continue
        //           }
        //         }
        //         var opt = document.createElement('option')
        //         opt.value = item.value
        //         opt.text = item.name
        //         this.secretLevelSelect.add(opt)
        //       }
        //     }
        //   }
        // },
        initLayout: function (config, fileInfos, secretLevels) {
          var div = document.getElementById(this.parent.targetId);
          this.configuration = {
            accept: config.accept,
            fileNumLimit: config.fileNumLimit,
            fileSingleSizeLimit: config.fileSingleSizeLimit,
            fileSizeLimit: config.fileSizeLimit,
            enableSecretLevel: config.enableSecretLevel === 1,
            allowUpload: config.allowUpload === 1,
            allowDelete: config.allowDelete === 1,
            allowDownload: config.allowDownload === 1,
            uploadOperationKey: config.uploadOperationKey,
            deleteOperationKey: config.deleteOperationKey,
            downloadOperationKey: config.downloadOperationKey,
            enableUserSeparate: config.enableUserSeparate === 1,
            enableImageCompress: config.enableImageCompress === 1,
            compressedImageWidth: config.compressedImageWidth,
            compressedImageHeight: config.compressedImageHeight,
            compressImageSize: config.compressImageSize,
            enablePreview: config.enablePreview === 1,
            enableReview: config.enableReview === 1,
            chunkSize: config.chunkSize,
          };
          _this.enableReview = config.enableReview === 1;
          _this.configuration = this.configuration;
          div.className = "custom-uploader";
          div.innerHTML = "";
          var divToolbar = document.createElement("div");
          divToolbar.className = "toolbar";
          // 密级选择
          // var secretLevelSelect = document.createElement('select');
          // secretLevelSelect.id = div.id + '-secret-level';
          // secretLevelSelect.className = this.isAllowUpload() && this.configuration.enableSecretLevel ? 'select-secret-level' : 'select-secret-level-not-allow-upload';
          // this.secretLevelSelect = secretLevelSelect;
          // divToolbar.appendChild(secretLevelSelect);
          // this.initSecretLevelSelect();
          // 选文件按钮
          var btnPicker = document.createElement("div");
          this.picker = btnPicker;
          btnPicker.id = this.pickerId;
          btnPicker.className = `el-button el-button--primary el-button--${_this.size} select-file`;
          btnPicker.innerHTML = `选择文件`;
          divToolbar.appendChild(btnPicker);
          // 打包下载按钮
          /*var btnDownloadZipped = document.createElement('button');
                                    btnDownloadZipped.type = 'button';
                                    btnDownloadZipped.id = div.id + '-download-zipped';
                                    btnDownloadZipped.webUploader = this;
                                    btnDownloadZipped.className = this.isAllowDownload() ? 'btn-download-zipped el-button el-button--primary el-button--small is-plain download-file' : 'btn-download-zipped-not-allow-download el-button el-button--primary el-button--small is-plain download-file';
                                    btnDownloadZipped.innerHTML = '打包下载';
                                    btnDownloadZipped.addEventListener('click', function () {
                                        this.webUploader.downloadZipped();
                                    });*/
          // divToolbar.appendChild(btnDownloadZipped);
          div.appendChild(divToolbar);
          if (this.isAllowUpload()) {
            this.initWebUploader();
          } else {
            btnPicker.className = "webuploader-pick-not-allow-upload";
          }
          this.totalSize = 0;
          for (var i = 0; i < fileInfos.length; i++) {
            var file = fileInfos[i];
            this.totalSize += file.fileSize;
            file.yfId = file.id;
            file.webUploader = this;
            file.fileSizeText = this.getFileSizeText(file.fileSize);
            file.secretLevelText = this.getSecretLevelText(file.secretLevel);
            file.download = function () {
              this.webUploader.downloadFile(this);
            };
            file.delete = function () {
              this.webUploader.deleteFile(this);
            };
            file.getDownloadUrl = function () {
              return this.webUploader.getDownloadFileUrl(this);
            };
            file.getPreviewUrl = function () {
              return this.webUploader.getPreviewUrl(this);
            };
            file.getThumbnailUrl = function () {
              return this.webUploader.getThumbnailUrl(this);
            };
            file.exists = true;
          }
          // _this.files = fileInfos;
          if (this.events.initSuccess != null) {
            this.events.initSuccess(this, _this.files, secretLevels, this.configuration);
          }
        },
        getDownloadFileUrl: function (file) {
          return _this.adornUrl("fileDownload/download", "configurationKey=" + encodeURI(this.parent.configurationKey) + "&fileToken=" + file.yfId);
        },
        getPreviewUrl: function (file) {
          return _this.adornUrl("fileDownload/preview", "configurationKey=" + encodeURI(this.parent.configurationKey) + "&fileToken=" + file.yfId);
        },
        getThumbnailUrl: function (file) {
          return _this.adornUrl("fileDownload/download", "configurationKey=" + encodeURI(this.parent.configurationKey) + "&fileToken=" + file.yfId + "&t=1");
        },
        downloadFile: function (file) {
          if (this.isAllowDownload()) {
            window.open(this.getDownloadFileUrl(file), "_blank");
          }
        },
        destroy: function () {
          if (this.webUploader != null) {
            try {
              this.webUploader.destroy();
            } catch (e) {
              //   console.log("上传组件销毁出错", e);
            }
          }
        },
      };
      fileUploader.pickerId = fileUploader.getUuid();
      _this.pickerId = fileUploader.pickerId;
      fileUploader.load();
      return fileUploader;
    },
  },
  beforeDestroy() {
    if (this.fileUploader != null) {
      if (this.fileUploader.webUploader != null) {
        try {
          this.fileUploader.webUploader.stop(true);
        } catch (e) {
          //   console.log("上传组件销毁前停止报错", e);
        }
      }
    }
  },
};
</script>
<style lang="scss">
//packages\ace-ui-web\
@import "../../../../theme-chalk/src/scss/mixi.scss";
.ace-upload-box {
  .ace-upload-secretLevel-selector {
    margin-right: 16px;
    width: 120px;
  }
  .el-divider--vertical {
    line-height: 32px;
    height: 20px;
    margin: 6px 16px 0 16px;
  }
  .select-secret-level {
  }
  .initiating-process {
  }
  .upper-box {
    display: flex;
  }
  .lower-box {
    font-size: 12px;
    color: #909399;
  }
  .operation-box {
    display: flex;
  }
  .custom-uploader {
    .webuploader-container {
      position: relative;
    }
    .webuploader-element-invisible {
      position: absolute !important;
      clip: rect(1px 1px 1px 1px);
      /* IE6, IE7 */
      clip: rect(1px, 1px, 1px, 1px);
    }
    .webuploader-pick-disable {
      opacity: 0.6;
      pointer-events: none;
    }
    .toolbar {
      display: flex;
      align-items: center;
      div.webuploader-pick + div {
        width: 100% !important;
        height: 100% !important;
        top: 0 !important;
        left: 0 !important;
      }
    }
    /*.select-secret-level {*/
    /*    position: relative;*/
    /*    -webkit-appearance: none;*/
    /*    background-color: #fff;*/
    /*    background-image: none;*/
    /*    border-radius: 4px;*/
    /*    border: 1px solid #dcdfe6;*/
    /*    box-sizing: border-box;*/
    /*    color: #606266;*/
    /*    display: inline-block;*/
    /*    font-size: inherit;*/
    /*    height: 32px;*/
    /*    line-height: 32px;*/
    /*    outline: none;*/
    /*    padding: 0 15px;*/
    /*    transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);*/
    /*    width: 125px;*/
    /*    margin-right: 10px;*/
    /*}*/
    //禁止上传
    .select-secret-level-not-allow-upload {
      display: none;
    }
    .webuploader-pick-not-allow-upload {
      display: none;
    }
    .btn-download-zipped-not-allow-download {
      display: none;
    }
    .custom-dark {
      .custom-uploader {
        .toolbar {
          background-color: $dark--bg--color;
        }
        .select-file {
          color: #eee;
        }
        .download-file {
          color: #eee;
        }
      }
    }
  }
}

.custom-dark {
  .custom-uploader {
    .toolbar {
      background-color: transparent;
    }
    .select-file {
      color: $dark-common-color;
    }
    .download-file {
      color: $dark-common-color;
    }
  }
  .dark-select {
    background-color: $dark--bg--color;
    color: $dark-common-color;
  }
}
</style>
