<template>
  <view class="Select-Organization">
    <view class="bar">
      <span>组织切换</span>
      <uni-icons size="15"
                 type="closeempty"
                 @click="tab"></uni-icons>
    </view>
    <view class="search_input">
      <uni-easyinput class="uni-mt-5"
                     suffixIcon="close"
                     v-model="value"
                     placeholder="检索组织"
                     @iconClick="clear"
                     @input="input"></uni-easyinput>
    </view>
    <view class="card_box">
      <uni-section title="组织机构"
                   type="line">
        <tui-loading :src="loading"
                     v-if="showLoading"></tui-loading>
        <tui-tree-view :treeData="treeData"
                       @click="onClick"></tui-tree-view>
      </uni-section>
    </view>
    <tui-tips ref="toast"
              position="center"></tui-tips>
  </view>
</template>
<script>
import HttpCache from "../../common/cache";
import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
import { clearMenu, getFlattenMenu, setMenu } from "../../utils";
import { initOwnedRoutes, isAccessCurrentPage } from "../../router";
import { getCurrentOrg } from "../../common/httpRequest";

export default {
  name: "Select-Organization",
  data() {
    return {
      showLoading: false,
      // loading动画
      loading: "/static/images/sxlq/loading.png",
      // input
      value: "",
      // 搜索组织data
      searchTreeData: [],
      // 当前树展示数据data
      treeData: [],
    };
  },
  computed: {
    ...mapState(["APIHOST", "nowSelectOrganizationInfo"]),
  },
  mounted() {
    this.getList();
  },
  methods: {
    ...mapMutations(["setNowSelectOrganizationInfo"]),
    // 切换组织
    tab() {
      const { id, name } = this.nowSelectOrganizationInfo;
      if (!id && !name) {
        this.showTips();
        return;
      }
      this.nowSelectOrganizationInfo.show = false;
    },
    // 消息提示
    showTips() {
      let options = {
        msg: "请选择当前组织",
        duration: 2000,
      };
      //需等组件初始化完成，确认已获取到组件实例
      this.$refs.toast && this.$refs.toast.showTips(options);
    },
    // 选中的数据
    async onClick(selectedValue) {
      const { text, value } = selectedValue;
      if (value.disabled) {
        return;
      }
      // 显示loading
      this.showLoading = true;
      console.log("选中内容:", selectedValue);
      this.$emit("id-change", selectedValue);
      this.setNowSelectOrganizationInfo({
        text,
        value,
      });
      try {
        // 更新菜单
        const res = await getApp().globalData.request.post(
          `common/Login/loginService?org_id=${value.id}`,
          uni.getStorage({ key: "sxlq_token" })
        );
        if (res.code === -1) {
          throw new Error(res.data.msg);
        }
        const mobileMenu = res.data.menu[0];
        clearMenu();
        setMenu(mobileMenu);
        // console.log('请求获取的资源loginService:',mobileMenu);
        initOwnedRoutes(getFlattenMenu());
        //权限判断当前路由
        if (!isAccessCurrentPage()) {
          uni.reLaunch({
            url: "/pages/home/index/index",
            success: () => {
              setTimeout(() => {
                uni.showToast({
                  title: "无权访问，已为您切换首页",
                  icon: "none",
                });
              }, 0);
            },
          });
        }
      } catch (error) {
        console.error(error);
      }
      // 触发自定义事件，并传递选中的值
      this.$emit("select-value", selectedValue);
      // 触发自定义事件
      this.$emit("toggle-organization");
      this.showLoading = false;
    },
    // 清空输入框内容
    clear(clearValue) {
      this.value = "";
      this.searchTreeData = [];
      this.getList();
    },
    // 输入框value事件
    input(inputValue) {
      this.value = inputValue;
      // console.log('搜索时this.search:',this.search);
      this.debounce(this.search, 500)();
    },
    // 获取所有组织
    getList() {
      this.showLoading = true;
      // 获取用户唯一id
      uni.getStorage({
        key: "sxlq_token",
        success: (res) => {
          var responsePromise = getApp().globalData.request.post(
            "common/Login/loginService",
            res.data
          );
          responsePromise
            .then((response) => {
              if (response.code !== -1) {
                this.showLoading = false;
                this.treeData = this.mapTreeData(response.data.org);
                this.searchTreeData = response.data.org;
                HttpCache.put("sxlq_menu", response.data.menu);
              }
            })
            .catch((error) => {
              console.error("Error:", error);
            });
        },
      });
    },
    search() {
      const flattenData = this.flattenTreeData(this.searchTreeData); //逆向递归返回扁平数据
      const searchResults = flattenData.filter((data) =>
        data.name.includes(this.value)
      );
      var uniqueArray = [];
      for (var item of searchResults) {
        uniqueArray = uniqueArray.concat(
          this.getAllParent(flattenData, item.pid)
        );
        uniqueArray = uniqueArray.concat(item);
      }
      // 去重扁平数据
      uniqueArray = Array.from(new Set(uniqueArray));
      // 扁平数据转换成树形数据
      const tree = this.buildTree(uniqueArray);
      // 映射搜索树形数据
      const mapTree = this.mapSearchData(tree);
      this.treeData = mapTree;
    },
    // 获取父级id
    getAllParent(data, pid) {
      var temp = [];
      for (var item of data) {
        if (item.id == pid) {
          temp.push(item);
          temp = temp.concat(this.getAllParent(data, item.pid));
        }
      }
      return temp;
    },
    // 递归转换成树形结构
    buildTree(data) {
      const map = {};
      const treeData = [];

      data.forEach((item) => {
        map[item.id] = {
          ...item,
          children: [],
        };
      });

      data.forEach((item) => {
        if (item.pid && map[item.pid]) {
          map[item.pid].children.push(map[item.id]);
        } else {
          treeData.push(map[item.id]);
        }
      });

      return treeData;
    },
    /**逆向递归返回扁平数据 */
    flattenTreeData(treeData) {
      const flattenData = [];

      function traverse(node, parent) {
        const flattenedNode = {
          id: node.id,
          pid: parent ? parent.id : null,
          name: node.name,
        };

        flattenData.push(flattenedNode);

        if (node.child && node.child.length > 0) {
          node.child.forEach((childNode) => {
            traverse(childNode, node);
          });
        }
      }

      treeData.forEach((node) => {
        traverse(node, null);
      });

      return flattenData;
    },

    // 映射所有字段tree
    mapTreeData(data) {
      return data.map((item) => ({
        collapsed: !item.disabled,
        value: item,
        text: item.name,
        disabled: item.disabled,
        children: item.child ? this.mapTreeData(item.child) : [],
      }));
    },
    // 映射搜索tree
    mapSearchData(treeData) {
      return treeData.map((node) => {
        const { id, name, children } = node;
        const newNode = {
          value: { id, name },
          text: name,
          collapsed: false,
          children: this.mapSearchData(children),
        };
        return newNode;
      });
    },
    // 防抖函数
    debounce(func, wait) {
      let timeout;

      return function () {
        let context = this; // 保存this指向
        let args = arguments; // 拿到event对象

        clearTimeout(timeout);
        timeout = setTimeout(function () {
          func.apply(context, args);
        }, wait);
      };
    },
  },
};
</script>

