<template>
  <div class="header-btn" v-show="isShowGroup">
    <el-popover
      placement="bottom"
      trigger="hover"
      popper-class="user-group-popover"
      :visible-arrow="false"
      v-model="visible"
    >
      <div class="changeBox">
        <div class="title-content">
          <span>{{ isUserList ? "切换用户" : "所选组织架构" }}</span>
          <img
            src="@/assets/images/headerImg/icon5-active.png"
            v-if="!isUserList"
            @click="showGroup"
          />
          <img
            src="@/assets/images/headerImg/icon6.png"
            v-if="!isUserList"
            @click="isUserList = true"
          />
          <img
            src="@/assets/images/headerImg/icon5.png"
            v-if="isUserList"
            @click="showGroup"
          />
          <img
            src="@/assets/images/headerImg/icon6-active.png"
            v-if="isUserList"
            @click="isUserList = true"
          />
          <!-- <i
            class="el-icon-arrow-left"
            style="cursor: pointer;"
            @click="isUserList = true"
          ></i>
          <i
            class="el-icon-arrow-right"
            style="cursor: pointer;"
            @click="isUserList = false"
          ></i> -->
        </div>
        <div
          class="content-list"
          :style="{ height: groupListData.length > 4 ? '300px' : 'auto' }"
          v-if="isUserList"
        >
          <vue-scroll style="height: 100%" v-if="groupListData.length > 0">
            <div
              class="content-list-item"
              v-for="(item, index) in groupListData"
              :key="index"
              @click="selectGroup(item)"
            >
              <!-- <i class="el-icon-trophy-1"></i> -->
              <img src="@/assets/images/headerImg/icon3.png" />
              <span>{{ item.companyName }}</span>
              <i class="el-icon-arrow-right"></i>
            </div>
          </vue-scroll>
          <div v-else class="nodata">暂无数据</div>
          <!-- <div class="content-list-item" @click="selectGroup()">
            <img src="@/assets/images/headerImg/icon4.png" />
            <span>{{ $store.state.userInfo.account }}</span>
            <div>个人租户</div>
            <i class="el-icon-arrow-right"></i>
          </div> -->
        </div>
        <div class="tree-group" v-else>
          <div
            class="select-list"
            :style="{ height: selectedGroupData.length > 4 ? '300px' : 'auto' }"
          >
            <vue-scroll style="height: 100%">
              <el-input
                placeholder="输入关键字进行查找"
                v-model="filterText"
                style="width: 98%"
                suffix-icon="el-icon-search"
                size="medium"
              >
              </el-input>
              <el-tree
                :data="selectedGroupData"
                :default-expanded-keys="expandKey"
                :default-expand-all="false"
                node-key="sn"
                ref="tree"
                :props="selectTreeProps"
                :filter-node-method="filterNode"
                :highlight-current="true"
                :check-on-click-node="false"
                style="margin: 10px 5px"
              >
                <span class="custom-tree-node" slot-scope="{ node, data }">
                  <span
                    style="
                      width: 100%;
                      overflow: hidden;
                      text-overflow: ellipsis;
                      white-space: nowrap;
                      display: inline-block;
                    "
                    @click="treeClick(data)"
                    :class="data.projectSn ? 'projectStyle' : 'companyStyle'"
                    :title="node.label"
                    >{{ node.label }}</span
                  >
                </span>
              </el-tree>
            </vue-scroll>
          </div>
        </div>
      </div>
      <!-- 点击内容 -->
      <div slot="reference" class="click-content">
        <!-- <i class="el-icon-trophy-1"></i> -->
        <img src="@/assets/images/headerImg/icon1.png" />
        <span
          v-if="
            $store.state.currentProDetail && $store.state.currentProDetail.name
          "
          :title="$store.state.currentProDetail.name"
          >{{ $store.state.currentProDetail.name }}</span
        >
        <span v-else :title="$store.state.userInfo.account">{{
          $store.state.userInfo.account
        }}</span>
        <i class="el-icon-arrow-down"></i>
      </div>
    </el-popover>
  </div>
