<template>
  <div
    class="menu-side left_col scroll-view"
    :style="{ width: width + 'px', backgroundColor: leftColor }"
  >
    <div class="navbar nav_title" style="border: 0">
      <a href="#/desktop/dashboard" class="site_title"><img
        :style="{ width: logoWidth + 'px'}"
        :src="logoUrl"
      /></a>
    </div>

    <div class="clearfix" />

    <div id="sidebar-menu" class="main_menu_side hidden-print main_menu">
      <div class="menu_section">
        <div class="menu-div">
          <input
            v-model="searchText"
            autocomplete="off"
            type="text"
            class="form-control menu-search"
            :placeholder="$t('lang.menuWidget.searchMenu')"
            :style="{ backgroundColor: searchColor }"
          />
        </div>

        <ul class="nav menu-nav side-menu">
          <template v-for="rootNode in rootNodes">
            <li
              v-if="rootNode.show"
              :key="rootNode.uuid"
              :name="rootNode.no"
              :model="rootNode"
              :class="{ active: selectedNode === rootNode }"
            >
              <a @click="selectMenuNode(rootNode)">
                <i :class="rootNode.icon" />
                {{ Language.getMenuNameTrl($i18n.locale, rootNode) }}
                <span class="fa fa-chevron-down" />
              </a>
              <ul
                class="nav menu-nav child_menu"
                :class="{ active: rootNode.expand == true }"
              >
                <template
                  v-for="subMenuItem in rootNode.subMenus"
                  :key="subMenuItem.uuid"
                >
                  <MenuNode
                    :menu-color="menuColor"
                    :select-color="selectColor"
                    :model="subMenuItem"
                    @select-node="selectNode($event, rootNode.subMenus)"
                  />
                </template>
              </ul>
            </li>
          </template>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import Common from '../common/Common.js';

import Language from '../common/Language.js';
import MenuNode from './MenuNode.vue';
import { Uuid } from 'pc-component-v3';