<style lang="scss">
.Select-Organization {
  height: 100vh;
  width: 100vw;
  position: absolute;
  background: #fff;
  z-index: 9999;
}
::v-deep .disabled {
  color: #999 !important;

  .tui-treeview__triangle {
    border-left: var(--tui-treeview-triangle-bl, 8px) solid #999;
  }
}

.bar {
  padding: 25rpx 25rpx;
  display: flex;
  align-items: center;

  span {
    flex: 1;
    font-size: 28rpx;
    text-align: center;
  }
}

.search_input {
  width: 95%;
  margin: 0px auto;
}

.card_box {
  width: 95%;
  margin: 50rpx auto 0;

  .test {
    padding-left: 30rpx;
  }
}

page {
  --tui-treeview-label-padding: 10px 15px;
  /*节点padding值*/
  --tui-treeview-label-border: 0;
  /*节点border*/
  --tui-treeview-label-margin: 0;
  /*节点margin*/
  --tui-treeview-label-radius: 0;
  /*节点圆角值*/
  --tui-treeview-label-bgcolor: transparent;
  /*节点背景色*/
  --tui-treeview-label-color: #000;
  /*节点文本颜色*/
  --tui-treeview-label-size: 26rpx;
  /*节点文本大小*/
  --tui-treeview-icon-width: 20px;
  /*节点图标宽度*/
  --tui-treeview-icon-height: 20px;
  /*节点图标高度*/
  --tui-treeview-icon-mr: 8px;
  /*节点图标 margin-right值*/
  --tui-treeview-children-pl: 20px;
  /*子节点padding-left值*/
  --tui-treeview-triangle-bt: 4px;
  /*三角箭头border-top宽度*/
  --tui-treeview-triangle-bl: 6px;
  /*三角箭头border-left宽度*/
  --tui-treeview-triangle-mr: 15px;
  /*三角箭头margin-right*/
}
</style>
