<template>
  <div class="ele-body">
    <el-card shadow="never" v-loading="loading">
      <ele-split-layout
        width="210px"
        allow-collapse
        :right-style="{ overflow: 'hidden' }"
      >
        <div>
          <!-- 操作按钮 -->
          <ele-toolbar class="ele-toolbar-actions">
            <div style="margin: 5px 0">
              <!-- <el-button
                size="small"
                type="primary"
                icon="el-icon-plus"
                class="ele-btn-icon"
                @click="openEdit()"
              >
                添加
              </el-button>
              <el-button
                size="small"
                type="warning"
                icon="el-icon-edit"
                class="ele-btn-icon"
                :disabled="!current"
                @click="openEdit(current)"
              >
                修改
              </el-button>
              <el-button
                size="small"
                type="danger"
                icon="el-icon-delete"
                class="ele-btn-icon"
                :disabled="!current"
                @click="remove"
              >
                删除
              </el-button> -->
            </div>
          </ele-toolbar>

          <div class="ele-border-lighter sys-organization-list">
            <el-tree
              ref="tree"
              :data="data"
              highlight-current
              :draggable="true"
              node-key="id"
              :props="{ label: 'name', children: 'sonDirectoryList' }"
              :expand-on-click-node="false"
              :default-expand-all="true"
              @node-click="onNodeClick"
              @node-drop="nodeDrop"
              :allow-drop="allowDrop"
            >
              <span
                class="custom-tree-node"
                slot-scope="{ node, data }"
                @contextmenu.prevent="onRightClick(data,$event)"
                @click.prevent="clicka"
                ref="trueNodeRef" 
              >
                <el-popover
                  style="position: fixed; z-index: 2000"
                  width="130"
                  ref="popoverRef"
                  v-model="visible"
                  @click.native="visible = false"
                  
                  v-if="data.id == rightData.id && fileType === 0 && !isPop"
                >
                  <div>
                    <el-link
                      v-if="lcyStatus == 1 && isPower(current)"
                      :underline="false"
                      @click.native="setPower(data)"
                      >更改权限
                    </el-link></div
                  >
                  <div>
                    <el-link
                      v-if="lcyStatus != 1"
                      :underline="false"
                      @click.native="goTo('文档工作区', data)"
                      >转到文档工作区
                    </el-link></div
                  >
                  <div>
                    <el-link
                      v-if="lcyStatus != '2'"
                      :underline="false"
                      @click.native="goTo('文档归档区', data)"
                      >转到文档归档区
                    </el-link></div
                  >
                  <div>
                    <el-link
                      v-if="lcyStatus != '3'"
                      :underline="false"
                      @click.native="goTo('文档发布区', data)"
                      >转到文档发布区
                    </el-link></div
                  >
                </el-popover>

                <ElementTreeLine
                  :node="node"
                  :showLabelLine="true"
                  :indent="20"
                >
                  <img src="../../../assets/wjj.png" />

                  <span>{{ node.label }}</span>
                </ElementTreeLine>
              </span>
            </el-tree>
          </div>
        </div>
        <template v-slot:content>
          <FileTableList
            ref="tableRef"
            :parentData="current"
            :folderList="data"
            @parenOpen="openEdit"
            :fileType="fileType"
            :lcyStatus="lcyStatus"
            :isPop="isPop"
            :disabledTableList="disabledTableList"
          />
        </template>
      </ele-split-layout>
    </el-card>
    <!-- 编辑弹窗 -->
    <folder-edit @done="query" ref="editRef" :fileType="fileType" />
    <!-- 文件夹权限 -->

    <ele-modal
      width="50vw"
      :visible="powerVisible"
      @close="powerVisible = false"
      :close-on-click-modal="false"
      append-to-body
    >
      <Power @powerSave="powerSave" ref="PowerRef" :powerArr="powerArr" />
    </ele-modal>
    <!-- {{current?.id}} -->
  </div>
</template>

<script>
//
import FileTableList from '@/views/doc/components/file-table-list.vue';
import folderEdit from '@/views/doc/components/folder-edit.vue';
import {
  directoryDeleteAPI,
  getDocTreeListAPI,
  directoryUpdateAPi,
  validationPersonal,
  moveDirectory
} from '@/api/doc-manage';
import { mapGetters } from 'vuex';
import Power from './power/index.vue';
import { isPower } from '../util.js';