export default {
  components: {
    MenuNode,
  },
  props: {
    width: {
      default: 230,
      type: Number,
    },
    logoWidth: {
      default: 152,
      type: Number,
    },
    leftColor: {
      default: '#2a3f54',
      type: String,
    },
    menuColor: {
      default: 'linear-gradient(#334556, #2c4257), #2a3f54',
      type: String,
    },
    searchColor: {
      default: '#1c3e4b',
      type: String,
    },
    selectColor: {
      default: '#495d70',
      type: String,
    },
  },
  data: function () {
    this.Language = Language;
    return {
      rootNodes: [],
      selectedNode: {}, // 选择的节点
      searchText: '',
      logoUrl: '', // logo路径
    };
  },

  watch: {
    searchText: function (newVal, oldVal) {
      this.search(newVal);
    },
  },

  mounted: function () {
    var _self = this;
    this.loadMenuData();
    this.getLogoName();
  },

  methods: {
    /// 加载数据
    loadMenuData: function () {
      console.log('loadMenuData');
      var _self = this;
      $.ajax({
        url: Common.getApiURL('MenuResourceV2/listCanVist'),
        type: 'POST',
        dataType: 'json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          $.ajax({
            url: Common.getApiURL('UserMenuResource/queryAddMenus'),
            type: 'get',
            dataType: 'json',
            beforeSend: function (request) {
              Common.addTokenToRequest(request);
            },
            success: function (data1) {
              if (data1 != null) {
                console.log(data1);
                _self.formateCollectionMenuData(data, data1);
              } else {
                _self.formateMenuData(data);
              }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
              Common.processException(XMLHttpRequest, textStatus, errorThrown);
            },
          });
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    // 格式化菜单数据
    formateMenuData: function (datas) {
      var _self = this;
      if (datas == null || datas.length == 0) {
        return;
      }
      // 对菜单进行排序和设置expand
      function initNode(nodes) {
        if (nodes instanceof Array) {
          nodes.forEach(function (node) {
            node.expand = false;
            node.show = true;
            node.uuid = Uuid.createUUID();
            if (node.subMenus instanceof Array) {
              initNode(node.subMenus);
            }
          });
        }
      }

      initNode(datas);
      this.rootNodes = datas;

      _self.$nextTick(function () {
        _self.initView();
      });
    },

    // 格式化菜单数据
    formateCollectionMenuData: function (datas, collections) {
      var _self = this;
      if (
        (datas == null || datas.length == 0) &&
        (collections == null || collections.length == 0)
      ) {
        return;
      }
      // 对菜单进行排序和设置expand
      function initNode(nodes, collectionDatas) {
        if (nodes instanceof Array) {
          nodes.forEach(function (node) {
            node.expand = false;
            node.show = true;
            node.uuid = Uuid.createUUID();
            collectionDatas.forEach(collectionData => {
              if (node.no == collectionData.no) {
                node.favorite = true;
              }
            });
            if (node.subMenus instanceof Array) {
              initNode(node.subMenus, collectionDatas);
            }
          });
        }
      }

      initNode(datas, collections);
      this.rootNodes = datas;
      _self.$nextTick(function () {
        _self.initView();
      });
    },

    setContentHeight: function () {
      var $RIGHT_COL = $('.right_col');
      var $BODY = $('body');
      var $LEFT_COL = $('.left_col');
      var $NAV_MENU = $('.nav_menu');

      var bodyHeight = $(window).height();
      var leftColHeight = $LEFT_COL.eq(1).height();
      var contentHeight =
        (bodyHeight < leftColHeight ? leftColHeight : bodyHeight) -
        ($NAV_MENU.height() + 2);

      $RIGHT_COL.css('min-height', contentHeight);
    },

    // 初始化界面
    initView: function () {
      var _self = this;

      // 窗口大小改变的时候，重新计算高度
      $(window).resize(function () {
        _self.setContentHeight();
      });

      _self.setContentHeight();
    },

    // 选择菜单节点
    selectMenuNode: function (rootNode) {
      if (rootNode.expand) {
        rootNode.expand = false;
      } else {
        rootNode.expand = true;
      }
    },

    selectNode: function (node, subMenus) {
      if (node.expand) {
        subMenus.forEach(function (item) {
          if (item != node) {
            //这里控制菜单是否可以同时展开
            //							item.expand = false;
          }
        });
      }
    },
    /**
     * 搜索菜单
     */
    search: function (inputText) {
      //判断一个节点及其子节点是否含有搜索的内容
      function filterNode(node) {
        var name = node.name;
        if (name.indexOf(inputText) != -1) {
          node.show = true;
        } else {
          node.show = false;
        }
        if (node.subMenus != undefined && node.subMenus instanceof Array) {
          node.subMenus.forEach(function (node2) {
            filterNode(node2);
          });
        }
      }

      /**
       * 递归修改属性为可见的节点的父节点为可见
       * @param {Object} node
       */
      function parseParent(node, level) {
        // 防止循环数据
        if (level > 5) {
          return;
        }
        if (node.subMenus != undefined && node.subMenus instanceof Array) {
          node.subMenus.forEach(function (node1) {
            parseParent(node1, level + 1);
            //递归结束时,设置可见节点的父节点为可见
            if (node1.show == true) {
              node.show = true;
              node.expand = true;
              node1.expand = true;
            }
          });
        }
      }
      var _self = this;
      _self.setNodeView();
      if (inputText) {
        //遍历所有根节点与传销内容无关的设置不可见
        this.rootNodes.forEach(function (node) {
          filterNode(node);
        });

        this.rootNodes.forEach(function (node) {
          parseParent(node, 0);
        });
      }
    },
    /**
     * 设置全部菜单可见
     */
    setNodeView: function () {
      var _self = this;
      function initNode(nodes) {
        if (nodes instanceof Array) {
          nodes.sort(function (a, b) {
            if (a.sortNo != undefined && b.sortNo != undefined) {
              return a.sortNo - b.sortNo;
            } else {
              return 0;
            }
          });
          nodes.forEach(function (node) {
            node.expand = false;
            node.show = true;
            if (node.subMenus instanceof Array) {
              initNode(node.subMenus);
            }
          });
        }
      }
      initNode(_self.rootNodes);
    },
    // 查询系统logo
    getLogoName: function () {
      const _self = this;
      $.ajax({
        type: 'GET',
        url: Common.getApiURL('clientLogoResource/selectByClientId'),
        dataType: 'json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (res) {
          if (res.errorCode === 0) {
            _self.logoUrl = `/Files/0/Images/com.leanwo.prodog.system.model.ClientLogo/${res.data.imageName}`;
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
  },
};
</script>

<style scoped>
.menu-side {
  background: var(--leftColor);
}
.menu-search {
  background: var(--searchColor);
}
.menu-div {
  padding-left: 10px;
  padding-right: 10px;
}

.call-div {
  color: white;
  padding-top: 10px;
  padding-left: 15px;
  padding-right: 10px;
  font-size: medium;
  cursor: pointer;
}
</style>

<style>
.menu-side {
  position: fixed;
  top: 0px;
  bottom: 0;
  left: 0;
  /* padding-top: 51px; */
  width: 230px;
  background-color: #293c55;
  overflow-y: auto;
  overflow-x: hidden;
}

.main_menu_side {
  padding: 0;
}
.main_menu .fa {
  width: 26px;
  opacity: 0.99;
  display: inline-block;
  font-family: FontAwesome;
  font-style: normal;
  font-weight: normal;
  font-size: 18px;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
.main_menu .navbar-nav > li > a {
  color: #fff !important;
}
.main_menu .nav.side-menu > li {
  position: relative;
  display: block;
  cursor: pointer;
}
.main_menu .nav.side-menu > li > a {
  margin-bottom: 6px;
}
.main_menu .nav.side-menu > li > a:hover {
  color: #f2f5f7 !important;
}
.main_menu .nav.side-menu > li > a,
.main_menu .nav.child_menu > li > a {
  /* color: #e7e7e7; */
  color: #fff;
  font-weight: 500;
}
.main_menu .nav.side-menu > li.current-page,
.main_menu .nav.side-menu > li.active {
  border-right: 5px solid #1abb9c;
}
.main_menu .nav.side-menu > li.active > a {
  text-shadow: rgba(0, 0, 0, 0.25) 0 -1px 0;
  background: linear-gradient(#334556, #2c4257), #2a3f54;
  box-shadow: rgba(0, 0, 0, 0.25) 0 1px 0,
    inset rgba(255, 255, 255, 0.16) 0 1px 0;
}
.main_menu .nav.child_menu {
  display: none;
}

.main_menu .nav.child_menu.active {
  display: block;
}
/*.nav.child_menu li:hover,
	.nav.child_menu li.active {
  background-color: #495d70; 
  }

	.nav.child_menu li a:hover {
  background-color: #495d70; 
	}*/
.main_menu .nav.child_menu li {
  padding-left: 36px;
}
.main_menu .nav-md ul.nav.child_menu li:before {
  background: #425668;
  bottom: auto;
  content: "";
  height: 8px;
  left: 23px;
  margin-top: 15px;
  position: absolute;
  right: auto;
  width: 8px;
  z-index: 1;
  border-radius: 50%;
}
.main_menu .nav-md ul.nav.child_menu li:after {
  border-left: 1px solid #425668;
  bottom: 0;
  content: "";
  left: 27px;
  position: absolute;
  top: 0;
}
.main_menu .nav.child_menu li li:hover,
.main_menu .nav.child_menu li li.active {
  background-color: v-bind(selectColor);
}
.main_menu .nav.child_menu li li a:hover,
.main_menu .nav.child_menu li li a.active {
  color: #fff;
}
.main_menu .nav > li > a {
  position: relative;
  display: block;
  padding: 13px 15px 12px;
}
/*.nav li.current-page {
  background: rgba(255, 255, 255, 0.05); 
	}

	.nav li li li.current-page {
  background: none; 
	}*/

.main_menu .nav li li.current-page a {
  color: #fff;
}
.main_menu .nav.navbar-nav > li > a {
  color: #515356 !important;
}
.main_menu .nav.top_menu > li > a {
  position: relative;
  display: block;
  padding: 10px 15px;
  color: #34495e !important;
}
/*	.nav > li > a:hover, .nav > li > a:focus {
  background-color: transparent; 
	}*/
.main_menu .menu-nav > li > a:focus,
.main_menu .menu-nav > li > a:hover {
  text-decoration: none;
  background-color: transparent !important;
}
.main_menu .menu-search {
  /* background-color: #1c3e4b; */
  color: #fff;
}
</style>