<template>
  <div class="dc-left-menu-container">
    <div class="dc-left-menu-box">
      <!-- <a-menu v-model="selectedKeys" :openKeys.sync="!collapsed ? openKeys : openKeysOnCollapsed" :inline-fold="collapsed" :inline-indent="16" @openChange="onOpenChange" @click="handleMenuClick" class="dc-left-menu" mode="inline">
        <template v-for="menu in menus">
          <a-menu-item v-if="!menu.children" :key="menu.key">
            <span class="anticon" v-if="menu.icon">
              <span class="iconfont dc-iconfont" :class="menu.icon"></span>
            </span>
            <img v-else class="anticon" style="width: 14px; height: 14px" :src="menuSvg" />
            <span class="dc-text">{{ menu.title }}</span>
          </a-menu-item>
          <sub-menu v-else :key="menu.key" :menu-info="menu" :collapsed="collapsed" />
        </template>
      </a-menu> -->
      <div :style="{ borderRadius: '3px' }">
        <t-menu width="228px" v-model="selectedKeys[0]" :collapsed="collapsed">
          <template v-for="menu in menus">
            <t-menu-item :key="menu.key" :value="menu.key" v-if="!menu.children" @click="handleMenuClick(menu)">
              <!-- <template #icon>
                <span class="anticon" v-if="menu.icon">
                  <span class="iconfont dc-iconfont" :class="menu.icon"></span>
                </span>
                <img v-else class="anticon" style="width: 14px; height: 14px" :src="menuSvg" />
              </template> -->
              <template #icon>
                <!-- <t-icon name="add"></t-icon> -->
                <icon-font class="dhcc-icon" :name="`${getIconByName(menu.icon)}`" :url="newIconfontUrl"></icon-font>
              </template>
              {{ menu.title }}
            </t-menu-item>
            <t-submenu v-else :key="menu.key" :name="menu.key" :value="menu.key" :title="menu.title">
              <template #icon>
                <!-- <t-icon name="add"></t-icon> -->
                <icon-font class="dhcc-icon" :name="`${getIconByName(menu.icon)}`" :url="newIconfontUrl"></icon-font>
              </template>
              <t-menu-item v-for="menuChildren in menu.children" :value="menuChildren.key" :key="menuChildren.key" @click="handleMenuClick(menuChildren)">
                <span>{{ menuChildren.title }}</span>
              </t-menu-item>
            </t-submenu>
          </template>
        </t-menu>
      </div>
    </div>
    <div class="dc-menu-fold">
      <t-button variant="text" class="dc-menu-fold-btn" block @click="toggleCollapsed">
        <t-icon :name="collapsed ? 'menu-fold' : 'menu-unfold'" />
        <div class="dc-menu-fold-btn-text" v-if="!collapsed">收起导航</div>
      </t-button>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Emit, Prop, Vue, Watch } from "vue-property-decorator";
import { NavMenu } from "../../model/NavMenu";
import { beanUtilsService } from "../../services/bean-utils.service";
import { routeTopologyService } from "../../services/route-topology.service";
import { Code } from "../../constants/enum/code.enum";
import { apiService } from "../../services/api.service";
import { RestfulResponse } from "../../model/RestfulResponse";
import { RestApi } from "../../model/RestApi";
import sysMenuInfoApi from "../../constants/api/sys-menu-info.api";
import { SysMenuInfo } from "../../model/SysMenuInfo";
import { menuTreeConvertService } from "../../services/menu-tree-convert.service";
import { MENU_SVG_XML } from "../../constants/encode-assets/svg";
import { ConnectType } from "../../constants/enum/connect-type.enum";
import { IconFont } from "tdesign-icons-vue";

@Component({
  name: "LeftMenu",
  components: {
    IconFont,
  },
})
export default class LeftMenu extends Vue {
  selectedKeys: string[] = []; // 当前激活的菜单编号集合
  openKeys: string[] = []; // 当前展开的菜单编号集合-暂未使用
  menus: NavMenu[] = []; // 动态菜单列表
  openKeysOnCollapsed: string[] = []; // 闭合时的父级菜单集合
  menuSvg: any = MENU_SVG_XML; // 默认菜单图标
  @Prop({ default: () => false }) collapsed!: boolean; // 左侧菜单闭合标识
  @Prop({ default: () => [] }) staticMenus!: NavMenu[]; // 静态菜单列表
  @Prop({ default: () => true }) dynamic!: boolean; // 是否动态加载
  newIconfontUrl = ""; // 默认菜单图标

  mounted() {
    console.log(this.$dc);
    this.newIconfontUrl = this.$dc.iconUrl;
    if (this.dynamic) {
      this.handleSearch();
    } else {
      this.onStaticMenusChange(this.staticMenus);
    }
  }

  /**
   * @description: 静态数据监听
   * @author ChenRui
   * @date 2021/9/15 16:01
   */
  @Watch("staticMenus")
  onStaticMenusChange(val: NavMenu[]): void {
    if (!this.dynamic) {
      this.menus = this.staticMenus || [];
    }
  }

