<template>
  <ele-modal
    :title="title"
    :visible.sync="treeVisible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    width="30%"
    :maxable="true"
    :resizable="true"
  >
    <div class="ele-border-lighter sys-organization-list">
      <el-tree
        :data="treeList"
        :props="defaultProps"
        v-loading="treeLoading"
        :node-key="nodeKey"
        ref="tree"
        :highlight-current="true"
        :expand-on-click-node="false"
        @node-click="handleNodeClick"
        v-bind="$attrs"
      >
      </el-tree>
    </div>
    <template v-slot:footer>
      <el-button @click="handleClose">关闭 </el-button>
      <el-button type="primary" @click="selected">选择</el-button>
    </template>
  </ele-modal>
</template>

<script>
  import { getProduceTreeByPid } from '@/api/saleManage/quotation';
  export default {
    data() {
      return {
        treeVisible: false,
        treeList: [],
        current: null,
        title: '选择分类',
        pathList: [],

        treeLoading: false,
        nodeKey: 'id',
        defaultProps: {
          children: 'children',
          value: 'id',
          label: 'name'
        }
      };
    },

    watch: {},
    methods: {
      open() {
        this.treeVisible = true;
        this.getTreeData();
      },
      handleClose() {
        this.treeVisible = false;
        this.current = null;
      },
      // 获取树结构数据
      async getTreeData() {
        try {
          this.treeLoading = true;
          let data = await getProduceTreeByPid();

          this.treeLoading = false;
          this.treeList = this.$util.toTreeData({
            data: data || [],
            idField: 'id',
            parentIdField: 'parentId'
          });
        } catch (error) {}
        this.treeLoading = false;
      },

      handleNodeClick(data, node) {
        this.$emit('handleNodeClick', data, node);
        this.current = data;
      },

      selected() {
        if (!this.current) {
          return this.$message.warning(`请${this.title}`);
        }
        this.pathList = this.findParent([], this.current, this.treeList);

        let ruleCode = null;
        if (this.pathList.length == 0) {
          ruleCode = this.current.ruleCode;
        } else {
          ruleCode =
            this.pathList[this.pathList.length - 1] &&
            this.pathList[this.pathList.length - 1].ruleCode;
        }

        this.pathList.unshift(this.current);
        const PathInfo = {
          categoryLevelPath: '',
          categoryLevelPathId: [],
          rootCategoryLevelId: null
        };
        const pathName = [];
        this.pathList.map((item) => {
          pathName.unshift(item.name);
          PathInfo.categoryLevelPathId.unshift(item.id);
          PathInfo.rootCategoryLevelId = item.rootCategoryLevelId;
        });
        PathInfo.categoryLevelPath = pathName.join('-');
        PathInfo.categoryLevelPathId = PathInfo.categoryLevelPathId.join(',');

        console.log(PathInfo);
        this.$emit('chooseCategory', [
          this.current,
          this.title,
          PathInfo,
          ruleCode
        ]);
        this.handleClose();
      },

      // parents:用于返回的数组，childNode:要查询的节点，treeList：json树形数据
      findParent(parents, childNode, treeList) {
        for (let i = 0; i < treeList.length; i++) {
          // 父节点查询条件
          if (treeList[i].id === childNode.parentId) {
            // 如果找到结果,保存当前节点
            parents.push(treeList[i]);
            // 用当前节点再去原数据查找当前节点的父节点
            this.findParent(parents, treeList[i], this.treeList);
            break;
          } else {
            if (treeList[i].children instanceof Array) {
              //	没找到，遍历该节点的子节点
              this.findParent(parents, childNode, treeList[i].children);
            }
          }
        }
        return parents;
      }
    }
  };
</script>

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

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

    & > .el-tree-node__expand-icon {
      margin-left: 10px;
    }
  }

  ::v-deep .el-tree-node__content:hover {
    background-color: #e6f7ff !important;
  }

  ::v-deep
    .el-tree--highlight-current
    .el-tree-node.is-current
    > .el-tree-node__content {
    background-color: #40a9ff !important;
  }
</style>
