import ElImageViewer from '@base/components/VabUpload/image-viewer';
import recycleBinPropertiesDialog from "../recycleBinPropertiesDialog";
import categoryMoveDialog from '../categoryMoveDialog'

let modules;
modules = {
  name: 'recycleBinDialog',
  props: {
    option: {
      type: Object
    },
    treeNodeArr: Array,
    currentFileCategory: Object
  },
  components: {
    ElImageViewer,
    categoryMoveDialog,
    recycleBinPropertiesDialog
  },
  provide() {
    return {
      current_prefix: this.current_prefix,
      storeAreaCode: this.storeAreaCode,
      dataId: this.dataId
    }
  },
  inject: ['getTitle'],
  mounted() {
    // treeScollx({target: this, type: 'default'});
    this.searchEvent();
    this.initTableList();
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  data() {
    let pageSize = 1000;
    let categoryPageSize = 1000;
    return {
      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: {},
      pageSize: pageSize,
      page: {
        current: 1,
        size: pageSize,
        total: 0,
        records: []
      },
      categoryPageSize: categoryPageSize,
      categoryPage: {
        current: 1,
        size: categoryPageSize,
        total: 0,
        records: []
      },
      showEditCategoryDialog: false,
      editCategory: {},
      rootCategory: false,


      currentNode: null,
      // treeNodeArr: [],
      checkRows: [],

      checkList: [],
      handleType: 1,//1移动，2复制
      showFileHistoryDialog: false,
      operateFileHistory: null,
      showShareDialog: false,
      shareAttachment: null,
      checkAll: false,
      fileArr: [],
      checkList2: [],
      //圈选
      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,

      showDialog: true,
      operateRows: [],
      showCategoryMoveDialog: false,
      hasRever: 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;
    },
    objectForeignId() {
      /*let currentFileCategoryId = this.currentFileCategory && this.currentFileCategory.id ? this.currentFileCategory.id : ''*/
      return 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)
    }
  },
  methods: {
    getHttpTarget() {
      let target = document.body;
      return target;
    },
    dialogClose() {
      this.$emit('update:visiable', false);
    },
    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;
    },
    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.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));
    },
    openPreview(attachment) {
      return;
      let fileSuffix = this.$commonFileUtil.getFileSuffix(attachment.url);
      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.isPdf(fileSuffix)) {
        window.open(attachment.domain + attachment.url);
      }
    },
    initAttchInfo(page) {
      let defaultPage = {
        current: 1,
        size: this.pageSize,
        total: 0,
        records: []
      }
      page = page || {
        current: 1,
        size: this.pageSize
      };
      this.$commonHttp({
        method: 'post',
        url: this.current_prefix + '/file_recovery/listPage',
        data: {
          storeAreaCode: this.storeAreaCode,
          ...this.formData,
          ...page
        },
        isLoading: true,
        loadingTarget: this.getHttpTarget(),
        success: res => {
          this.page = res.objx ? res.objx : defaultPage;
        }
      });
    },
    initTableList() {
      let that = this;
      let tableOption = {
        vue: this,
        tableRef: 'table-m1',
        tableName: 'user_fileLibrary_recycleBinDialog-m1',
        /* path: this.current_prefix + '/file_attachment/listPage',
         param: () => {
           return {
             objectForeignId: this.objectForeignId,
             storeAreaCode: this.storeAreaCode,
             categoryCode: this.currentFileCategoryCode,
             ...this.formData
           }
         },*/
        config: {
          height: 'auto',
          /*checkboxConfig: {
            checkMethod({row}) {
              return !row.dirs;
            }
          }*/
        },
        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-image', {
                        props: {
                          src: showUrl
                        }
                      })
                    ]),
                    h('span', row.fileName)
                  ];
                } else {
                  return [
                    h('a', {
                      staticClass: "a-link img",
                      on: {
                        click: (event) => {
                          event.stopPropagation();
                        }
                      }
                    }, [
                      h('div', {
                        staticClass: "img"
                      }, [
                        h('svg-icon', {
                          props: {"icon-class": "ico-wenjianjia"}
                        }),
                        h('span', row.fileName)
                      ])
                    ])
                  ]
                }
              }
            }
          },
          {
            title: "文件地址",
            field: 'treePathName',
            width: 250
          },
          {
            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.fileSn'),
            field: "fileSn",
            width: 150
          },
          {title: this.$t2('删除人', 'components.fileLibrary.deleteBy'), field: '_createBy', width: 150},
          {
            field: 'createDate',
            title: this.$t2('删除时间', 'components.fileLibrary.deleteDate'),
            width: 150
          },
          {
            minWidth: 100,
            fixed: 'right',
            title: '',
            sortable: false,
            slots: {
              default: "operate"
            }
          }
        ],
        callback(a, b) {

        }

      };
      this.$vxeTableUtil.initVxeTable(tableOption).then(opts => {
        this.vxeOption = opts;
      });
    },
    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({type, currentPage, pageSize, $event}) {
      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);
    },
    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();
    },
    rever(rows) {
      if (rows == null) {
        rows = this.getCheckRows();
        if (!rows.length) {
          this.$message({
            message: this.$t2('', 'components.fileLibrary.revertTip3'),
            type: 'error',
            duration: 3000,
          });
          return;
        }
      }

      this.operateRows = rows;
      this.showCategoryMoveDialog = true;
    },
    confirmMoveDialog(chooseCategory, categoryArr) {
      let rows = this.operateRows;
      let parentId = chooseCategory && chooseCategory.id ? chooseCategory.id : 0;
      let fileRow = rows.find(row => !row.dirs);
      if (!parentId && fileRow) {
        let fileName = this.getTitle();
        this.$message({
          message: this.$t2('文件不允许还原到[' + fileName + ']', 'components.fileLibrary.revertTip4', {fileName: fileName}),
          type: 'error',
          duration: 3000,
        });
        return;
      }

      this.$baseConfirm(this.$t2('您确定要还原吗？', 'components.fileLibrary.revertConfirmTip')).then(() => {

        this.$http({
          method: 'post',
          url: this.current_prefix + '/file_recovery/revert',
          data: {
            storeAreaCode: this.storeAreaCode,
            parent: parentId,
            fileRecoveryDTOs: rows
          },
          isLoading: true,
          loadingTarget: this.getHttpTarget(),
          success: res => {
            this.hasRever = true;
            this.$message({
              message: res.content,
              type: 'success',
              duration: 500,
            });
            // this.dialogClose();
            this.searchEvent();
            this.$emit('confirm', this.hasRever);
          }
        });
      });
    },
    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';
      }
    },
    //圈选
    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();
    }
  }
};
export default modules;