  /**
   * @description: 闭合标识消息弹射
   * @author ChenRui
   * @date 2021/8/9 15:51
   */
  @Emit("update:collapsed")
  toggleCollapsed() {
    return !this.collapsed;
  }

  /**
   * @description: 路由变化监听
   * @author ChenRui
   * @date 2021/8/9 15:51
   */
  @Watch("$route")
  onRouteChanged() {
    this.navPosition();
  }

  @Watch("collapsed")
  onCollapsedChanged(newVal: boolean) {
    if (newVal) {
      this.openKeys = [];
    }
  }

  /**
   * @description: 动态查找菜单信息
   * @author ChenRui
   * @date 2021/8/9 15:12
   */
  handleSearch(): void {
    const query = {
      appId: this.$dc.sysId,
    };
    const restApi: RestApi = new RestApi(sysMenuInfoApi.queryAuthorizedMenuByAppId);
    restApi.url = this.$dc.baseApi + sysMenuInfoApi.queryAuthorizedMenuByAppId.url;
    apiService.general(restApi, query).then((response: RestfulResponse) => {
      if (response.code === Code.SUCCESS.code) {
        if (response.data && response.data.length > 0) {
          const sysMenuInfos: SysMenuInfo[] = response.data;
          const navMenus: NavMenu[] = menuTreeConvertService.menuToNavMenu(sysMenuInfos);
          this.menus = navMenus;
          this.navPosition();
        }
      }
    });
  }

  /**
   * @description: 菜单展开处理
   * @author ChenRui
   * @date 2020/7/29 17:18
   */
  onOpenChange(openKeys: string[]) {
    const latestOpenKey = openKeys.find((key) => this.openKeys.indexOf(key as never) === -1);
    if (this.menus.findIndex((item) => item.key === latestOpenKey) === -1) {
      this.openKeys = openKeys as any;
    } else {
      this.openKeys = latestOpenKey ? ([latestOpenKey] as any) : [];
    }
  }

  /**
   * @description: 动态切换导航及面包屑激活状态
   * @author ChenRui
   * @date 2020/7/29 17:07
   */
  navPosition(): void {
    const route = this.$route;
    const nodes = routeTopologyService.fetchNodes(route.path);
    if (nodes && nodes.length > 0) {
      for (const node of nodes) {
        const menus = this.recursionSerarchCurrentMenuTreeByUrl(this.menus, node.path);
        if (menus) {
          this.selectedKeys = [];
          this.openKeys = [];
          menus.forEach((menu: NavMenu) => {
            if (menu.url !== node.path) {
              this.openKeys.push(menu.key!);
            } else {
              this.selectedKeys.push(menu.key!);
            }
          });
          break;
        }
      }
    }
  }

  /**
   * @description: 菜单点击处理，切换导航
   * @author ChenRui
   * @date 2021/8/9 15:08
   */
  handleMenuClick(menu: any) {
    if (menu) {
      // const menu: NavMenu | undefined = this.recursionSerarchMenuByKey(this.menus, e.key);
      if (menu && !!menu.url && menu.url !== this.$route.path) {
        if (menu.connectType === ConnectType.EXTERNAL.code) {
          window.open(menu.url);
        } else {
          this.$router.push(menu.url);
        }
      }
    }
  }

  /**
   * @description: 递归查找菜单信息
   * @author ChenRui
   * @date 2021/8/9 15:09
   */
  recursionSerarchMenuByKey(menus: NavMenu[], key: string): NavMenu | undefined {
    for (const i in menus) {
      if (menus[i].key === key) {
        return menus[i];
      } else if (!!menus[i].children && (menus[i].children || []).length > 0) {
        const mu: NavMenu = this.recursionSerarchMenuByKey(menus[i].children || [], key) as NavMenu;
        if (mu) {
          return mu;
        }
      }
    }
  }

  /**
   * @description: 根据url获取菜单导航树
   * @author ChenRui
   * @date 2020/7/29 17:16
   */
  recursionSerarchCurrentMenuTreeByUrl(menus: NavMenu[], url: string): NavMenu[] | undefined {
    for (const i in menus) {
      if (menus[i].url === url) {
        return [beanUtilsService.copy(menus[i])];
      } else if (menus[i].children) {
        const mus: NavMenu[] = this.recursionSerarchCurrentMenuTreeByUrl(menus[i].children || [], url) as NavMenu[];
        if (mus) {
          const menuCp = [beanUtilsService.copy(menus[i])];
          return [...menuCp, ...mus];
        }
      }
    }
  }
  getIconByName(name: string) {
    console.log(name);
    // 图标转换
    let data: any = {
      "icon-shouye14x14": "dhcc-icon-home",
      "icon-kehuguanli14x14": "dhcc-icon-customer",
      "icon-jintiaoguanli14x14": "dhcc-icon-responsible",
      "icon-wuliaoguanli14x14": "dhcc-icon-material",
      "icon-hetongguanli14x14": "dhcc-icon-contract",
      "icon-chanpinmoxing14x14": "dhcc-icon-model",
    };
    return data[name] ? `${data[name]}` : name;
  }
}
</script>

