<template>
  <div flex>
    <div ref="siderBox" :style="{
        backgroundColor:
          settings.sideTheme === 'theme-dark'
            ? variables.menuBackground
            : variables.menuLightBackground,
      }">
      <!-- <news-sider
        v-if="!isConciseMode"
        :collectionsData="collectionsData"
        :sidebarRouters="sidebarRouters"
        @openChildren="openChildren"
        @closeWin="closeOpenWin"
        :routePath="routePath"
        ref="newsSiderRef"
      /> -->
      <news-sider-app :collectionsData="collectionsData" :sidebarRouters="sidebarRouters" @openChildren="openChildren"
        @closeWin="closeOpenWin" :routePath="routePath" ref="newsSiderRef" />
      <!-- @mouseleave="closeOpenWin" -->
    </div>
    <!-- v-if="childrenList.length > 0 && sidebar.childrenHide" -->
    <div @mouseleave="closeOpenWin" class="sidebar_box"
      :style="'width:' + childrenWidth + 'px;' + 'padding:' + childrenPadding">
      <div flex="cross:center main:justify;" style="margin: 15px 0; justify-content: space-between; over-flow: auto">
        <div flex="cross:center">
          <p>{{ childrenList }}</p>
          <el-autocomplete v-model="state" placeholder="请输入内容" :fetch-suggestions="querySearch"
            :trigger-on-focus="false" @select="handleSelect" class="navbarSearch" suffix-icon="el-icon-search">
          </el-autocomplete>
          <i class="el-icon-close" style="font-size: 24px; cursor: pointer; margin-left: 15px" @click="closeOpenWin" />
        </div>
      </div>
      <div flex="dir:top" flex-wrap style="height: calc(100% - 70px)">
        <children-sider ref="childrenSider" v-for="(route, index) in menuList" :key="route.path + index" :item="route"
          @refreshSider="refreshSider" @openChildren="openChildren" @clearActive="clearActive"
          @closeOpenWin="closeOpenWin" :fatherPath="fatherPath" :lastPath="lastPath" style="width: 200px" />
        <!-- <children-app-sider
          v-if="isConciseMode"
          v-for="(route, index) in childrenList"
          :key="route.path + index"
          :item="route"
          @refreshSider="refreshSider"
          @openChildren="openChildren"
          @clearActive="clearActive"
          :fatherPath="fatherPath"
          :lastPath="lastPath"
        /> -->
      </div>
    </div>
  </div>
</template>

