let modules;
import {treeScolly} from "@base/utils/global.js";

modules = {
  props: {
    _dataId: Number,
    visiable: Boolean,
    checkRows: Array,
    handleType: {
      type: Number,
      default: 1,
    },
  },
  inject: [
    "current_prefix",
    "storeAreaCode",
    "dataId",
    "getTitle",
    "getIsPrivate",
    "getObjectForeignId",
    "billConfig",
    "isBillEnabled",
    "billRowField",
    "billDialogParam",
  ],
  components: {},
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  data() {
    return {
      showDialog: true,
      filterText: "",
      defaultProps: {
        children: "children",
        label: "fileName",
        isLeaf: "leaf",
      },
      showEditCategoryDialog: false,
      editCategory: {},
      currentFileCategory: null,
      rootCategory: false,
      categoryPageSize: 1000,
      treeNodeArr: [],
      currentNode: null,
      formData: {},
      showBillDialog: false,
      billDialogContent: null,
      checkBillDatas: [],
    };
  },
  computed: {
    hasCheckBill() {
      let hasCheckBill = false;
      if (this.isBillEnabled) {
        let checkBillIds = this.checkBillIds;
        if (checkBillIds.length) {
          if (checkBillIds.length == 1) {
            hasCheckBill = checkBillIds[0] != 0;
          } else {
            hasCheckBill = true;
          }
        }
      }
      return checkBillIds;
    },
    checkBillIds() {
      let ids = [];
      if (this.isBillEnabled) {
        let cids = this.checkBillDatas.map((row) => row.id);
        return cids.length ? cids : this.objectForeignId;
      } else {
        return this.getObjectForeignId();
      }
    },
    objectForeignId() {
      /* let currentFileCategoryId = this.currentFileCategory && this.currentFileCategory.id ? this.currentFileCategory.id : ''*/
      return this.dataId || [0];
    },
    dialogTitle() {
      let titleMap = {
        0: this.$t2('文件还原', 'components.fileLibrary.revertFile'),
        1: this.$t2('移动文件', 'components.fileLibrary.moveFile'),
        2: this.$t2('复制文件', 'components.fileLibrary.copyFile')
      };
      return titleMap[this.handleType];
    },
  },
  created() {
    if (this.isBillEnabled) {
      this.billDialogContent = this.billConfig.billDialog;
    }
  },
  mounted() {
    this.$nextTick(() => {
      let f =
        this.isBillEnabled && this.handleType == 2 ? ".nextDom2" : ".nextDom";
      let nextDom = this.$el.querySelector(f);
      treeScolly({
        target: this,
        type: "selectDialog",
        nextDom: nextDom,
      });
    });
  },
  methods: {
    changeCategory(row, node) {
      this.handleNodeData(node);
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.categoryName.indexOf(value) !== -1;
    },
    handleNodeClick(data, node, v) {
      if (!data.moreBtn) {
        this.changeCategory(data, node);
      } else {
        this.showModeCategory(data, node, v);
      }
    },
    showModeCategory(data, node, v) {
      let param = {
        parent: data.parent,
        dirs: true,
        storeAreaCode: this.storeAreaCode,
        size: this.categoryPageSize,
        current: data.next,
      };
      if (this.getIsPrivate()) {
        param.objectForeignId = this.getObjectForeignId();
        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) {
      let id = node && node.data && node.data.id ? node.data.id || "" : "";
      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.getIsPrivate()) {
        param.objectForeignId = this.getObjectForeignId();
        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;
          });
          if (node.level === 0) {
            setTimeout(() => {
              this.$refs.tree.setCurrentKey(node.childNodes[0].data);
              this.handleNodeData(node.childNodes[0]);
              node.childNodes[0].expand();
            }, 200);
          }
          let items = [];
          if (node.level === 0) {
            let item = {
              parent: null,
              fileName: this.getTitle(),
              leaf: rows.length == 0,
              allFileBtn: true,
              id: 0,
              children: rows,
            };
            items.push(item);
          } else {
            items = rows;
          }
          resolve(items);
        },
      });
    },
    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 ? node.data : null;
      this.currentNode = node;
      this.$set(this, "treeNodeArr", treeNodeArr);
    },
    doNav(t) {
      let node = this.$refs.tree.getNode(t.data.id + "");
      this.$refs.tree.setCurrentKey(node.data);
      this.handleNodeClick(node.data, node, this);
    },
    dialogClose() {
      this.$emit("update:visiable", false);
    },
    dialogPrimary() {
      if (this.handleType == 0) {
        this.dialogPrimary0();
        return;
      }
      let checkCategorys = this.checkRows.filter((item) => item.dirs);
      for (let i = 0; i < checkCategorys.length; i++) {
        let checkCategory = checkCategorys[i];
        if (this.currentFileCategory.id == checkCategory.id) {
          this.$message({
            message: this.$t2('目标文件夹与源文件夹的不允许为同一个文件夹', 'components.fileLibrary.moveTip1'),
            type: "error",
            duration: 3000,
          });
          return;
        }
        if (
          this.currentFileCategory.id &&
          this.currentFileCategory.treePath.indexOf(
            "," + checkCategory.id + ","
          ) != -1
        ) {
          this.$message({
            message: this.$t2('目标文件夹是源文件夹的子文件夹', 'components.fileLibrary.moveTip2'),
            type: "error",
            duration: 3000,
          });
          return;
        }
      }

      if (this.handleType == 2) {
        this.dialogPrimary2();
        return;
      }
      if (!this.currentFileCategory) {
        this.$message({
          message: this.$t2('请选择需要移动的文件夹', 'components.fileLibrary.moveTip3'),
          type: "error",
          duration: 3000,
        });
        return;
      }

      if (this.currentFileCategory.id == this.checkRows[0].parent) {
        this.$message({
          message:
            this.$t2("数据已在文件夹[" + this.currentFileCategory.fileName + "]中，不需要移动", 'components.fileLibrary.moveTip4', {fileName: this.currentFileCategory.fileName}),
          type: "error",
          duration: 3000,
        });
        return;
      }

      if (this.currentFileCategory.id == 0) {
        let fileItem = this.checkRows.find((item) => !item.dirs);
        if (fileItem) {
          let fileName = this.getTitle();
          this.$message({
            message: this.$t2("数据不允许移动到[" + fileName + "]", 'components.fileLibrary.moveTip5', {fileName: fileName}),
            type: "error",
            duration: 3000,
          });
          return;
        }
      } else if (!this.currentFileCategory.hasAuth) {
        let fileName = this.currentFileCategory.fileName;
        this.$message({
          message: this.$t2("数据不允许移动到[" + fileName + "]", 'components.fileLibrary.moveTip5', {fileName: fileName}),
          type: "error",
          duration: 3000,
        });
        return;
      }

      this.$baseConfirm(this.$t2('您确定要移动文件吗？', 'components.fileLibrary.moveConfirmTip')).then(() => {
        this.$http({
          method: "post",
          url: this.current_prefix + "/file_obj/move",
          data: {
            objectForeignId: this.checkBillIds,
            parent: this.currentFileCategory.id,
            storeAreaCode: this.currentFileCategory.storeAreaCode,
            fileObjDTOs: this.checkRows,
          },
          isLoading: true,
          success: (res) => {
            this.$message({
              message: res.content,
              type: "success",
              duration: 500,
            });
            let categoryArr = this.treeNodeArr
              .reverse()
              .map((item) => item.data);
            this.$emit("confirm", this.currentFileCategory, categoryArr);
            this.dialogClose();
          },
        });
      });
    },
    dialogPrimary2() {
      if (!this.currentFileCategory) {
        this.$message({
          message: this.$t2('请选择文件夹', 'components.fileLibrary.copyTip1'),
          type: "error",
          duration: 3000,
        });
        return;
      }

      if (this.currentFileCategory.id == 0) {
        let fileItem = this.checkRows.find((item) => !item.dirs);
        if (fileItem) {
          let fileName = this.getTitle();
          this.$message({
            message: this.$t2("数据不允许复制到[" + fileName + "]", 'components.fileLibrary.copyTip2', {fileName: fileName}),
            type: "error",
            duration: 3000,
          });
          return;
        }
      } else if (!this.currentFileCategory.hasAuth) {
        let fileName = this.currentFileCategory.fileName;
        this.$message({
          message:
            this.$t2("数据不允许复制到[" + fileName + "]", 'components.fileLibrary.copyTip2', {fileName: fileName}),
          type: "error",
          duration: 3000,
        });
        return;
      }
      this.$baseConfirm(this.$t2('您确定要复制文件吗？', 'components.fileLibrary.copyConfirmTip')).then(() => {
        let newRows = this.checkRows.map((row) => {
          return {
            id: row.id,
            name: row.name,
            fileName: row.fileName,
            url: row.url,
            source: row.source,
            domain: row.domain,
            thumbnail: row.thumbnail,
            medium: row.medium,
            large: row.large,
            fileSize: row.fileSize,
            extension: row.extension,
          };
        });
        this.$http({
          method: "post",
          url: this.current_prefix + "/file_obj/copy",
          data: {
            objectForeignId: this.checkBillIds,
            parent: this.currentFileCategory.id,
            storeAreaCode: this.currentFileCategory.storeAreaCode,
            fileObjDTOs: newRows,
          },
          isLoading: true,
          success: (res) => {
            this.$message({
              message: res.content,
              type: "success",
              duration: 500,
            });
            // this.$emit('confirm');
            let categoryArr = this.treeNodeArr
              .reverse()
              .map((item) => item.data);
            this.$emit("confirm", this.currentFileCategory, categoryArr);
            this.dialogClose();
          },
        });
      });
    },
    dialogPrimary0() {
      if (!this.currentFileCategory) {
        this.$message({
          message: this.$t2('请选择文件夹', 'components.fileLibrary.revertTip1'),
          type: "error",
          duration: 3000,
        });
        return;
      }
      if (this.currentFileCategory.id == 0) {
        let fileItem = this.checkRows.find((item) => !item.dirs);
        if (fileItem) {
          let fileName = this.getTitle();
          this.$message({
            message: this.$t2("数据不允许还原到[" + fileName + "]", 'components.fileLibrary.revertTip2', {fileName: fileName}),
            type: "error",
            duration: 3000,
          });
          return;
        }
      } else if (!this.currentFileCategory.hasAuth) {
        let fileName = this.currentFileCategory.fileName;
        this.$message({
          message: this.$t2("数据不允许还原到[" + fileName + "]", 'components.fileLibrary.revertTip2', {fileName: fileName}),
          type: "error",
          duration: 3000,
        });
        return;
      }

      let categoryArr = this.treeNodeArr.reverse().map((item) => item.data);
      this.$emit("confirm", this.currentFileCategory, categoryArr);
      this.dialogClose();
    },
    deleteBillData(index) {
      this.checkBillDatas.splice(index, 1);
    },
    getBillLabel(item) {
      let billConfig = this.billConfig;
      let dataProps = billConfig.dataProps;
      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);
    },
    clearBill() {
      this.checkBillDatas = [];
      this.searchEvent();
    },
  },
};
export default modules;
