<template>
  <!-- 自定义 -->
  <div :style="{ height: '100%' }">
    <a-layout id="components-layout-demo-responsive" :style="{ height: '100%' }">
      <!-- 侧边栏 -->
      <a-layout-sider
        v-if="menuShow"
        breakpoint="lg"
        collapsed-width="0"
        :style="{
          background: navTheme == 'dark' ? '#001529' : 'white',
          borderRight: navTheme == 'dark' ? '' : '1px solid #e8e8e8 !important',
        }"
      >
        <div
          class="logo"
          :style="{
            margin: '0',
            color: 'white',
            background: navTheme == 'dark' ? navColor[17] : navColor[6],
            textAlign: 'center',
            height: '64px',
            cursor: 'pointer',
          }"
          @click="sideMenu({key:homePath})"
        >
          <div
            :style="{
              display: 'flex',
              alignItems: 'center',
              height: '100%',
            }"
          >
            <img
              :style="{
                width: '30px',
                heigit: '30px',
                margin: 'auto 10px auto 10px',
                borderRadius: '50%',
              }"
              src="~@/common/assets/yallaIcon.png"
              alt
            />
            <span
              :style="{
                fontWeight: '900',
                fontSize: '18px',
                color: navTheme == 'light' ? '#001529' : 'white',
              }"
            >{{ $t($store.state.homeUser.nowSiteName) }}</span>
          </div>
        </div>

        <!-- 侧边菜单 -->
        <a-menu
          v-if="menuShow"
          :theme="navTheme"
          mode="inline"
          @click="sideMenu"
          :selectedKeys="Menu.side.sideMenuSeleted"
          @openChange="openChange"
          :style="{
            borderRight: 'none !important',
          }"
        >
          <!-- <a-menu-item
            v-for="(item, key) in menus[Menu.top.key].children"
            :key="String(key)"
            @click="setTab(item)"
          >-->
          <template v-for="item in menus[Menu.top.key].children">
            <a-menu-item
              v-if="!item.children"
              :key="item.meta.id"
              v-show="!item.meta.hiddenHeaderContent"
            >
              <a-icon
                :style="{ marginRight: '5px', fontWeight: '600', fontSize: '15px' }"
                :type="item.meta.icon || ' '"
              />
              <span :style="{ fontWeight: '600', fontSize: '15px' }">
                {{
                $t(item.name)
                }}
              </span>
            </a-menu-item>
            <sub-menu v-else :key="item.meta.id" :menu-info="item" :i18nRender="i18nRender" />
          </template>
          <!-- <a-icon :type="item.meta.icon || ' '" />
          <span class="nav-text">{{ $t(item.name) }}</span>-->
          <!-- </a-menu-item> -->
        </a-menu>
      </a-layout-sider>

      <a-layout>
        <!-- 顶部 -->
        <a-layout-header
          v-show="menuShow"
          :style="{
            background: navColor[4],
            padding: 0,
            display: 'flex',
            justifyContent: 'space-between',
            alignItems:'center',
            borderBottom:`1px solid ${navColor[4]}`
          }"
        >
          <!-- <span :style="{color:'white'}">{{$t('pages.form.basicform.content')}}</span>  -->
          <!-- 顶部菜单 -->
          <a-menu
            :theme="navTheme"
            mode="horizontal"
            :default-selected-keys="['0']"
            :selectedKeys="Menu.top.topMenuSeleted"
            :style="{ lineHeight: '64px', background: navColor[4],overflow:'hidden',flex:1, }"
            class="topTitle"
            @click="topMenu"
          >
            <a-menu-item
              v-for="(item, key) in menus"
              :key="String(key)"
              v-show="!item.meta.hiddenHeaderContent"
            >
              <a-icon
                v-if="!item.meta.hiddenHeaderContent"
                :style="{ marginRight: 0, fontWeight: '900', fontSize: '16px' }"
                :type="item.meta.icon || ' '"
              />

              <span
                v-if="!item.meta.hiddenHeaderContent"
                class="text-shaw"
                :style="{ fontWeight: '900', fontSize: '15px' }"
              >{{ $t(item.name) }}</span>
            </a-menu-item>
          </a-menu>

          <!-- 顶部右边 -->
          <div class="head-set" :style="{ display: 'flex' }">
            <UserCenter :color="navTheme == 'dark' ? 'rgba(255,255,255,.8)' : 'rgba(0,0,0,.6) '" />

            <div
              class="navSearch"
              :style="{
                color:
                  navTheme == 'dark'
                    ? 'rgba(255,255,255,.8) !important'
                    : 'rgba(0,0,0,.5) !important',
              }"
            >
              <MenuSearch :menuList="menus" @selectMenu="selectMenu" @setTab="setTab" />
              <!-- 菜单搜索 -->
            </div>

            <!-- 用户中心 -->
            <!-- 布局设置 -->
            <div class="layoutSet" :style="{ margin: '0 20px' }">
              <a-popover trigger="click" placement="bottom">
                <template class="content" slot="content">
                  <a-row class="form-row" :gutter="[16, 0]" :style="{ width: '200px' }">
                    <a-col :lg="24" :md="24" :sm="24" :style="{ marginBottom: '10px' }">
                      <!-- 导航栏显示 -->
                      <div class="set-tabs">
                        <span>{{ $t("导航栏") }}：</span>
                        <a-switch
                          :checked-children="$t('开')"
                          :un-checked-children="$t('关')"
                          v-model="tabsIsShow"
                        />
                      </div>
                    </a-col>

                    <a-col :lg="24" :md="24" :sm="24">
                      <!-- 语言选择 -->
                      <div class="language">
                        <span>{{ $t("语言选择") }}：</span>
                        <a-select
                          v-model="localLang"
                          @change="languageSelected"
                          :style="{ width: '90px' }"
                        >
                          <a-select-option :value="'zh-CN'">中文</a-select-option>
                          <a-select-option :value="'en-US'">English</a-select-option>
                        </a-select>
                      </div>
                    </a-col>
                    <a-col :lg="24" :md="24" :sm="24">
                      <!-- 导航主题 -->
                      <div class="nav-theme">
                        <span>{{ $t("导航主题") }}：</span>
                        <a-select
                          v-model="navTheme"
                          @change="navThemeSelected"
                          :style="{ width: '90px' }"
                        >
                          <a-select-option :value="'dark'">dark</a-select-option>
                          <a-select-option :value="'light'">light</a-select-option>
                        </a-select>
                      </div>
                    </a-col>
                    <a-col :lg="24" :md="24" :sm="24">
                      <!-- 主题色 -->
                      <div class="nav-theme">
                        <span>{{ $t("主题颜色") }}：</span>
                        <ColorPicker
                          :style="{
                            display: 'inline-block',
                            marginLeft: '0px',
                            paddingTop: '2px',
                          }"
                          @themeColorSelected="themeColorSelected"
                        />
                      </div>
                    </a-col>
                  </a-row>
                </template>

                <div class="set">
                  <a-tooltip placement="top">
                    <template slot="title">{{ $t("布局设置") }}</template>
                    <a-icon
                      type="setting"
                      class="action"
                      :style="{
                        color:
                          navTheme == 'dark'
                            ? 'rgba(255,255,255,.8) !important'
                            : 'rgba(0,0,0,.5) !important',
                      }"
                    />
                  </a-tooltip>
                </div>
              </a-popover>
            </div>
          </div>
        </a-layout-header>

        <!-- tabs导航栏 -->
        <div
          class="Home-tabs"
          v-show="tabsIsShow && menuShow "
          :style="{ height: '40px', marginTop: '10px' }"
        >
          <Tabs ref="tabs" @selectMenu="selectMenu" @changeIsLoging="changeIsLoging"/>
        </div>

        <!-- 内容 -->
        <a-layout-content :style="{ margin: '0px 0px 0', background: '#fff' }">
          <div
            :style="{
              margin: '24px',
              background: '#fff',
            }"
          >
            <div v-show="isIframe" v-if="menuShow">
              <Ifr></Ifr>
            </div>
            <keep-alive>
              <router-view :key="$route.fullPath" v-if="isLoading"></router-view>
            </keep-alive>
            <router-view :key="$route.fullPath" v-if="!isLoading" />
          </div>
        </a-layout-content>
      </a-layout>
    </a-layout>
  </div>
