import { treeScollx } from "@base/utils/global.js";
import ElImageViewer from "@base/components/VabUpload/image-viewer";
import propertiesDialog from "@base/components/fileLibrary/propertiesDialog";
import categoryMoveDialog from "@base/components/fileLibrary/categoryMoveDialog";
import fileHistoryDialog from "@base/components/fileLibrary/fileHistoryDialog";
import shareDialog from "@base/components/fileLibrary/shareDialog";
import recycleBinDialog from "@base/components/fileLibrary/recycleBinDialog";
import videoDialog from "@base/components/video/dialog";
import userDialog from "@base/views/user/user/dialog";
import { encode } from "js-base64";
import fileObjAuthDialog from "@base/components/fileLibrary/fileObjAuthDialog";
import filterDialog from "@base/components/fileLibrary/filterDialog.vue";

let modules;
modules = {
  props: {
    option: {
      type: Object,
    },
  },
  components: {
    ElImageViewer,
    propertiesDialog,
    categoryMoveDialog,
    fileHistoryDialog,
    shareDialog,
    recycleBinDialog,
    videoDialog,
    userDialog,
    fileObjAuthDialog,
    filterDialog,
  },
  provide() {
    return {
      current_prefix: this.current_prefix,
      storeAreaCode: this.storeAreaCode,
      billConfig: this.billConfig,
      isBillEnabled: this.isBillEnabled,
      billRowField: this.billRowField,
      billDialogParam: this.billDialogParam,
      dataId: this.dataId,
      getTitle: () => {
        return this.title;
      },
      getIsPrivate: () => {
        return this.isPrivate;
      },
      getObjectForeignId: () => {
        return this.objectForeignId;
      },
      getFileStoreArea: () => {
        return this.fileStoreArea;
      },
    };
  },
  async created() {
    if (this.isPrivate) {
      await this.getCurrentUser();
    }
  },
  mounted() {
    //初始化单据弹框
    if (this.isBillEnabled) {
      this.billDialogContent = this.billConfig.billDialog;
    }

    this.initTitle();
    this.initTableList();
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  data() {
    let pageSize = 1000;
    let categoryPageSize = 1000;
    return {
      showBillDialog: false,
      billDialogContent: null,
      checkBillDatas: [],
      title: "",
      fileStoreArea: {},
      folderStatus: false,
      filterText: "",
      defaultProps: {
        children: "children",
        label: "fileName",
        isLeaf: "leaf",
      },
      resolveFunc: function () {},
      fileAttachmentCategorys: [],
      currentFileCategoryCode: null,
      chooseIndex: -1,
      imageDTOs: [],
      showViewer: false,
      showPropertiesDialog: false,
      editAttachment: null,
      vxeOption: {},
      showType: 1,
      formData: {},
      showAdvancedSearch: false,
      advancedFormData: {},
      pageSize: pageSize,
      page: {
        current: 1,
        size: pageSize,
        total: 0,
        records: [],
      },
      categoryPageSize: categoryPageSize,
      categoryPage: {
        current: 1,
        size: categoryPageSize,
        total: 0,
        records: [],
      },
      showEditCategoryDialog: false,
      editCategory: {},
      currentFileCategory: null,
      rootCategory: false,
      currentNode: null,
      treeNodeArr: [],
      checkRows: [],
      showCategoryMoveDialog: false,
      checkList: [],
      handleType: 1, //1移动，2复制
      showFileHistoryDialog: false,
      operateFileHistory: null,
      showShareDialog: false,
      shareAttachment: null,
      checkAll: false,
      fileArr: [],
      checkList2: [],
      showRecycleBinDialog: false,

      showVideoDialog: false,
      videoOption: null,

      //个人文档
      userInfo: {
        id: null,
        nickName: null,
      },
      treeFlag: false,
      currentUser: {},
      showUserDialog: false,
      isDocAdmin: false,

      //圈选
      is_show_mask: false,
      box_screen_left: 0,
      box_screen_top: 0,
      start_x: 0,
      start_y: 0,
      end_x: 0,
      end_y: 0,
      scrollTop1: 0,
      scrollTop2: 0,
      showFileObjAuthDialog: false,
      fileObjAuth: {},
      popAnnexFilter: false,
      showFilterDialog: false,
    };
  },
  computed: {
    isEdit() {
      //默认可编辑
      return this.option.isEdit !== false ? true : false;
    },
    isCategoryEdit() {
      if (this.isEdit === false) {
        return false;
      }
      //文件夹默认不可编辑
      return this.option.isCategoryEdit === true ? true : false;
    },
    mouseCheck() {
      //鼠标框选默认不开启
      return this.option.mouseCheck === true ? true : false;
    },
    dataId() {
      // return this.option.dataId;
      let dataId = this.isBillEnabled
        ? this.checkBillDatas.map((row) => row.id)
        : this.option.dataId
        ? [this.option.dataId]
        : [0];
      return dataId;
    },
    objectForeignId() {
      if (this.option.private) {
        return [this.userInfo.id || 0];
      } else {
        return this.dataId && this.dataId.length ? this.dataId : [0];
      }
    },
    current_prefix() {
      return this.option.current_prefix;
    },
    storeAreaCode() {
      return this.option.storeAreaCode;
    },
    pictureDtoList() {
      return this.page.records.filter((row) => {
        return row.url && this.$commonFileUtil.isPictureFile(row.url);
      });
    },
    //圈选
    getMaskStyle: function () {
      return this.getStyle();
    },
    checkAllDisabled() {
      return this.page.records.length == 0;
    },
    checkAllIndeterminate() {
      return (
        this.checkList.length > 0 &&
        this.checkList.length < this.page.records.length
      );
    },
    billConfig() {
      return this.option.billConfig || {};
    },
    billRowField() {
      let billConfig = this.billConfig;
      return billConfig.rowField || "id";
    },
    isBillEnabled() {
      return this.billConfig.enabled || false;
    },
    billDialogParam() {
      if (this.isBillEnabled && this.billConfig.billDialogParam) {
        return this.billConfig.billDialogParam();
      }
    },
    checkBillNames: {
      get() {
        let dataProps = this.billConfig.dataProps;
        return this.checkBillDatas
          .map((row) => {
            return row[dataProps.label];
          })
          .join(",");
      },
      set(val) {
        if (!val) {
          this.checkBillDatas = [];
        }
      },
    },
    isPrivate() {
      return this.option.private || false;
    },
    currentCategoryId() {
      return this.currentFileCategory &&
        this.currentFileCategory.id &&
        this.currentFileCategory.id > 0
        ? this.currentFileCategory.id
        : 0;
    },
    customFileButtons() {
      let buttonConfig = this.option.buttonConfig || {};
      return buttonConfig && buttonConfig.file ? buttonConfig.file : [];
    },
    customToobarButtons() {
      let buttonConfig = this.option.buttonConfig || {};
      return buttonConfig && buttonConfig.toobar ? buttonConfig.toobar : [];
    },
  },
  methods: {
    openFileDirs(row) {
      let keys = row.treePath.split(",").filter((item) => !!item);
      if(row.dirs){
        keys.push(row.id + "")
      }
      let size = keys.length;
      let tree = this.$refs.tree;

      let parent = null;
      let loopDo = (index) => {
        if (size <= index) return;
        let key = keys[index];
        let node = tree.getNode(key + "");
        let data = node.data;
        if (size == index + 1) {
          tree.setCurrentKey(data);
          this.handleNodeClick(data, node, this);
          return;
        }

        if (!data.leaf) {
          node.expand(() => {
            loopDo(index + 1);
          });
        }
      };
      this.getTopNode().expand(() => {
        loopDo(0);
      });
    },
    getTopNode() {
      return this.$refs.tree.root.childNodes[0];
    },
    getFileName(row) {
      if (row.extension) {
        let index = row.fileName.lastIndexOf("." + row.extension);
        return row.fileName.substring(0, index);
      } else {
        return row.fileName;
      }
    },
    openShareDialog(shareAttachment) {
      this.showShareDialog = true;
      this.shareAttachment = shareAttachment;
    },
    getCheckRows() {
      let checkRows = [];
      if (this.showType == 1) {
        let checkList = this.checkList;
        checkRows = this.page.records.filter((row) =>
          checkList.includes(row.id)
        );
      } else {
        checkRows = this.$refs["table-m1"].getCheckboxRecords(true);
      }
      return checkRows;
    },
    getRows() {
      let rows = [];
      if (this.showType == 1) {
        rows = this.page.records;
      } else {
        rows = this.$refs["table-m1"].getTableData().fullData;
      }
      return rows;
    },
    openCategoryMoveDialog(handleType) {
      let checkRows = this.getCheckRows();
      if (!checkRows.length) {
        let msg =
          handleType == 1
            ? this.$t2("请选择需要移动的文件", "components.fileLibrary.moveTip")
            : this.$t2(
                "请选择需要复制的文件",
                "components.fileLibrary.copyTip"
              );
        this.$message({
          message: msg,
          type: "error",
          showClose: true,
          duration: 3000,
        });
        return;
      }

      this.checkRows = checkRows;
      this.handleType = handleType;
      this.showCategoryMoveDialog = true;
    },
    confirmMoveDialog(chooseCategory, categoryArr) {
      /*handleType: 1,//1移动，2复制*/

      let $tree = this.$refs.tree;
      if (!chooseCategory.id) {
        this.currentFileCategory = null;
        let node1 = this.getTopNode();
        let node2 = node1.parent;
        node2.loadData();
      } else {
        if (this.handleType == 1) {
          this.checkRows.filter((item) => {
            if (item.dirs) {
              $tree.remove(item);
            }
          });
        }

        for (let i = 0; i < categoryArr.length; i++) {
          let category = categoryArr[i];
          let node = $tree.getNode(category.id + "");
          if (node) {
            node.expanded = true;
          }
        }

        let cIndex = 0;
        let loopDo = () => {
          let category = categoryArr[cIndex];
          let node = $tree.getNode(category.id + "");
          if (cIndex == 0) {
            if (node) {
              this.$refs.tree.setCurrentKey(node.data);
              this.handleNodeClick(node.data, node, this);
              node.childNodes = [];
              this.loadNode(node, node.resolve);
            } else {
              cIndex = cIndex + 1;
              loopDo();
            }
          } else {
            if (node) {
              this.loadNode(node, node.resolve, () => {
                cIndex = cIndex - 1;
                loopDo();
              });
            } else {
              cIndex = cIndex + 1;
              loopDo();
            }
          }
        };
        loopDo();
      }
    },
    deleteCategory(category) {
      if (!category && !this.currentCategoryId) {
        this.$message({
          message: this.$t2(
            "请选择需要删除的文件夹",
            "components.fileLibrary.deleteCategoryTip"
          ),
          type: "error",
          showClose: true,
          duration: 3000,
        });
        return;
      }
      this.$baseConfirm(
        this.$t2(
          "您确定要删除文件夹吗？",
          "components.fileLibrary.deleteCategoryConfirmTip"
        )
      ).then(() => {
        let categoryId = category ? category.id : this.currentCategoryId;
        this.$http({
          method: "post",
          url: this.current_prefix + "/file_obj/setDisable",
          data: [categoryId],
          isLoading: true,
          success: (res) => {
            this.$message({
              message: res.content,
              type: "success",
              duration: 500,
            });
            if (!category) {
              this.$refs.tree.remove(this.currentFileCategory);
              let node = this.getTopNode();
              this.$refs.tree.setCurrentKey(node.data);
              this.handleNodeData(null);
            } else {
              //删除树节点
              this.$refs.tree.remove(category);
            }
            this.searchEvent();
          },
        });
      });
    },
    changeShowType() {
      this.showType = this.showType == 1 ? 2 : 1;
      this.searchEvent();
    },
    changeCategory(row, node) {
      if (!node) {
        node = this.$refs.tree.getNode(row.id + "");
        this.$refs.tree.setCurrentKey(row);
      }
      if (row.id) {
        node.expand();
      }
      this.formData = {};
      this.advancedFormData = {};
      this.handleNodeData(node);
      this.searchEvent();
    },
    searchEvent() {
      this.doSearch();
    },
    resetEvent() {
      this.formData = {};
      this.doSearch();
    },
    doSearch() {
      this.checkList = [];
      this.checkAll = false;
      this.initAttchInfo();
      /*if (this.showType == 1) {
        this.initAttchInfo();
      } else if (this.showType == 2) {
        this.$refs['table-m1'].commitProxy('reload');
      }*/
    },
    openPropertiesDialog(attachment) {
      this.editAttachment = attachment;
      this.showPropertiesDialog = true;
    },
    getShowUrl(attachment, field) {
      if (!field) field = "medium";
      return this.$commonFileUtil.getShowUrl(
        attachment.domain +
          (attachment[field] ? attachment[field] : attachment.url)
      );
    },
    isVideo(fileSuffix) {
      let videoTypes = ["webm", "ogg", "3gp", "mp4"];
      return videoTypes.includes(fileSuffix);
    },
    hasPreview(attachment) {
      let fileSuffix = this.$commonFileUtil.getFileSuffix(attachment.url);
      return (
        this.$commonFileUtil.isPictureFile(attachment.url) ||
        this.$commonFileUtil.isPreviewFile(attachment.url)
      );
    },
    openPreview(attachment) {
      if (this.$commonFileUtil.isPictureFile(attachment.url)) {
        this.imageDTOs = this.pictureDtoList;
        this.chooseIndex = this.pictureDtoList.findIndex(
          (row) => row.id == attachment.id
        );
        this.showViewer = true;
      } else if (this.$commonFileUtil.isPreviewFile(attachment.url)) {
        this.$openFilePreview(attachment);
      }
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.fileName.indexOf(value) !== -1;
    },
    initAttchInfo(page) {
      let defaultPage = {
        current: 1,
        size: this.pageSize,
        total: 0,
        records: [],
      };
      page = page || {
        current: 1,
        size: this.pageSize,
      };

      let parent = this.currentCategoryId;
      this.$commonHttp({
        method: "post",
        url: this.current_prefix + "/file_obj/listPage",
        data: {
          parent: parent,
          objectForeignId: this.objectForeignId,
          privateDir: this.isPrivate ? 1 : 0,
          storeAreaCode: this.storeAreaCode,
          ...this.formData,
          ...this.advancedFormData,
          ...page,
        },
        isLoading: true,
        success: (res) => {
          let page = res.objx ? res.objx : defaultPage;
          let objectForeignId = this.objectForeignId;
          let checkBillDatas = this.checkBillDatas;
          let done = (res) => {
            this.page = res;
          };
          let preHandlePage = this.option.preHandlePage;
          if (preHandlePage) {
            preHandlePage({ page, objectForeignId, checkBillDatas, done });
          } else {
            done(page);
          }
        },
      });
    },
    addFile() {
      let currentFileCategory = this.currentFileCategory;
      if (!currentFileCategory || !currentFileCategory.id) {
        this.$message({
          message: this.$t2(
            "文件夹[" + this.title + "]不允许上传",
            "components.fileLibrary.uploadTip1",
            { title: this.title }
          ),
          type: "error",
          showClose: true,
          duration: 3000,
        });
        return;
      }
      if (this.isBillEnabled) {
        if (!this.checkBillDatas.length) {
          let billName = this.billConfig.name;
          this.$message({
            message: this.$t2(
              "请选择" + billName,
              "components.fileLibrary.uploadTip2",
              { billName: billName }
            ),
            type: "error",
            showClose: true,
            duration: 3000,
          });
          return;
        }
      }
      this.$baseUpload.open({
        limit: 200,
        accept: "file",
        size: 5 * 1024 * 1024 * 1024,
        pickPrivateProfile: false,
        callback: (rows) => {
          this.confirmFileAttachment(rows);
        },
      });
    },
    confirmFileAttachment(rows) {
      let parent = this.currentCategoryId;
      let notes = [];
      let billConfig = this.billConfig;
      if (this.isBillEnabled && billConfig.fileNote) {
        notes = this.checkBillDatas.map((row) => {
          return billConfig.fileNote(row);
        });
      }

      this.$http({
        method: "post",
        url: this.current_prefix + "/file_attach/save",
        data: {
          objectForeignId: this.objectForeignId,
          parent: parent,
          storeAreaCode: this.storeAreaCode,
          fileObjDTOs: rows,
          notes: notes,
        },
        isLoading: true,
        success: (res) => {
          this.$message({
            message: res.content,
            type: "success",
            duration: 500,
          });
          /*let files = res.objx || [];
          this.page.records.push(...files);
          this.page.total = this.page.total + files.length*/
          this.searchEvent();
        },
      });
      return false;
    },
    deleteAttach(attachment) {
      let data = [];
      let categorys = [];
      let checkRows = [];
      if (attachment) {
        if (attachment.status == 1) {
          this.$message({
            message: "归档文件不允许删除",
            type: "error",
            showClose: true,
            duration: 3000,
          });
          return;
        }
        data.push(attachment.id);
        if (attachment.dirs) {
          categorys.push(attachment);
        }
        checkRows = [attachment];
      } else {
        checkRows = this.getCheckRows();
        if (checkRows.find((row) => row.status == 1)) {
          this.$message({
            message: "归档文件不允许删除",
            type: "error",
            showClose: true,
            duration: 3000,
          });
          return;
        }
        data = checkRows.map((row) => row.id);
        categorys = checkRows.filter((row) => row.dirs);
      }
      if (!data.length) {
        this.$message({
          message: this.$t2(
            "请选择需要删除的文件",
            "components.fileLibrary.deleteFileTip"
          ),
          type: "error",
          showClose: true,
          duration: 3000,
        });
        return;
      }

      let deleteDirAuth =
        this.fileObjAuth && this.fileObjAuth.deleteDirAuth ? 1 : 0;
      let deleteAuth = this.fileObjAuth && this.fileObjAuth.deleteAuth ? 1 : 0;
      for (let i = 0; i < checkRows.length; i++) {
        let item = checkRows[i];
        if (item.dirs && !deleteDirAuth) {
          this.$message({
            message: this.$t2(
              "您没有删除文件夹的权限！",
              "components.fileLibrary.deleteCategoryTip2"
            ),
            type: "error",
            showClose: true,
            duration: 3000,
          });
          return;
        } else if (!item.dirs && !deleteAuth) {
          this.$message({
            message: this.$t2(
              "您没有删除文件的权限！",
              "components.fileLibrary.deleteFileTip2"
            ),
            type: "error",
            showClose: true,
            duration: 3000,
          });
          return;
        }
      }

      // let data = [attachment.id];
      this.$baseConfirm(
        this.$t2("您确定要删除吗？", "components.fileLibrary.deleteConfirmTip")
      ).then(() => {
        this.$http({
          method: "post",
          url: this.current_prefix + "/file_obj/setDisable",
          data: data,
          isLoading: true,
          success: (res) => {
            this.$message({
              message: res.content,
              type: "success",
              duration: 500,
            });

            let $tree = this.$refs.tree;
            categorys.forEach((category) => {
              $tree.remove(category);
            });
            this.searchEvent();
          },
        });
      });
    },
    initTableList() {
      let that = this;
      let customColumns = this.option.customColumns
        ? this.option.customColumns()
        : [];
      let tableOption = {
        vue: this,
        tableRef: "table-m1",
        tableName: "user_fileLibrary_list-m1",
        config: {
          height: "auto",
          pagerConfig: {
            autoHidden: false,
            enabled: true,
          },
        },
        columns: [
          { type: "checkbox", width: 48, resizable: false, fixed: "left" },
          {
            title: this.$t2("文件名称", "components.fileLibrary.fileName"),
            field: "fileName",
            width: 250,
            fixed: "left",
            slots: {
              default: ({ row, $rowIndex }) => {
                let h = this.$createElement;
                if (!row.dirs) {
                  let showUrl = that.getShowUrl(row, "thumbnail");
                  return [
                    h(
                      "a",
                      {
                        staticClass: "a-link img",
                        on: {
                          click: (event) => {
                            event.stopPropagation();
                            that.openPreview(row);
                          },
                        },
                      },
                      [
                        h(
                          "el-tooltip",
                          {
                            props: {
                              enterable: false,
                              effect: "dark",
                              content: this.$t2(
                                "预览",
                                "components.fileLibrary.preview"
                              ),
                              placement: "top",
                              "popper-class": "tooltip-skin",
                            },
                          },
                          [
                            h("el-image", {
                              props: {
                                src: showUrl,
                              },
                            }),
                          ]
                        ),
                      ]
                    ),
                    h("span", row.fileName),
                  ];
                } else {
                  return [
                    h(
                      "a",
                      {
                        staticClass: "a-link img",
                        on: {
                          click: (event) => {
                            event.stopPropagation();
                            that.changeCategory(row);
                          },
                        },
                      },
                      [
                        h(
                          "div",
                          {
                            staticClass: "img",
                          },
                          [
                            h("svg-icon", {
                              props: { "icon-class": "ico-wenjianjia" },
                            }),
                            h("span", row.fileName),
                          ]
                        ),
                      ]
                    ),
                  ];
                }
              },
            },
          },
          {
            title: this.$t2("文件大小", "components.fileLibrary.fileSize"),
            field: "fileSize",
            width: 150,
            slots: {
              default: ({ row, $rowIndex }) => {
                if (!row.dirs) {
                  return this.formatFileSize(row.fileSize);
                }
              },
            },
          },
          {
            title: this.$t2("版本号", "components.fileLibrary.fileRev"),
            field: "rev",
            width: 150,
            slots: {
              default: ({ row, $rowIndex }) => {
                if (!row.dirs) {
                  return row.rev;
                }
              },
            },
          },
          {
            title: this.$t2("分辨率", "components.fileLibrary.widthHeight"),
            field: "widthHeight",
            width: 150,
          },
          {
            title: this.$t2("所属对象描述", "components.fileLibrary.note"),
            field: "note",
            width: 250,
          },
          {
            title: "状态",
            field: "status",
            width: 150,
            slots: {
              default: ({ row, $rowIndex }) => {
                if (!row.dirs) {
                  return row.status == 1 ? "已归档" : "未归档";
                }
              },
            },
          },
          {
            title: this.$t2("文件编码", "components.fileLibrary.fileSn"),
            field: "fileSn",
            width: 150,
          },
          ...customColumns,
          {
            title: this.$t2("创建人", "components.fileLibrary.createBy"),
            field: "_createBy",
            width: 150,
          },
          {
            field: "createDate",
            title: this.$t2("创建时间", "components.fileLibrary.createDate"),
            width: 150,
          },
          {
            width: this.isEdit ? 280 : 47,
            fixed: "right",
            title: "",
            sortable: false,
            slots: {
              default: "operate",
            },
          },
        ],
        callback(a, b) {},
      };
      this.$vxeTableUtil.initVxeTable(tableOption).then((opts) => {
        this.vxeOption = opts;
      });
    },
    getCustomButtonNodes(attachment) {
      let customFileButtons = this.customFileButtons;
      let nodes = [];
      customFileButtons.forEach((fileButton, index) => {
        if (
          fileButton.dirs === null ||
          fileButton.dirs === undefined ||
          attachment.dirs === fileButton.dirs
        ) {
          if (this.customFileButtonVisable(fileButton, attachment)) {
            nodes.push(
              this.getBtnVnode({
                class: fileButton.icon,
                title: fileButton.label,
                click: (event) => {
                  that.customFileButtonEvent(fileButton, attachment);
                },
              })
            );
          }
        }
      });
      return nodes;
    },
    getBtnVnode(opt) {
      let h = this.$createElement;
      let show = opt.show === false ? false : true;
      if (show) {
        return h(
          "a",
          {
            staticClass: "a-link",
            on: {
              click: (event) => {
                opt.click && opt.click(event);
              },
            },
          },
          [
            h(
              "el-tooltip",
              {
                props: {
                  enterable: false,
                  effect: "dark",
                  content: opt.title,
                  placement: "top",
                  "popper-class": "tooltip-skin",
                },
              },
              [
                h("i", {
                  staticClass: opt.class,
                }),
              ]
            ),
          ]
        );
      }
    },
    changePageNew({ type, currentPage, pageSize, $event }) {
      this.checkList = [];
      this.checkAll = false;
      this.initAttchInfo({
        current: currentPage,
        size: pageSize,
      });
    },
    changePage(currentPage, pageSize) {
      this.initAttchInfo({
        current: currentPage,
        size: pageSize,
      });
    },
    handleNodeClick(data, node, v) {
      if (!data.moreBtn) {
        this.changeCategory(data, node);
      } else {
        this.showModeCategory(data, node, v);
      }
    },
    doNav(t) {
      let node = this.$refs.tree.getNode(t.data.id + "");
      this.$refs.tree.setCurrentKey(node.data);
      this.handleNodeClick(node.data, node, this);
    },
    showModeCategory(data, node, v) {
      let param = {
        parent: data.parent,
        dirs: true,
        storeAreaCode: this.storeAreaCode,
        size: this.categoryPageSize,
        current: data.next,
      };
      if (this.isPrivate) {
        param.objectForeignId = this.objectForeignId;
        param.privateDir = 1;
      }
      this.$http({
        url: this.current_prefix + "/file_obj/listPage",
        method: "post",
        data: param,
        isLoading: true,
        success: (res) => {
          let page = res.objx;
          let rows = page && page.records ? page.records : [];
          this.$refs.tree.remove(node);
          if (page.pages > page.current) {
            rows.push({
              parent: param.parent,
              fileName: this.$t2("更多", "components.fileLibrary.more"),
              moreBtn: true,
              leaf: true,
              pages: page.pages,
              current: page.current,
              next: page.current + 1,
            });
          }
          rows.forEach((value) => {
            value.leaf = !value.hasChild;
          });
          rows.forEach((row) => {
            this.$refs.tree.append(row, param.parent);
          });
        },
      });
    },
    // 异步树叶子节点懒加载逻辑
    loadNode(node, resolve, callback) {
      let id = node && node.data && node.data.id ? node.data.id || "" : "";
      node.resolve = resolve;
      let url, param;
      url = this.current_prefix + "/file_obj/listPage";
      if (!id) {
        param = {
          dirs: true,
          storeAreaCode: this.storeAreaCode,
          size: this.categoryPageSize,
        };
      } else {
        param = {
          dirs: true,
          parent: id,
          storeAreaCode: this.storeAreaCode,
          size: this.categoryPageSize,
        };
      }
      if (this.isPrivate) {
        param.objectForeignId = this.objectForeignId;
        param.privateDir = 1;
      }
      this.$http({
        url: url,
        method: "post",
        data: param,
        success: (res) => {
          let page = res.objx;
          let rows = page && page.records ? page.records : [];
          if (page.pages > page.current) {
            rows.push({
              parent: param.parent,
              fileName: this.$t2("更多", "components.fileLibrary.more"),
              moreBtn: true,
              leaf: true,
              pages: page.pages,
              current: page.current,
              next: page.current + 1,
            });
          }

          // moreBtn
          rows.forEach((value) => {
            value.leaf = !value.hasChild;
          });
          let items = [];
          if (node.level === 0) {
            let item = {
              parent: null,
              fileName: this.title,
              leaf: rows.length == 0,
              allFileBtn: true,
              id: 0,
              children: rows,
            };
            items.push(item);
            setTimeout(() => {
              this.$refs.tree.setCurrentKey(node.childNodes[0].data);
              this.handleNodeData(node.childNodes[0]);
              node.childNodes[0].expand();
              if (this.option.treeExpandAll) {
                //默认全部展开树分类
                node.childNodes[0].childNodes.forEach((item) => {
                  if (!item.data.leaf) item.expand();
                });
              }
            }, 200);
            this.$nextTick(() => {
              callback && callback();
            });
            this.searchEvent();
          } else {
            items = rows;
            this.$nextTick(() => {
              if (this.option.treeExpandAll) {
                //默认全部展开树分类
                node.childNodes.forEach((item) => {
                  if (!item.data.leaf) item.expand();
                });
              }
              callback && callback();
            });
          }
          resolve(items);
        },
      });
    },
    addFileCategory(flag) {
      let currentFileCategory = this.currentFileCategory;
      let editCategory = {
        storeAreaCode: this.storeAreaCode,
        enabled: true,
        dirs: true,
        leaf: true,
        // children:[]
      };
      if (currentFileCategory) {
        editCategory.parent = currentFileCategory.id;
        this.rootCategory = false;
      } else {
        this.rootCategory = true;
      }
      this.editCategory = editCategory;
      this.showEditCategoryDialog = true;
    },
    editFileCategory(category) {
      let currentFileCategory = category || this.currentFileCategory;
      if (!currentFileCategory) {
        this.$message({
          message: this.$t2(
            "请选择文件夹",
            "components.fileLibrary.editCategoryTip"
          ),
          type: "error",
          showClose: true,
          duration: 3000,
        });
        return;
      }
      this.editCategory = Object.assign({}, currentFileCategory);
      this.showEditCategoryDialog = true;
    },
    confirmEditCategoryDialog() {
      this.$refs.editCategoryForm.$baseValidate((valid) => {
        if (valid) {
          this.$baseConfirm(
            this.$t2(
              "您确定要保存吗？",
              "components.fileLibrary.saveConfirmTip"
            )
          ).then(() => {
            var url =
              this.current_prefix +
              (this.editCategory.id ? "/file_obj/update" : "/file_obj/save");
            let formData = Object.assign({}, this.editCategory);
            if (!this.editCategory.id) {
              if (!this.rootCategory) {
                formData.parent = this.currentCategoryId;
              }
            }

            if (this.isPrivate && !this.editCategory.id) {
              //个人文档，新增文件夹时，需要传当前用户的Id
              formData.objectForeignId = this.objectForeignId[0];
            }
            this.$http({
              url: url,
              method: `post`,
              data: formData,
              isLoading: true,
              success: (res) => {
                this.showEditCategoryDialog = false;
                this.$message({
                  message: res.content,
                  type: "success",
                  duration: 500,
                  onClose: (t) => {},
                });
                let nodeData = res.objx;
                nodeData.leaf = !nodeData.hasChild;
                if (!this.editCategory.id) {
                  //新增
                  let parent = nodeData.parent ? nodeData.parent + "" : "";
                  if (parent) {
                    let parentNode = this.$refs.tree.getNode(parent);
                    this.$refs.tree.append(nodeData, parent);
                    this.$nextTick(() => {
                      parentNode.expand();
                    });
                  } else {
                    let parentNode = this.getTopNode();
                    parentNode.expanded = false;
                    parentNode.loaded = false;
                    parentNode.expand();
                  }
                  //文件区域增加目录
                  /*let index = this.page.records.findIndex(item => !item.dirs)
                  if (index > -1) {
                    this.page.records.splice(index, 0, nodeData);
                  } else {
                    this.page.records.push(nodeData);
                  }*/
                  this.searchEvent();
                } else {
                  //编辑
                  let tree = this.$refs.tree;
                  let node = tree.getNode(formData.id + "");
                  node.data = res.objx;

                  //文件区域修改文件夹信息
                  let cItem = this.page.records.find(
                    (item) => item.id == formData.id
                  );
                  if (cItem) {
                    Object.assign(cItem, res.objx);
                  }
                }
              },
            });
          });
        }
      });
    },
    handleNodeData(node) {
      let treeNodeArr = [];
      let tree = this.$refs.tree;
      // let firstNode = tree.root.childNodes[0];
      if (node) {
        treeNodeArr.push(node);
        let end = false;
        let pNode = node;
        while (!end) {
          pNode = pNode.parent;
          if (pNode && pNode.data) {
            let pData = pNode.data;
            treeNodeArr.push(pNode);
            end = pNode.level <= 1;
          } else {
            end = true;
          }
        }
        treeNodeArr = treeNodeArr.reverse();
      }
      /*treeNodeArr.unshift(firstNode)
      if (!node) {
        node = firstNode;
      }*/
      this.currentFileCategory = node ? node.data : null;
      this.currentNode = node;
      this.$set(this, "treeNodeArr", treeNodeArr);
      this.getFileObjAuth();
    },
    getFileObjAuth() {
      this.$http({
        url: this.current_prefix + `/file_obj_auth/getFileObjAuth`,
        method: `post`,
        data: {
          fileObjId: this.currentCategoryId,
          storeAreaCode: this.storeAreaCode,
        },
        isLoading: true,
        modalStrictly: true,
        success: (res) => {
          this.fileObjAuth = res.objx || {};
        },
      });
    },
    mulDownload() {
      let checkRows = this.getCheckRows();
      if (!checkRows.length) {
        this.$message({
          message: this.$t2(
            "请选择需要下载的文件",
            "components.fileLibrary.downloadTip"
          ),
          type: "error",
          showClose: true,
          duration: 3000,
        });
        return;
      }
      checkRows.forEach((row) => {
        this.$commonFileUtil.downloadFile(row.domain + row.url, row.fileName);
        // this.downLoadFile(row);
      });
    },
    mulDownload2() {
      let checkRows = this.getCheckRows();
      if (!checkRows.length) {
        this.$message({
          message: this.$t2(
            "请选择需要下载的文件",
            "components.fileLibrary.downloadTip"
          ),
          type: "error",
          showClose: true,
          duration: 3000,
        });
        return;
      }
      this.getDownloadDomian((domain) => {
        this.getFileWhole(checkRows, (fileWhole) => {
          // let fileName = this.$moment().format('YYYYMMDDHHmmss');
          this.$http({
            method: "post",
            url: domain + "/docfile/download",
            /*data: {
              "fileName": fileName,
              "children": checkRows,
              "dirs": true
            },*/
            data: fileWhole,
            isLoading: true,
            success: (res) => {
              // this.downLoadFile2(res.objx.url)
              window.open(res.objx.url);
            },
          });
        });
      });
      /*checkRows.forEach(row => {
        this.$commonFileUtil.downloadFile(row.domain + row.url, row.fileName);
      })*/
    },
    getDownloadDomian(callback) {
      this.$http({
        method: "post",
        url: USER_PREFIX + "/common/fileDownloadUrl",
        data: {},
        isLoading: true,
        success: (res) => {
          callback(res.objx);
        },
      });
    },
    getFileWhole(rows, callback) {
      let ids = rows.map((row) => row.id);
      let data = {
        ids: ids,
        objectForeignId: this.objectForeignId,
      };
      if (this.option.foreignDirs === true) {
        data.foreignDirs = true;
      }
      this.$http({
        method: "post",
        url: this.current_prefix + "/file_obj/getFileWhole",
        data: data,
        isLoading: true,
        success: (res) => {
          callback(res.objx);
        },
      });
    },
    downLoadFile2(fileUrl) {
      let that = this;
      that.$http({
        method: "get",
        url: fileUrl,
        data: {},
        /*headers: {
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },*/
        responseType: "blob",
        resultType: "other",
        isLoading: true,
        callback: (res, response) => {
          let fileName = fileUrl.slice(fileUrl.lastIndexOf("/") + 1);
          const blobUrl = window.URL.createObjectURL(res);
          const a = document.createElement("a");
          a.download = fileName;
          a.href = blobUrl;
          a.click();
        },
      });
    },
    downLoadFile(row) {
      let that = this;
      let fileUrl = row.domain + row.url;
      that.$http({
        method: "get",
        url: fileUrl,
        data: {},
        /*headers: {
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },*/
        responseType: "blob",
        resultType: "other",
        isLoading: true,
        callback: (res, response) => {
          const blobUrl = window.URL.createObjectURL(res);
          const a = document.createElement("a");
          a.download = row.fileName;
          a.href = blobUrl;
          a.click();
        },
      });
    },
    replaceFile(row, $rowIndex, items) {
      this.$baseUpload.open({
        limit: 1,
        accept: "file",
        size: 5 * 1024 * 1024 * 1024,
        pickPrivateProfile: false,
        callback: (rows) => {
          if (rows.length) {
            this.confirmReplaceFileAttachment(rows[0], row, (res) => {
              items.splice($rowIndex, 1, res.objx);
            });
          }
        },
      });
    },
    confirmReplaceFileAttachment(newFile, oldFile, callback) {
      newFile.id = oldFile.id;
      newFile.attachCode = oldFile.attachCode;
      newFile.dirs = false;
      this.$http({
        method: "post",
        url: this.current_prefix + "/file_attach/replace",
        data: newFile,
        isLoading: true,
        success: (res) => {
          this.$message({
            message: res.content,
            type: "success",
            duration: 500,
          });
          callback(res);
        },
      });
      return false;
    },
    openFileHistoryDialog(row) {
      this.operateFileHistory = row;
      this.showFileHistoryDialog = true;
    },
    confirmFileHistoryDialog(row) {
      this.searchEvent();
    },
    checkChange() {
      let rows = this.getRows();
      let checkRows = this.getCheckRows();
      this.checkAll = rows.length && rows.length == checkRows.length;
    },
    changeCheckAll(val) {
      let rows = this.getRows();
      this.checkList = val ? rows.map((row) => row.id) : [];
      if (this.showType == 2) {
        this.$refs["table-m1"].setAllCheckboxRow(val);
      }
    },
    tableCheckChange() {
      let checkRows = this.getCheckRows();
      this.checkList = checkRows.map((row) => row.id);
      this.checkChange();
    },
    tableCheckAll(val) {
      let checkRows = this.getCheckRows();
      this.checkList = checkRows.map((row) => row.id);
      this.checkChange();
    },
    confirmRecycleBinDialog() {
      let categoryId = 0;
      let node = this.$refs.tree.getNode(categoryId + "");
      if (!categoryId) {
        node = node.parent;
      }
      node.childNodes = [];
      this.loadNode(node, node.resolve);
      if (categoryId) {
        this.searchEvent();
      }
    },
    initTitle() {
      this.$http({
        method: "post",
        url: USER_PREFIX + "/file_store_area/getByCode",
        data: {
          stringOne: this.storeAreaCode,
        },
        isLoading: true,
        success: (res) => {
          let fileStoreArea = res.objx;
          if (fileStoreArea) {
            this.fileStoreArea = fileStoreArea;
            this.title = fileStoreArea.storeAreaName;
            let tabType = this.option.tabType;
            if (tabType) {
              this.showType = tabType === "table" ? 2 : 1;
            }
            this.$nextTick(() => {
              treeScollx({ target: this, type: "default" });
              this.treeFlag = true;
            });
          } else {
            this.$baseAlert(
              this.$t2(
                "文档工作区未维护",
                "components.fileLibrary.fileStoreAreaTip"
              )
            );
          }
        },
      });
    },
    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";
      }
    },
    deleteBillData(index) {
      this.checkBillDatas.splice(index, 1);
      this.searchEvent();
    },
    getBillLabel(item) {
      let billConfig = this.billConfig;
      let dataProps = billConfig.dataProps;
      if (dataProps.content) {
        return dataProps.content(item);
      } else {
        return item[dataProps.label];
      }
    },
    openBillDialog() {
      this.showBillDialog = true;
    },
    confirmBillDialog(rows) {
      // this.checkBillDatas = rows;

      let billRowField = this.billRowField;
      let checkBillDatas = this.checkBillDatas;
      let fieldDatas = checkBillDatas.map((row) => {
        return row[billRowField];
      });
      let newRows = rows.filter((row) => {
        return !fieldDatas.includes(row[billRowField]);
      });
      this.checkBillDatas.push(...newRows);
      this.searchEvent();
    },
    clearBill() {
      this.checkBillDatas = [];
      this.searchEvent();
    },
    //个人文档
    async getCurrentUser() {
      return this.$http({
        url: USER_PREFIX + "/user/currentUser",
        method: "post",
        success: (res) => {
          this.currentUser = res.objx;
          this.confirmUser([this.currentUser]);
          this.getIsDocAdmin();
        },
      });
    },
    confirmUser(rows) {
      if (rows) {
        let row = rows[0];
        this.userInfo.id = row.id;
        this.userInfo.nickName = row.nickName;
        this.reflushTree();
      }
    },
    setCurrentUser(flag) {
      this.confirmUser([this.currentUser]);
      this.reflushTree();
    },
    reflushTree() {
      this.treeFlag = false;
      setTimeout(() => {
        this.treeFlag = true;
      }, 200);
    },
    getIsDocAdmin() {
      return this.$http({
        url: USER_PREFIX + "/file_obj/isDocAdmin",
        method: "post",
        success: (res) => {
          this.isDocAdmin = res.objx || false;
        },
      });
    },
    batchReplace() {
      let checkRows = this.getCheckRows();
      if (!checkRows.length) {
        this.$message({
          message: this.$t2(
            "请选择需要替换的文件",
            "components.fileLibrary.replaceFileTip"
          ),
          type: "error",
          showClose: true,
          duration: 3000,
        });
        return;
      }
      this.$baseUpload.open({
        limit: 200,
        accept: "file",
        size: 5 * 1024 * 1024 * 1024,
        auto: false,
        confirmUpload: this.checkBatchReplace,
        pickPrivateProfile: false,
        callback: (rows) => {
          if (rows.length) {
            this.confirmBatchReplaceFileAttachment(rows, (res) => {
              this.searchEvent();
            });
          }
        },
      });
    },
    checkBatchReplace({ files, done }) {
      let newFileObjDTOs = files.map((file) => {
        return {
          name: file.name,
        };
      });
      let checkRows = this.getCheckRows();
      this.$http({
        url: this.current_prefix + "/file_attach/checkBatchReplace",
        method: `post`,
        data: {
          oldFileObjDTOs: checkRows,
          newFileObjDTOs: newFileObjDTOs,
        },
        isLoading: true,
        success: (res) => {
          //确认上传回调
          done();
        },
      });
    },
    confirmBatchReplaceFileAttachment(rows, callback) {
      let checkRows = this.getCheckRows();
      this.$http({
        method: "post",
        url: this.current_prefix + "/file_attach/batchReplace",
        data: {
          oldFileObjDTOs: checkRows,
          newFileObjDTOs: rows,
        },
        isLoading: true,
        success: (res) => {
          this.$message({
            message: res.content,
            type: "success",
            duration: 500,
          });
          callback(res);
        },
      });
      return false;
    },
    //圈选
    mask_width() {
      return Math.abs(this.end_x - this.start_x);
    },
    mask_height() {
      return Math.abs(
        this.end_y + this.scrollTop2 - this.start_y - this.scrollTop1
      );
    },
    mask_left() {
      return Math.min(this.start_x, this.end_x) - this.box_screen_left;
    },
    mask_top() {
      return (
        Math.min(this.start_y, this.end_y) -
        this.box_screen_top -
        Math.max(this.scrollTop2 - this.scrollTop1, 0)
      );
    },
    getStyle() {
      const style =
        "width:" +
        this.mask_width() +
        "px;left:" +
        this.mask_left() +
        "px;height:" +
        this.mask_height() +
        "px;top:" +
        this.mask_top() +
        "px;";
      return style;
    },
    updateMaskStyle() {
      const dom_mask = document.querySelector(".viewBox .mask");
      dom_mask.setAttribute("style", this.getStyle());
    },
    handleMouseDown(event) {
      // if (event.target.tagName === 'SPAN') return false;
      if (!this.mouseCheck) return;
      let containter1 =
        this.showType == 1
          ? this.$refs.containter1
          : this.$el.querySelector(".vxe-table--body-wrapper");
      this.scrollTop1 = containter1.scrollTop;
      this.scrollTop2 = containter1.scrollTop;

      const dom_box = document.querySelector(".viewBox");
      let rect = dom_box.getBoundingClientRect();
      this.box_screen_left = rect.left;
      this.box_screen_top = rect.top;

      this.start_x = event.clientX;
      this.start_y = event.clientY;

      this.end_x = event.clientX;
      this.end_y = event.clientY;
      this.is_show_mask = true;

      document.body.addEventListener("mousemove", this.handleMouseMove);
      document.body.addEventListener("mouseup", this.handleMouseUp);
    },
    handleMouseMove(event) {
      let containter1 =
        this.showType == 1
          ? this.$refs.containter1
          : this.$el.querySelector(".vxe-table--body-wrapper");
      this.scrollTop2 = containter1.scrollTop;

      this.select_list = [];
      this.end_x = event.clientX;
      this.end_y = event.clientY;
      this.updateMaskStyle();

      if (this.start_x != this.end_x || this.start_y != this.end_y) {
        setTimeout(() => {
          this.handleDomSelect();
        }, 0);
      }
    },
    handleMouseUp(event) {
      this.end_x = event.clientX;
      this.end_y = event.clientY;
      document.body.removeEventListener("mousemove", this.handleMouseMove);
      document.body.removeEventListener("mouseup", this.handleMouseUp);

      this.is_show_mask = false;
      /*if (this.start_x != this.end_x || this.start_y != this.end_y) {
        this.handleDomSelect();
      }*/
      this.resSetXY();
    },
    handleDomSelect() {
      const dom_mask = window.document.querySelector(".mask");
      const rect_select = dom_mask.getClientRects()[0];
      if (!rect_select) {
        return;
      }
      let checkList = [];
      if (this.showType == 1) {
        document
          .querySelectorAll(".el-checkbox-group.f-group .item")
          .forEach((node, index) => {
            let fileData = this.page.records[index];
            if (!fileData.dirs) {
              const rects = node.getClientRects()[0];
              if (this.collide(rects, rect_select) === true) {
                checkList.push(this.page.records[index].id);
              }
            }
          });
      } else {
        let checkRows = [];
        document
          .querySelectorAll(".viewBox .vxe-body--row")
          .forEach((node, index) => {
            const rects = node.getClientRects()[0];
            if (this.collide(rects, rect_select) === true) {
              let fileData = this.page.records[index];
              if (!fileData.dirs) {
                checkRows.push(fileData);
                checkList.push(fileData.id);
              }
            }
          });
        this.$refs["table-m1"].setAllCheckboxRow(false);
        this.$refs["table-m1"].setCheckboxRow(checkRows, true);
      }
      this.checkList = checkList;
      this.checkChange();
    },
    // eslint-disable-next-line class-methods-use-this
    collide(rect1, rect2) {
      const maxX = Math.max(rect1.x + rect1.width, rect2.x + rect2.width);
      const maxY = Math.max(rect1.y + rect1.height, rect2.y + rect2.height);
      const minX = Math.min(rect1.x, rect2.x);
      const minY = Math.min(rect1.y, rect2.y);
      if (
        maxX - minX <= rect1.width + rect2.width &&
        maxY - minY <= rect1.height + rect2.height
      ) {
        return true;
      } else {
        return false;
      }
    },
    resSetXY() {
      this.start_x = 0;
      this.start_y = 0;
      this.end_x = 0;
      this.end_y = 0;
      this.scrollTop1 = 0;
      this.scrollTop2 = 0;
      this.updateMaskStyle();
    },
    customFileButtonEvent(customFileButton, attachment) {
      customFileButton.onclick({
        row: attachment,
      });
    },
    customToobarButtonEvent(customFileButton) {
      customFileButton.onclick({
        rows: this.checkRows,
      });
    },
    customFileButtonVisable(customFileButton, attachment) {
      if (customFileButton.visable === "function") {
        let checkBillDatas = this.checkBillDatas;
        return customFileButton.visable({ row: attachment, checkBillDatas });
      } else if (
        customFileButton.visable === null ||
        customFileButton.visable == undefined
      ) {
        return true;
      } else {
        return customFileButton.visable;
      }
    },
    downloadSingerFile(attachment) {
      let fileObjAuth = this.fileObjAuth;
      if (attachment.dirs || !fileObjAuth.downloadAuth) return;
      let url = attachment.domain + attachment.url;
      if (this.fileStoreArea.toDownWatermark && fileObjAuth.downWatermarkAuth) {
        let loginAccount = this.$store.getters.loginAccount;
        url += "?_w=" + encodeURIComponent(encode(loginAccount));
      }
      this.$commonFileUtil.downloadFile(url, attachment.fileName);
    },
  },
};
export default modules;