</template>
<script>
import { getGroupListApi } from "@/assets/js/api/loginSign.js";
import { getComapnyStatisticsSupplierListApi } from "@/assets/js/api/company/project";
import { getNewUserAllModulePageApi } from "@/assets/js/api/jxjadmin.js";
export default {
  data() {
    return {
      visible: false,
      isUserList: true,
      filterText: "",
      selectTreeProps: {
        children: "list",
        label: "name",
      },
      groupListData: [],
      selectedGroupData: [],
      selectedProjectSn: "",
      expandKey: [],
      selectFirst: 0,
      isShowGroup: false,
      selectGroupFirst: 0,
      workSpaceShow: false,
    };
  },
  created() {
    console.log(this.$store.state.groupTreeList, "测试进入123456");
    if (this.$store.state.userInfo.headquartersSn) {
      console.log(this.$store.state.groupTreeList, "测试进入123456");
      this.getGroupTreeData();
    }
    if (this.$store.state.projectSn) {
      this.selectedProjectSn = this.$store.state.projectSn;
      this.expandKey = [this.selectedProjectSn];
    }
    this.loadData();
    this.getModuleList();
  },
  mounted() {},
  methods: {
    // 查询全部模块(拿到工作流的模块菜单)
    getModuleList() {
      getNewUserAllModulePageApi({
        projectSn: this.$store.state.projectSn,
        moduleType: 7,
        userId: this.$store.state.userInfo.userId,
      }).then((res) => {
        let all = res.result.moduleList;
        if (all.length == 0) {
          this.workSpaceShow = false;
          return;
        } else {
          this.workSpaceShow = true;
        }
      });
    },
    // 获取是否只有一个企业一个项目，只有一个企业一个项目时隐藏
    loadData() {
      let that = this;
      let sn = this.$store.state.userInfo.headquartersSn;
      let projectType = 1; // 展示项目列表
      // if (this.$store.state.userInfo.addProjectType == 1) {
      //   projectType = 0; // 不展示项目列表
      // }
      getComapnyStatisticsSupplierListApi({
        sn: sn,
        projectType: projectType,
      }).then((res) => {
        console.log(res, 666555444);
        if (res.result && res.result.companyList) {
          if (res.result.companyList.length > 1) {
            that.isShowGroup = true;
          } else {
            if (res.result.companyList.length == 1) {
              that.selectShowGroup(res.result.companyList[0]);
            } else {
              that.isShowGroup = false;
            }
          }
        }
      });
    },
    // 选中组织中的项目级
    selectShowGroup(obj) {
      console.log(obj, "111222333");
      if (!obj) return;
      if (obj.list && obj.list.length > 0) {
        obj.list.map((item) => {
          this.selectShowGroup(item);
        });
      } else {
        if (this.selectGroupFirst === 0) {
          // 加判断是为了在循环中只选中第一个
          this.isShowGroup = false;
        } else {
          this.isShowGroup = true;
        }
        // this.setTreeActive();
        this.selectGroupFirst = 1;
      }
    },
    // 处理组织架构树形数据
    filterTreeData(tree) {
      tree.forEach((node) => {
        if (!node.projectSn) {
          node.disabled = true;
        }
        if (node.list && node.list.length) {
          this.filterTreeData(node.list);
        }
      });
    },
    // 展示组织架构内容
    showGroup() {
      this.isUserList = false;
      this.setTreeActive();
    },
    // 选中组织中的项目级
    selectProject(obj) {
      console.log(obj, "111222333");
      if (!obj) return;
      if (obj.list && obj.list.length > 0) {
        obj.list.map((item) => {
          this.selectProject(item);
        });
      } else {
        if (this.selectFirst === 0) {
          // 加判断是为了在循环中只选中第一个
          this.selectedProjectSn = obj.sn;
          this.expandKey = [this.selectedProjectSn];
          // 修改全局projectSn
          this.$store.commit("setProjectSn", obj.sn);
          this.$store.commit("setProDetail", obj);
        }
        this.setTreeActive();
        this.selectFirst = 1;
      }
    },
    // 设置树形的选中项目样式
    setTreeActive() {
      this.$nextTick(() => {
        let activeSn = this.$store.state.projectSn || this.selectedProjectSn;
        if (activeSn) {
          this.$refs.tree.setCurrentKey(activeSn);
        }
      });
    },
    // 选中组织
    selectGroup(item) {
      if (item) {
        this.selectedGroupData = [item];
        this.$store.commit("setSelectedGroupSn", item.companySn); // 存储选中的组织Sn
        this.filterTreeData(this.selectedGroupData);
        if (this.workSpaceShow) {
          if (this.$route.path.indexOf("supplier") == -1) {
            this.$router.push("/workSpace");
          } else {
            this.$router.push("/supplierIndex");
          }
        } else {
          this.$router.push("/projectIndex");
        }
        console.log(this.selectedGroupData);
      } else {
        this.selectedGroupData = [];
        this.$store.commit("setProjectSn", "");
        this.$store.commit("setProDetail", null);
      }
      this.isUserList = false;
      this.getGroupTreeData();
      this.selectFirst = 0;
      // this.$nextTick(() => {
      //   this.selectProject(item);
      // });
    },
    // 获取组织树数据
    getGroupTreeData() {
      this.groupListData = this.$store.state.groupTreeList;
      console.log(this.groupListData, "我的组织机构123456");
      if (!this.groupListData) return;
      this.isUserList = false;
      let requestData = {
        userId: this.$store.state.userInfo.userId,
        headquartersSn:
          this.$store.state.selectedGroupSn ||
          this.$store.state.userInfo.headquartersSn,
      };
      getGroupListApi(requestData).then((res) => {
        console.log(res, "我的组织机构");
        if (res && res.result) {
          this.selectedGroupData = res.result;
          this.filterTreeData(this.selectedGroupData);
          this.$nextTick(() => {
            // 默认选中项目
            if (
              this.$route.path.indexOf("/supplierIndex") != -1 &&
              !this.$store.state.projectSn
            ) {
              this.selectProject(this.selectedGroupData[0]);
            } else {
              this.setTreeActive();
            }
          });
        }
      });
      // 以前的版本处理方法
      // let findItem = this.groupListData.find((item) => {
      //   return item.sn == this.$store.state.selectedGroupSn;
      // });
      // if (findItem) {
      //   this.$store.commit("setSelectedGroupSn", findItem.sn); // 存储选中的组织Sn
      //   this.selectedGroupData = [findItem]
      //   this.filterTreeData(this.selectedGroupData);
      //   this.$nextTick(() => {
      //     this.selectProject(findItem);
      //   });
      // }
    },
    // 树形控件点击
    treeClick(data) {
      console.log(data);
      if (data.projectSn) {
        this.selectedProjectSn = data.projectSn;
        // 修改全局projectSn
        this.$store.commit("setProjectSn", data.projectSn);
        this.$store.commit("setProDetail", data);
        // 收起popover
        this.visible = false;
      }
      if (this.workSpaceShow) {
        if (this.$route.path.indexOf("supplier") == -1) {
          this.$router.push("/workSpace");
        } else {
          this.$router.push("/supplierIndex");
        }
      } else {
        this.$router.push("/projectIndex");
      }
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
};
</script>
<style lang="less" scoped>
.flexStyle() {
  display: flex;
  align-items: center;
}
.changeBox {
  padding: 0px 10px;
  .title-content {
    .flexStyle();
    > span {
      font-size: 16px;
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      color: #000000;
      margin-right: auto;
    }
    img {
      width: 15px;
      height: 15px;
      cursor: pointer;
      margin-left: 5px;
    }
  }
  .content-list {
    margin-top: 15px;
    &-item {
      .flexStyle();
      padding: 10px 15px;
      border: 1px solid #dadbdb;
      border-radius: 5px;
      cursor: pointer;
      img {
        width: 30px;
        height: 30px;
      }
      // >div{
      //   border: 1px solid #7299F8;
      //   border-radius: 5px;
      //   background-color: #E3F6FF;
      //   padding: 5px 15px;
      //   color: #5A88F7;
      // }
      > span:nth-child(2) {
        margin: 2px 10px 0px 10px;
      }
      > div {
        padding: 3px 10px;
        color: #79acfa;
        background-color: #e4f5ff;
        border: 1px solid #99c3fb;
        border-radius: 5px;
        margin-top: 2px;
        font-size: 10px;
      }
      /deep/.el-icon-arrow-right {
        margin-left: auto;
      }
    }
    &-item:not(:last-child) {
      margin-bottom: 10px;
    }
    .nodata {
      text-align: center;
      padding-top: 20px;
    }
  }
  .tree-group {
    margin-top: 15px;
    background-color: #fff;
    .select-list {
      .custom-tree-node {
        width: 100%;
        .flexStyle();
        .projectStyle {
          font-family: Source Han Sans CN, Source Han Sans CN;
          font-weight: 400;
          color: #272d45;
        }
        .companyStyle {
          font-family: Source Han Sans CN, Source Han Sans CN;
          font-weight: 400;
          color: #a2a4af;
        }
      }
    }
  }
}
.click-content {
  cursor: pointer;
  .flexStyle();
  img {
    width: 20px;
    height: 20px;
  }
  > span {
    display: inline-block;
    max-width: 77px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin: 0px 10px;
  }
}
</style>
<style>
.user-group-popover {
  min-width: 300px;
  box-sizing: content-box !important;
}
</style>