<style lang="scss" scoped>
.dc-left-menu-container {
  height: 100%;
  // background-color: rgba(42.16, 50.1, 62, 1);
  background-color: #fff;
  .dc-left-menu-box {
    height: calc(100% - 43px);
    scrollbar-width: none; /* firefox */
    -ms-overflow-style: none; /* IE 10+ */
    overflow-y: auto;
    padding-top: 2px;
    .dhcc-icon {
      margin-left: 5px;
      margin-right: 5px;
    }
    ::v-deep {
      .t-icon {
        width: 14px;
        height: 14px;
      }
      .t-menu__content {
        margin-left: 0;
      }
    }
    .dc-left-menu {
      padding: 16px 8px;
    }
    &::-webkit-scrollbar {
      display: none; /* Chrome Safari */
    }
    .dc-left-menu {
      // background-color: rgba(42.16, 50.1, 62, 1);
      background-color: #fff;
      .dc-text {
        // color: rgba(0, 0, 0, 0.9);
      }

      &.ant-menu-inline-collapsed {
        width: initial;
        ::v-deep {
          .ant-menu-submenu-title {
            padding-left: 22px !important;
          }
          & > {
            .ant-menu-item {
              padding-left: 22px !important;
            }
          }
          & > {
            .ant-menu-item,
            .ant-menu-submenu .ant-menu-submenu-title {
              &::after {
                display: none;
              }
            }
          }
        }
      }
      & > {
        .ant-menu-item-selected {
          background-color: #e0ebff !important;
          color: #0052d9;
          font-weight: 400;
          position: relative !important;
          border-radius: 5px;
          .dc-iconfont {
            color: rgb(0 82 217) !important;
          }
          &::before {
            display: initial !important;
            content: "";
            transform: scaleY(1);
            opacity: 1;
            transition: transform 0.15s cubic-bezier(0.645, 0.045, 0.355, 1), opacity 0.15s cubic-bezier(0.645, 0.045, 0.355, 1);
            position: absolute;
            top: 0;
            left: 0;
            bottom: 0;
          }
        }
      }
      ::v-deep {
        & > {
          .ant-menu-item {
            display: flex;
            align-items: center;
          }
          .ant-menu-item,
          .ant-menu-submenu .ant-menu-submenu-title {
            height: 38px;
            line-height: 38px;
            position: relative;
            margin-top: 5px;
            margin-bottom: 5px;
          }
        }
        .ant-menu-submenu,
        .ant-menu-item {
          color: #333333;
          .dc-iconfont {
            color: rgba(0, 0, 0, 0.9);
            opacity: 0.8;
          }
        }
        .ant-menu-submenu {
          .ant-menu-item {
            font-size: 12px;
            border-radius: 5px;
            &.ant-menu-item-selected {
              background-color: #e0ebff !important;
              .dc-rectangle {
                background-color: #a3b9e0;
              }
              .dc-iconfont {
                color: rgba(0, 0, 0, 0.9);
              }
              .dc-text {
                color: #0052d9;
              }
            }
          }
        }
        .ant-menu-submenu-selected {
          .ant-menu-submenu-title {
            color: #245fac;
            font-weight: 700;
            position: relative;
            &::before {
              content: "";
              transform: scaleY(1);
              opacity: 1;
              transition: transform 0.15s cubic-bezier(0.645, 0.045, 0.355, 1), opacity 0.15s cubic-bezier(0.645, 0.045, 0.355, 1);
              position: absolute;
              top: 0;
              left: 0;
              bottom: 0;
            }
            .dc-iconfont {
              color: rgba(0, 0, 0, 0.9) !important;
            }
          }
        }
        .ant-menu-item-selected {
          color: #0052d9;
          background-color: #006eff;
          &::after {
            display: none;
          }
        }
      }
    }
  }
  .dc-menu-fold {
    margin-top: auto;
    height: 40px;
    display: flex;
    align-items: center;
    border-top: 1px solid #d8dce6;
    .dc-menu-fold-btn {
      display: flex;
      flex-direction: row;
      align-items: center;
      color: rgba(0, 0, 0, 0.6);
      border: 0;
      ::v-deep {
        .anticon {
          display: block;
          margin-bottom: -2px;
          font-size: 16px;
        }
      }
      .dc-menu-fold-btn-text {
        font-size: 12px;
        margin-left: 10px;
        display: inline-block;
      }
      &:hover {
        background: none;
      }
    }
  }
  .dc-iconfont {
    font-size: 20px;
    margin: 0 5px 0 0;
  }
  ::v-deep {
    @for $i from 15 through 20 {
      .dc-iconfont-#{$i} {
        font-size: $i + px !important;
      }
    }
  }
}
</style>