</template>

<script>
import ColorPicker from "@/homeComponents/layouts/ColorPicker";
import Ifr from "@/homeComponents/components/iframe/index.vue";
import { mapState, mapActions } from "vuex";
// import { RightContent } from "@/components"; // GlobalFooter
// import { SettingDrawer, updateColorWeak } from "@ant-design-vue/pro-layout";
import {
  updateTheme,
  themeColor
} from "@/homeComponents/config/changeColor.js";
import { i18nRender } from "@/common/locales";
// import storage from "store";
// import { baseMixin } from "@/common/store/app-mixin";
import Tabs from "@/homeComponents/layouts/Tabs.vue";
import SubMenu from "@/homeComponents/layouts/subMenu.vue";
import {
  SIDEBAR_TYPE,
  TOGGLE_COLOR,
  TOGGLE_MOBILE_TYPE
} from "@/common/store/mutation-types";
import defaultSettings from "@/homeComponents/config/defaultSettings";
import UserCenter from "@/homeComponents/layouts/UserCenter";
import MenuSearch from "@/homeComponents/layouts/MenuSearch";
import {refreshIframeById} from "@/common/utils/tools.js"
export default {
  name: "BasicLayout",
  // mixins: [baseMixin], // this[xxx] store value mixin, see this file
  data() {
    this.siteTitle = defaultSettings.title;
    return {
      isLoading: true,
      routerLoadingArr:[],


      // base
      menus: [],
      // 侧栏收起状态
      collapsed: false,
      // 媒体查询
      query: {},
      homePath: "",
      nowIndex: 0,
      Menu: {
        top: {
          topMenuSeleted: undefined,
          key: 0
        },
        side: {
          sideMenuSeleted: undefined,
          key: ""
        }
      },
      localLang: window.localStorage.getItem("app_language").replace(/"/g, ""),
      tabsIsShow: true,
      openKeys: [],
      navTheme: window.localStorage.getItem("navTheme") || "dark",
      navColor: [],
      themeColor: JSON.parse(window.localStorage.getItem("color")) || "#1890FF"
    };
  },
  computed: {
    ...mapState({
      // 动态主路由
      mainMenu: state => state.homePermission.addRouters,
      isIframe: state => state.homeApp.isIframeRouter
    }),
    menuShow() {
      if (window != top) {
        return false;
      } else {
        return true;
      }
    }
  },
  created() {
    this.GetNowSiteName();

    if (this.mainMenu) {
      console.log(this.mainMenu);
      
      // bind router (绑定路由)
      const routes = this.mainMenu.find(item => item.path === "/");

      this.menus = (routes && routes.children) || [];
      // console.log(this.menus);

      // console.log(this.searchMenuKey2('/home',this.menus));
      this.homePath = this.searchMenuKey2("/home", this.menus);
      this.homePath = this.homePath[this.homePath.length - 1];

      // this.menuLanguageChange(this.menus);
      // console.log(this.menus);
    }

    // 处理侧栏收起状态
    this.$watch("collapsed", () => {
      this.$store.commit(SIDEBAR_TYPE, this.collapsed);
    });
    this.$watch("isMobile", () => {
      this.$store.commit(TOGGLE_MOBILE_TYPE, this.isMobile);
    });
  },
  mounted() {
    //根据当前hash 选定菜单
    var hash = window.location.hash.replace("#", "");
    if (hash != "/") {
      this.selectMenu(hash);
    } else {
      this.sideMenu({ key: this.homePath });
    }

    var menuInfo = this.getHashMenu(hash, this.menus);
    this.routerLoadingArr.push(menuInfo.meta.id)

    // ////console.log(this.getHashMenu(hash, this.menus));
    if (!menuInfo.children) {
      this.$refs.tabs.menus.push(menuInfo);
    }

    // const userAgent = navigator.userAgent;
    // if (userAgent.indexOf("Edge") > -1) {
    //   this.$nextTick(() => {
    //     this.collapsed = !this.collapsed;
    //     setTimeout(() => {
    //       this.collapsed = !this.collapsed;
    //     }, 16);
    //   });
    // }

    // first update color
    // THEME COLOR HANDLER!! PLEASE CHECK THAT!!
    // if (process.env.NODE_ENV !== "production" || process.env.VUE_APP_PREVIEW === "true") {
    this.navColor = themeColor.getAntdSerials(this.themeColor);
    updateTheme(this.themeColor);
    // }
    //  first update color weak
    // if (this.colorWeak) {
    //   updateColorWeak(this.colorWeak);
    // }
  },
  methods: {
    ...mapActions(["GetNowSiteName"]),
    i18nRender,
    changeIsLoging (status) {
      this.isLoading = status
      // console.log(status)
      // console.log(this.isLoading)
    },
    handleCollapse(val) {
      this.collapsed = val;
    },

    selectMenu(hash) {
      // ////console.log(hash,hash === null);
      if (hash === null) {
        this.Menu.top.topMenuSeleted = undefined;
        this.Menu.top.key = 0;
        this.Menu.side.sideMenuSeleted = undefined;
        this.Menu.side.key = 0;
      } else {
        var arr = this.searchMenuKey(hash, this.menus);
        var arr2 = this.searchMenuKey2(hash, this.menus);
        arr2 = arr2.reverse();
        arr2.splice(arr2.length - 1, 1);
        //console.log(arr2);
        if (arr) {
          if (arr.length > 0) {
            this.Menu.top.topMenuSeleted = [String(arr[0])];
            this.Menu.top.key = arr[0];
          }
          if (arr.length > 1) {
            this.Menu.side.sideMenuSeleted = arr2;
            this.Menu.side.key = arr[1];
          }
        }
      }
    },

    //点击 侧边栏菜单 更新 tabs
    setTab(menuInfo) {
      // console.log('22222',menuInfo);

      // ////console.log(menuInfo);
      var flag = true;
      // //////console.log(menuInfo);
      // //////console.log(this.$refs.tabs.menus);
      if (this.$refs.tabs.menus.length > 0) {
        this.$refs.tabs.menus.forEach(item => {
          if (item.meta.id == menuInfo.meta.id) {
            // //////console.log(this.$refs.tabs.activeKey);
            this.$refs.tabs.activeKey = item.meta.id;
            flag = false;
          }
        });
      }

      flag ? this.$refs.tabs.menus.push(menuInfo) : "";
    },

    //查找菜单 生成 index数组
    searchMenuKey(hash, nodes, arr) {
      if (!arr) {
        var arr = [];
      }
      // arr.concat(arr1)
      for (var i = 0; i < nodes.length; i++) {
        var tmpPath = arr.concat();
        tmpPath.push(i);

        if (nodes[i].path == hash) {
          // //////console.log(tmpPath)
          return tmpPath;
        }
        // debugger;
        if (nodes[i].children) {
          var findResult = this.searchMenuKey(hash, nodes[i].children, tmpPath);
          // //////console.log(findResult,'2')
          if (findResult) {
            return findResult;
          }
        }
      }
    },
    searchMenuKey2(hash, nodes, arr) {
      if (!arr) {
        var arr = [];
      }
      // arr.concat(arr1)
      for (var i = 0; i < nodes.length; i++) {
        var tmpPath = arr.concat();
        tmpPath.push(nodes[i].meta.id);

        if (nodes[i].path == hash) {
          // //////console.log(tmpPath)
          return tmpPath;
        }
        // debugger;
        if (nodes[i].children) {
          var findResult = this.searchMenuKey2(
            hash,
            nodes[i].children,
            tmpPath
          );
          // //////console.log(findResult,'2')
          if (findResult) {
            return findResult;
          }
        }
      }
    },

    getHashMenu(hash, nodes, arr) {
      if (!arr) {
        var arr = {};
      }
      for (var i = 0; i < nodes.length; i++) {
        if (nodes[i].path == hash) {
          arr = nodes[i];
          return arr;
        }
        if (nodes[i].children) {
          var findResult = this.getHashMenu(hash, nodes[i].children, arr);
          if (findResult) {
            return findResult;
          }
        }
      }
    },
    pushFatherArr(id, nodes, path) {
      if (path == undefined) {
        path = [];
      }
      for (var i = 0; i < nodes.length; i++) {
        var tmpPath = path.concat();
        tmpPath.push(nodes[i].meta.id);
        if (id == nodes[i].meta.id) {
          return tmpPath;
        }
        if (nodes[i].children) {
          var findResult = this.pushFatherArr(id, nodes[i].children, tmpPath);
          if (findResult) {
            return findResult;
          }
        }
      }
    },
    getSideKeyArr(id) {
      var sideKey = this.pushFatherArr(id, this.menus).reverse();
      sideKey.splice(sideKey.length - 1, 1);
      return sideKey;
    },

    openChange(openKeys) {
      ////console.log(openKeys);
      if (this.openKeys.length < openKeys.length) {
        if (openKeys.length > 0) {
          // ////console.log(this.getRouteInfo(openKeys[openKeys.length - 1], this.menus));
          var menuInfo = this.getRouteInfo(
            openKeys[openKeys.length - 1],
            this.menus
          );

          var { path } = menuInfo;
          if (path != "/") {
            this.setTab(menuInfo);
            this.$router.push({ path: path });
          }
        }
      }
      this.openKeys = openKeys;
    },

    sideMenu({ item, key, keyPath }) {
      //console.log(item, key, keyPath);
      // console.log('点击侧边栏');
      var menuInfo = this.getRouteInfo(key, this.menus);
      
      if(this.routerLoadingArr.indexOf(key) === -1){
        this.routerLoadingArr.push(key);
        this.isLoading = true;
      }else{
        // console.log(1111111111111,this.getRouteInfo(key, this.menus));
        
        if(menuInfo.meta.isIframe){
          try{
            refreshIframeById(key);

          }catch(error){
            console.error(error);
            
          }
          // console.log('这里调用刷新Iframe方法？？');
          
        }
        this.isLoading = false;
      }
      this.Menu.side.sideMenuSeleted = this.getSideKeyArr(key);
      this.Menu.side.key = key;
      // //console.log(this.menus);
      //console.log(this.Menu.side.sideMenuSeleted);

      // this.getRouteInfo(key,this.menus)
      // console.log(key);
      this.setTab(menuInfo);
      // ////console.log();
      var { path } = menuInfo;
      // // //////console.log(this.menus[this.Menu.top.key].children[this.Menu.side.key].path);
      this.$router.push({ path: path });
    },
    getRouteInfo(id, obj, info) {
      if (!info) {
        var info = {};
      }
      for (var i = 0; i < obj.length; i++) {
        if (obj[i].meta.id == id) {
          this.menuInfo = obj[i];
          return obj[i];
        }

        //  ////console.log(obj[i].meta.id,'继续');
        if (obj[i].children && obj[i].children.length > 0) {
          var result = this.getRouteInfo(id, obj[i].children, info);
          if (result) {
            return result;
          }
        }
      }
    },

    topMenu({ item, key, keyPath }) {
      // ////console.log(item, key, keyPath);
      // if (this.Menu.top.topMenuSeleted != keyPath) {
      this.Menu.top.topMenuSeleted = keyPath;
      this.Menu.top.key = key;
      this.Menu.side.sideMenuSeleted = undefined;

      // this.$refs.tabs.activeKey = null; //点击顶部 tabs选中效果清空
      // var routerPath = this.menus[this.Menu.top.key].path; //获取 路径
      // ////console.log(this.menus[this.Menu.top.key]);
      // this.$router.push({ path: routerPath }); //路由跳转
      // }
    },

    languageSelected(key) {
      //////console.log(key);
      this.$store.dispatch("setLang", key);

      try {
        this.localLang = key.key.replace(/"/g, "");
      } catch (error) {}
      // this.menuLanguageChange(this.menus);
    },
    menuLanguageChange(obj) {
      return obj.map(item => {
        item.name = this.$t(item.name);
        if (item.children && item.children.length > 0) {
          this.menuLanguageChange(item.children);
        }
        return item;
      });
    },
    navThemeSelected(val) {
      window.localStorage.setItem("navTheme", val);
    },
    themeColorSelected(val) {
      // console.log(val);
      this.navColor = themeColor.getAntdSerials(val);
      // console.log(this.navColor);
      window.localStorage.setItem("color", val);
      this.$store.commit(TOGGLE_COLOR, val);
      updateTheme(val);
    }
  },
  components: {
    // RightContent,
    // GlobalFooter,
    // SettingDrawer,
    UserCenter,
    MenuSearch,
    Tabs,
    "sub-menu": SubMenu,
    ColorPicker,
    Ifr
  }
};
</script>

<style lang="less">
@import "./BasicLayout.less";
.table {
  position: relative;
}
main {
  position: relative;
}
.pageCount {
  position: absolute;
  bottom: 0;
  width: 200px;
}
.action {
  color: inherit !important;
}
.ant-layout-sider-zero-width-trigger {
  top: 250px !important;
}
.ant-cascader-menu-item-active:not(.ant-cascader-menu-item-disabled),
.ant-cascader-menu-item-active:not(.ant-cascader-menu-item-disabled):hover {
  background-color: #ccc !important;
}
.ant-layout-content {
  min-height: initial !important;
}
</style>
