<!-- 机组诊断的侧边导航 -->
<template>
  <div class="sidebar" v-loading="loading" :element-loading-background="loadingColor">
    <el-scrollbar class="scrollbar">
      <div class="menu-block">
        <!-- 搜索 -->
        <div class="menu-search global">
          <el-input class="input-style" v-model="searchValue" placeholder="快速搜索" @keyup.enter.native="search"></el-input>
          <el-button class="btn-style" @click="search">搜索</el-button>
          <el-button class="btn-style" @click="cleanUp">清空</el-button>
        </div>
        <!-- 菜单 -->
        <el-menu ref="menu" text-color="#fff" unique-opened1 @open="openMenu" @close="closeMenu">
          <el-submenu v-for="(factory, index) of menu" :key="index" :index="index+''">
            <template slot="title">
              <span>{{ factory.plantName }}</span>
            </template>
            <div class="sub-menu" v-for="(crew, index2) of factory.plantDevices" :key="index2">
              <div v-if="index2 == factory.plantDevices.length - 1" class="line-y-item"></div>
              <div class="line-x-item"></div>
              <el-submenu :index="index + '_' + index2">
                <template slot="title">
                  <span>{{ crew.deviceName }}</span>
                </template>
                <div class="sub-menu" v-for="(character, index3) of crew.characters" :key="index3">
                  <div v-if="index3 == crew.characters.length - 1" class="line-y-item"></div>
                  <div class="line-x-item"></div>
                  <el-checkbox-group class="check-list" v-model="checkList" :max="pointListMax">
                    <el-checkbox class="check-style" :label="index + '_' + index2 + '_' + index3" @change="changeMenu">
                      {{ character.cpName }} </el-checkbox>
                  </el-checkbox-group>
                </div>
              </el-submenu>
            </div>
          </el-submenu>
        </el-menu>
      </div>
    </el-scrollbar>
  </div>
</template>

<script>
  import API from '@/api/factory.js';
  import {
    ChartStyle
  } from '@/common/const.js';

  export default {
    data() {
      return {
        loading: false,
        loadingColor: ChartStyle.loadingColor,
        searchValue: '', // 搜索值
        menuAll: null, // 所有菜单列表
        menu: null, // 当前菜单列表
        pointListMax: 4, // 报警最多选择数量
        checkList: [], // 选择列表
        lastMenuKey: '', // 存储菜单最后一次的key，用于打开其他菜单时，主动调用关闭前一个菜单（清空测点，优化性能）
      };
    },
    computed: {
      // 根据当前菜单和选择列表,返回选择列表中每个项的测点信息
      checkNodeList() {
          if (!this.checkList.length) return [];
          let list = this.checkList.map(i => {
              let arr = i.split('_');
              let obj = {
                  factory: this.menu[arr[0]],
                  crew: this.menu[arr[0]].plantDevices[arr[1]],
                  character: this.menu[arr[0]].plantDevices[arr[1]].characters[arr[2]],
                  index: i
              };
              return obj;
          });
          return list;
      },
    },
    created() {
      this.initMenu();
    },
    methods: {
      // 初始化菜单
      initMenu() {
        this.menu = this.menuAll = this.$x_factoryList;
        this.initDefaultActive();
      },
      // 展开菜单，如果没有选择机组，则展开第一个机组的第一个部件的第一个测点，否则展开选择机组的第一个部件的第一个测点，如果有默认按钮，则找到默认按钮对应的测点展开
      async initDefaultActive() {
        this.$nextTick(async () => {
          let pointList = this.$route.query.pointList;
          try{
            pointList = JSON.parse(pointList);
          }catch(e){
            pointList = null;
          }
          if (pointList) {
            // 选择了测点
            let indexFactory = this.menu.findIndex(i => i.plantId == this.$x_factory.plantId); // 电厂索引，当前电厂
            let itemFactory = this.menu[indexFactory];
            let checkList = [];
            // 构造机组测点树结构
            let tmpTree = {};
            pointList.forEach(i => {
              let indexCrew = itemFactory.plantDevices.findIndex(j => j.deviceId == i.deviceId); // 机组索引
              if (!tmpTree[indexCrew]) tmpTree[indexCrew] = [i.kksCode];
              else tmpTree[indexCrew].push(i.kksCode);
            })
            // 遍历获取测点
            let tmpCount = 0; // 记录遍历次数
            let tmpLen = Object.keys(tmpTree).length;
            for (let indexCrew in tmpTree) {
              try{
                await this.openMenu(indexFactory + '_' + indexCrew); // 获取测点
                let itemCrew = itemFactory.plantDevices[indexCrew];
                tmpTree[indexCrew].forEach(i => {
                  let indexCharacter = itemCrew.characters.findIndex(j => j.kksCode == i); // 测点索引
                  checkList.push(indexFactory + '_' + indexCrew + '_' + indexCharacter); // 放入选择列表
                })
                // 如果都放进去了,模拟点击菜单
                if(++tmpCount == tmpLen) {
                  this.checkList = checkList;
                  this.changeMenu();
                  this.$refs.menu.open(indexFactory + '_' + indexCrew); // 展开机组菜单
                }
              }catch(e){
                console.log(e);
              }
            }
          } else {
            // 没有选择默认测点
            let indexFactory = 0; // 电厂索引，默认第一个
            let indexCrew = 0; // 机组索引，默认第一个
            let indexCharacter = 0; // 测点索引，默认第一个
            try{
              await this.openMenu(indexFactory + '_' + indexCrew); // 获取测点
              this.checkList = [indexFactory + '_' + indexCrew + '_' + indexCharacter]; // 模拟点击测点
              this.changeMenu();
              this.$refs.menu.open(indexFactory + '_' + indexCrew); // 展开机组菜单
            }catch(e){
              console.log(e);
              this.$refs.menu.open(indexFactory); // 展开电厂菜单
            }
          }
        });
      },
      // 展开菜单，获取机组测点
      async openMenu(key) {
        let arr = key.split('_');
        if (arr.length != 2) return; // 只有等于2（即机组菜单）时才需要后续的获取测点
        // 由于设置了只同一时间只存在一个菜单的展开，所以清空上一次菜单的测点
        this.closeMenu(this.lastMenuKey);
        this.lastMenuKey = key;
        // 查询测点
        let crew = this.menu[arr[0]].plantDevices[arr[1]];
        if (!crew.characters?.length) {
          this.loading = true;
          try {
            let res = await API.getCharacterList(crew.deviceId); // 获取测点信息
            crew.characters = res;
          } catch (e) {
            console.log(e);
          }
          this.loading = false;
        }
        return crew.characters;
      },
      // 关闭展开的菜单时，如果选择列表里有当前菜单的测点,则不清空测点,没有则清空
      closeMenu(key) {
        // let arr = key.split('_');
        // if (arr.length != 2) return;
        // if (this.checkList.find(i => i.indexOf(arr[0] + '_' + arr[1]) == 0)) return; // 这里只判断机组部件的索引是否包含，不去判断二级菜单
        // this.menu[arr[0]].plantDevices[arr[1]].characters = []; // 清空测点
      },
      // 切换菜单
      changeMenu() {
        this.$emit('changeMenu', this.checkNodeList);
      },
      // 搜索测点名
      search() {
        this.checkList = [];
        this.lastMenuKey = '';
        let copyMenu = JSON.parse(JSON.stringify(this.menuAll));
        this.menu = copyMenu.filter(i => {
          let newDev = i.plantDevices.filter(j => {
            let newCha = j.characters ? j.characters.filter(k => k.cpName.indexOf(this.searchValue) != -1) : [];
            j.characters = newCha;
            return newCha.length;
          })
          i.plantDevices = newDev;
          return newDev.length;
        });
      },
      // 清空搜索
      cleanUp() {
        this.checkList = [];
        this.lastMenuKey = '';
        this.searchValue = '';
        this.menu = this.menuAll;
      }
    }
  };