<script>
  import {
    mapGetters,
    mapState
  } from "vuex";
  import Logo from "./Logo";
  import newsSider from "./newsSider";
  import childrenSider from "./childrenSider";
  import newsSiderApp from "./newsSiderApp";
  import childrenAppSider from "./childrenAppSider";
  import variables from "@/assets/styles/variables.scss";
  import {
    GetMyCollectionData
  } from "@/api/apis/menuManage";
  import router from "@/router";
  import loginVue from "../../../views/login.vue";

  export default {
    components: {
      Logo,
      newsSider,
      childrenSider,
      newsSiderApp,
      childrenAppSider,
    },
    computed: {
      ...mapState(["settings", "sidebar"]),
      ...mapGetters(["sidebarRouters", "sidebar"]),
      activeMenu() {
        const route = this.$route;
        const {
          meta,
          path
        } = route;
        // if set path, the sidebar will highlight the path you set
        if (meta.activeMenu) {
          return meta.activeMenu;
        }
        let pathUrl = path + "?id=" + meta.id;
        return path;
      },
      showLogo() {
        return this.$store.state.settings.sidebarLogo;
      },
      conciseMenu() {
        return true;
      },
      variables() {
        return variables;
      },
      isCollapse() {
        return !this.sidebar.opened;
      },
      defaultTheme() {
        return this.$store.state.settings.theme;
      },
    },
    watch: {
      defaultTheme: {
        handler: function (val, oldVal) {
          this.theme = val;
          this.changeBgColor(val);
        },
        immediate: true,
      },
      conciseMenu: {
        handler: function (val, oldVal) {
          this.isConciseMode = val;
          // this.changeBgColor(val);
        },
        immediate: true,
      },
      sidebar: {
        handler: function (val, oldVal) {
          if (val.opened) {
            this.state = "";
          }
        },
        deep: true,
      },
      siderBoxHeight: {
        immediate: true,
        handler() {
          this.handleResize();
        },
      },
    },
    created() {},
    data() {
      return {
        childrenPadding: 0,
        childrenWidth: 0,
        childrenList: [],
        state: "",
        fatherPath: "",
        routePath: "",
        lastPath: "",
        hoverType: false,
        firstNum: true,
        windowHeight: 0,
        siderBoxHeight: null,
        isSearch: false,
        collectionsData: [], //已收藏菜单
        valForm: {},
        isConciseMode: false,
        siderSHowType: false,
        menuList: [],
        // clientHeight: document.body.clientHeight
      };
    },
    mounted() {
      // this.GetMyCollectionData();
      this.siderBoxHeight = this.$refs.siderBox.offsetHeight;
    },
    methods: {
      handleResize() {
        // const siderBoxHeight = this.$refs.siderBox.offsetHeight;
        this.windowHeight = this.siderBoxHeight - 110;
      },
      clearActive() {
        this.$refs.newsSiderRef.activeIndex = null;
      },
      getRoute() {
        this.$store.dispatch("app/changeChildrenHide");
        let path = this.$route.path;
        this.routePath = "/" + path.split("/")[1];
        this.fatherPath = this.routePath;
        this.lastPath = path.split("/")[path.split("/").length - 1];

        this.sidebarRouters.forEach((el) => {
          if (el.path.split("/")[1] == path.split("/")[1] && el.children) {
            this.childrenList = el.children;
            this.$emit(
              "openChildren",
              this.childrenList.length > 0 ? true : false
            );
          }
        });
      },
      refreshSider() {
        this.GetMyCollectionData(true);
      },
      changeBgColor(val) {
        document
          .getElementsByTagName("body")[0]
          .style.setProperty("--bg-color", val);
      },
      hoverChilden() {
        this.hoverType = true;
        this.firstNum = false;
      },
      openChildren(val) {
        this.valForm = val;
        this.getRoute();
        this.isSearch = false;
        this.state = "";
        if (val.id != "129") {
          if (!val.children) {
            this.childrenWidth = 0;
            this.childrenPadding = 0;
            this.childrenList = [];
          } else {
            const setCollect = (arr) => {
              arr.forEach((el) => {
                el.collect = false;
                this.matchMyCollection(el);
                if (el.children != null && el.children && el.children.length) {
                  setCollect(el.children);
                }
              });
            };
            setCollect(val.children);
            this.childrenList = val.children;

            this.fatherPath = val.path;
          }
        } else {
          this.childrenList = val.children;
        }
        let menuList = [];

        function changeMenuData(data, path) {
          data.forEach((el) => {
            let menuPath = path + "/" + el.path;
            let level = el.children ? 2 : 3;
            let arr = {
              collect: el.collect,
              meta: el.meta,
              name: el.name,
              path: menuPath,
              hidden: el.hidden == "true" ? true : false || false,
              level: level,
            };
            // if(!arr.hidden){
            // }
            menuList.push(arr);
            if (el.children && el.children.length > 0) {
              changeMenuData(el.children, menuPath);
            }
          });
        }

        changeMenuData(this.childrenList, this.fatherPath);
        this.menuList = menuList;
        this.changeWidth();
        // let chilrenSum = 0
        // let notChildrenSum = 0

        // function getWidth(data) {
        // 	data.forEach(el => {
        // 		if (!el.children) {
        // 			notChildrenSum = notChildrenSum + 1
        // 		}
        // 		if (el.children && el.children.length > 0) {
        // 			// chilrenSum = chilrenSum + 1
        // 			getWidth(el.children)
        // 		}
        // 	})
        // }
        // getWidth(this.childrenList)
        // let childrenHight = notChildrenSum * 50 + chilrenSum * 34
        // // let windowHight = this.$refs.siderBox.offsetHeight - 110
        // // console.log(windowHight, "windowHight");
        // if (this.childrenList.length > 0) {
        // 	this.childrenWidth = (Math.floor(childrenHight / this.windowHeight) + 1) * 250
        // 	// console.log(this.childrenWidth, "this.childrenWidth");
        // 	this.childrenPadding = '0 20px 20px '
        // } else {
        // 	this.childrenWidth = 0
        // 	this.childrenPadding = 0
        // }
        this.$store.dispatch("app/changeChildrenHide", true);
        this.$emit("openChildren", this.childrenList.length > 0 ? true : false);
      },
      changeWidth() {
        let secondNumber = 0;
        let thirdNumber = 0;
        this.menuList.forEach((el) => {
          if (el.level == 2 && !el.hidden) {
            secondNumber = secondNumber + 1;
          } else if (el.level == 3 && !el.hidden) {
            thirdNumber = thirdNumber + 1;
          }
        });
        this.$nextTick(() => {
          let childrenHight = thirdNumber * 50 + secondNumber * 35;
          let windowHight = this.$refs.siderBox.offsetHeight - 51;
          if (this.childrenList.length > 0) {
            this.childrenPadding = "20px ";
            windowHight = windowHight - 40;
            this.childrenWidth =
              (Math.floor(childrenHight / windowHight) + 1) * 320;
          } else {
            this.childrenWidth = 0;
            this.childrenPadding = 0;
          }
          this.$emit("changeWidth", this.childrenWidth);
        });
      },
      // 获取收藏列表
      async GetMyCollectionData(collectType) {
        let res = await GetMyCollectionData({});
        if (res.code == 1) {
          const putCollectData = (res) => {
            res.forEach((el) => {
              el.collect = true;
              if (el.children != null && el.children && el.children.length) {
                putCollectData(el.children);
              }
            });
          };
          putCollectData(res.data);

          this.collectionsData = res.data;
          this.childrenList = [];
          if (collectType) {
            setTimeout(() => {
              if (this.valForm.id != "129") {
                this.openChildren(this.valForm);
              } else {
                this.openChildren(this.collectionsData[0]);
              }
            }, 1);
          }
        }
      },
      // 匹配 是否已收藏
      matchMyCollection(item) {
        const isCollectData = (res) => {
          res.forEach((el) => {
            if (el.id === item.id) {
              item.collect = true;
            }
            if (el.children != null && el.children && el.children.length) {
              isCollectData(el.children);
            }
          });
        };
        isCollectData(this.collectionsData);
      },
      // 关闭弹窗
      closeOpenWin() {
        if (this.isSearch != true) {
          this.$refs.newsSiderRef.activeIndex = null;
          this.childrenWidth = 0;
          this.childrenPadding = 0;
          this.$store.dispatch("app/changeChildrenHide", false);
        }
      },
      routerClick() {
        this.isSearch = false;
        this.closeOpenWin();
      },
      createList(row) {
        let children = [];
        const parseList = (arr, centerPath) => {
          arr.forEach((el) => {
            let path;
            if (!centerPath) {
              path = this.fatherPath + "/" + el.path;
            } else {
              path = this.fatherPath + "/" + centerPath + "/" + el.path;
            }
            let arr = {
              value: el.meta.title,
              path: path,
            };
            children.push(arr);
            if (el.children != null && el.children && el.children.length) {
              parseList(el.children, el.path);
            }
          });
        };
        parseList(row);
        return children;
      },
      getRestaurants(row) {
        let children = [];
        const restaurants = (arr, fatherPath) => {
          arr.forEach((el) => {
            let path = "";
            el.fullpath = fatherPath ? fatherPath + "/" + el.path : el.path;

            let arr = {
              value: el.meta.title,
              path: el.fullpath,
            };
            children.push(arr);
            if (el.children != null && el.children && el.children.length) {
              restaurants(el.children, el.fullpath);
            }
          });
        };
        restaurants(row);
        return children;
      },
      querySearch(queryString, cb) {
        this.isSearch = true;
        var restaurants = this.getRestaurants(this.sidebarRouters);
        var results = queryString ?
          restaurants.filter(this.createFilter(queryString)) :
          restaurants;
        cb(results);
      },

      createFilter(queryString) {
        return (restaurant) => {
          return restaurant.value.toLowerCase().indexOf(queryString) !== -1;
        };
      },
      handleSelect(item) {

        let routeData = this.$router.resolve({
          path: item.path,
        });
        window.open(routeData.href, "_self");
        this.routerClick();
        this.$refs.newsSiderRef.activeIndex = null;
        this.childrenPadding = 0;
        this.$store.dispatch("app/changeChildrenHide", false);
      },
      collectClick(item) {},
    },
  };

</script>
<style lang="scss">
  $activeColor: var(--bg-color, "#00aaff");

  .el-tree-node__content:hover,
  .el-upload-list__item:hover {
    // color: white;
    // background-color: $activeColor !important;
    background-color: #ecf5ff !important;
  }

  .el-tree-node:focus>.el-tree-node__content {
    color: white;
    background-color: $activeColor !important;
  }

  .el-tree-node.is-current>.el-tree-node__content {
    color: white;
    background-color: $activeColor !important;
  }

  .navbarSearch {
    // width: 200px !important;

    ::v-deep .el-input--medium .el-input__inner {
      border: 1px solid #bbbbbb;
      border-radius: 15px;
      background-color: transparent;
    }

    ::v-deep .el-input__suffix {
      color: #1890ff;
      font-size: 24px;
    }
  }

  ::v-deep .sidebar-container {
    z-index: 9000 !important;
  }

  .sidebar_box {
    background-color: white;
    height: 98%;
    // padding: 26px 0;
    // border-left: 4px solid #eef0f3;
    // max-width: 500px;
    // min-width: 800px;
    // padding: 0 30px 20px 30px;
    // width: calc(100% - 300px);
    transition: width 0.3s;
  }

</style>