import ElementTreeLine from 'element-tree-line';
// css
import 'element-tree-line/dist/style.scss';
export default {
  components: { FileTableList, folderEdit, ElementTreeLine, Power },
  props: {
    fileType: '', //0：公共文档 1：个人文档 2：文档模板
    lcyStatus: '', //1：文档工作区 2：文档归档区 3：文档发布区 4：文档废止区
    isPop: {
      //是否弹出
      default: false
    },
    disabledTableList: {
      //已选择列表
      default: () => []
    }
  },
  data() {
    return {
      isPower,
      powerArr: [
        { name: 'add', label: '新建' },
        { name: 'revise', label: '修改' },
        { name: 'del', label: '删除' }
      ],
      visible: false,
      powerVisible: false,
      rightData: {},
      // 加载状态
      loading: true,
      // 列表数据
      data: [],
      institutionList: [],
      // 选中数据
      current: {},
      // 是否显示表单弹窗
      showFolderEditFlag: false,
      // 编辑回显数据
      editData: null,
      // 上级id
      parentId: null
    };
  },
  computed: {
    ...mapGetters(['user'])
  },
  created() {
    this.query();
  },
  mounted() {
    document.addEventListener('click', this.clicka);
  },
  destroyed() {
    document.removeEventListener('click', this.clicka);
  },

  methods: {
    /* 查询 */
    async query(row) {
      this.loading = true;
      let query = {
        type: this.fileType,
        currentUserId: this.user.info.userId
      };
      this.data = await getDocTreeListAPI(query);
      if (this.fileType == 1 && this.data.length == 0) {
        await validationPersonal();
        await this.query();
      }
   
      this.$nextTick(() => {
        if (this.$route.params.row) {
          this.$refs.tree.setCurrentKey(this.$route.params.row.id);
          this.onNodeClick(this.$route.params.row);
        }else if (row&&row.id) {
          this.$refs.tree.setCurrentKey(row.id);
          this.onNodeClick(row);
        }else {
          this.$refs.tree.setCurrentKey(this.data[0].id);

          this.onNodeClick(this.data[0]);
        }
      });
      this.loading = false;
    },
    /* 选择数据 */
    onNodeClick(row) {
      console.log(row,'row')
      if (row) {
        this.current = row;
        this.$nextTick(() => {
          this.$refs.tableRef.reload();
        });
      } else {
        this.current = null;
      }
    },
    allowDrop(draggingNode, dropNode, type) {
      //拖拽限制
      return dropNode.parent.id == draggingNode.parent.id && type != 'inner';
    },
    clicka() {
      this.visible = false;
    },

    onRightClick(data,PointerEvent) {
      this.rightData = data;
      this.visible = true;
      this.$nextTick(() => {
        let y = PointerEvent.pageY;
        let x = PointerEvent.pageX+10;
        if (PointerEvent.screenY >= PointerEvent.view.innerHeight) {
          y -= 80;
        }
        this.$refs.popoverRef.$el.style.top = y+'px'
        this.$refs.popoverRef.$el.style.left = x+'px'
      });
    },
    setPower(data) {
      this.powerVisible = true;
      this.$nextTick(() => {
        this.$refs.PowerRef &&
          this.$refs.PowerRef.setTableList(data.userAuthority || []);
      });
    },
    //权限保存
    powerSave(tableList) {
      directoryUpdateAPi({
        id: this.current.id,
        userAuthority: tableList,
        authority: 1
      }).then((msg) => {
        this.powerVisible = false;
        this.query();
      });
    },
    goTo(name, row) {
      this.$router.push({
        name,
        params: {
          row
        }
      });
    },
    /* 显示编辑 */
    openEdit(type) {
      if (type == 'del') {
        this.remove();
        return;
      }
      this.$refs.editRef.open(
        type,
        JSON.parse(JSON.stringify(this.current)),
        this.data
      );
    },
    /* 删除 */
    remove() {
      this.$confirm('确定要删除选中文件夹吗?', '提示', {
        type: 'warning'
      })
        .then(() => {
          const loading = this.$loading({ lock: true });
          directoryDeleteAPI([this.current.id])
            .then((msg) => {
              loading.close();
              this.$message.success('操作成功');
              this.query();
            })
            .catch((e) => {
              loading.close();
            });
        })
        .catch(() => {});
    },
    nodeDrop(to, form) {
      moveDirectory({
        targetId: form.data.id,
        replaceId: to.data.id
      });
    },
    getTableList() {
      return this.$refs.tableRef.getTableList();
    }
  }
};
</script>

<style lang="scss" scoped>
.sys-organization-list {
  height: calc(100vh - 180px);
  box-sizing: border-box;
  border-width: 1px;
  border-style: solid;
  overflow: auto;
}

.sys-organization-list :deep(.el-tree-node__content) {
  height: 25px;

  & > .el-tree-node__expand-icon {
    margin-left: 10px;
  }
}
.custom-tree-node {
  display: flex;
  align-items: center;
}
:deep(.el-popover) {
  min-width: 50px;
  position: fixed;
  background: #409EFF;
  
}
:deep(.el-link--inner) {
  padding: 3px 0;
}
:deep(.el-link.el-link--default) {
  color:#fff
}
// :deep(.element-tree-node-line-hor) {
//   border-bottom: 1px solid #dcdfe6;
// }
// :deep(.element-tree-node-line-ver) {
//   border-left: 1px solid #dcdfe6;
// }
</style>
<style lang="scss">
.el-tree
  > .el-tree-node
  > .el-tree-node__content:nth-of-type(1)
  .element-tree-node-line-hor {
  border: none;
}
.el-tree
  > .el-tree-node
  > .el-tree-node__content:nth-of-type(1)
  .element-tree-node-line-ver {
  border: none;
}
</style>