</script>

<style lang="scss" scoped>
  .sidebar {

    // el滚动条
    .scrollbar {
      height: 100%;
    }

    /deep/.el-scrollbar__wrap {
      overflow-x: hidden;
    }

    .menu-block {
      margin: 1.25rem;
    }

    // 搜索样式
    .menu-search {
      display: flex;
      margin-bottom: 0.625rem;
      height: 2.5rem;

      .input-style {
        margin-right: 0.625rem;
      }

      /deep/.el-input__inner {
        border-radius: 50px;
        height: 100%;
      }

      .btn-style {
        @extend %btn-default;
        font-size: 0.875rem;
        flex-shrink: 0;
      }
    }

    $item-height: 2.5rem;
    $line-color: rgba($color: #fff, $alpha: 0.3);

    // 菜单样式
    /deep/ .el-menu {
      border: none;
      position: relative;
      background-color: transparent;

      // 横向线条
      .line-x-item {
        width: calc(6% + 1px);
        height: 2px;
        background-color: $line-color;
        position: absolute;
        top: 2.125rem;
        left: 0;
      }

      // 纵向线条
      .line-y-item {
        width: 2px;
        height: 2.1875rem;
        background-color: $line-color;
        position: absolute;
        top: 0%;
        left: 0%;
      }

      .sub-menu {
        position: relative;
        width: 92%;
        padding-left: 6%;
        box-sizing: border-box;
        border-left: 2px solid $line-color;
      }

      .sub-menu:last-child {
        width: 92%;
        padding-left: 6%;
        box-sizing: border-box;
        border-left: none;
      }

      .check-list {
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: flex-end;

        .check-style {
          width: 100%;
          height: $item-height;
          margin-top: 1rem;
          padding: 0 1.25rem;
          box-sizing: border-box;
          background-color: rgba($color: $color-cyan, $alpha: 0.1);
          border-radius: 50px;
          display: flex;
          align-items: center;

          /deep/ .el-checkbox__label {
            font-size: 1rem !important;
            color: #fff;
          }
        }
      }

      // 组菜单标题和单项标题
      /deep/.el-submenu__title,
      /deep/.el-menu-item {
        height: 2.5rem;
        background-color: rgba($color: $color-cyan, $alpha: 0.1);
        display: flex;
        align-items: center;
        border-radius: 50px;
        font-size: 1rem;
        padding: 0 1.25rem !important;
        overflow: hidden;
      }

      // 组菜单标题和单项标题滑过
      /deep/.el-submenu__title:hover,
      /deep/.el-menu-item:hover {
        background-color: $color-deep-blue;
      }

      // 组菜单标题
      /deep/.el-submenu__title {
        margin-top: 1rem;
      }

      // 去掉图标
      /deep/.el-icon-arrow-down:before {
        content: '';
      }

      $disable-color: #888888;

      /deep/.el-checkbox__input.is-disabled+span.el-checkbox__label {
        color: $disable-color;
      }

      /deep/.el-checkbox__input.is-disabled .el-checkbox__inner {
        background-color: $disable-color;
        border: none;
      }

      /deep/ul {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
      }
    }
  }
</style>
