<template>
  <div class="cn-header">
    <div class="cn-header__banner">
      <div class="banner__left">
        <span @click="shrink" class="shrink-button" :class="{'shrink-button--collapse': showMenu}"><i
            class="cn-icon cn-icon-navigation"></i></span>
        <img alt="loading..." height="26" :src="logo" @click="jump('/panel/networkOverview', '', '', 0)" style="cursor: pointer"/>
      </div>
      <!--个人操作-->
      <div class="personal">
        <el-dropdown>
          <div class="header-menu__item"><i class="cn-icon cn-icon-language"></i></div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeLocal(EN)">
                <div id="header-to-english" class="personal-dropdown-item" :class="language === EN ? 'is-active' : ''">
                  English
                </div>
              </el-dropdown-item>
              <el-dropdown-item @click="changeLocal(ZH)">
                <div id="header-to-chinese" class="personal-dropdown-item" :class="language === ZH ? 'is-active' : ''">
                  中文
                </div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-dropdown>
          <div class='login-user header-menu__item'>{{ nickName }}&nbsp;<i class="cn-icon cn-icon-arrow-down"></i></div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="showPinDialog">
                <div id="header-to-changepin">{{ $t('overall.changePassword') }}</div>
              </el-dropdown-item>
              <el-dropdown-item @click="logout">
                <div id="header-to-logout">{{ $t('overall.logout') }}</div>
              </el-dropdown-item>
<!--              <el-dropdown-item>-->
<!--                <div id="header-to-theme" @click="switchTheme">-->
<!--                  <span>暗黑模式</span>-->
<!--                  <el-switch v-model="isDark" size="large" class="mt-2" style="margin-left: 24px" inline-prompt />-->
<!--                </div>-->
<!--              </el-dropdown-item>-->
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <div class="cn-header__nav">
      <i class="cn-icon cn-icon-a-NetworkAnalytics"></i>
      <el-breadcrumb class="header__left-breadcrumb" separator=">" v-if="route.startsWith('/panel')">
        <el-breadcrumb-item class="header__left-breadcrumb-item" :id="`breadcrumb${item.value}`" :title="index===3?item.value:''"
                            v-for="(item,index) in breadcrumb" :key="item.value">
          <template v-if="index===3" >
            <div class="header__left-breadcrumb-item-select" style="position: relative">
              <el-popover placement="bottom-start"
                          style="position: absolute"
                          ref="breadcrumbPopover"
                          :show-arrow="false"
                          :append-to-body="false"
                          :hide-after="0"
                          :show-after="0"
                          popper-class="breadcrumb__popper"
                          @show="showBreadcrumbPopover(item.value)"
                          @hide="hideBreadcrumbPopover()"
                          trigger="click">
                <template #reference>
                  <div class="breadcrumb-button" id="breadcrumbButton"
                       :class="showBackground?'breadcrumb-button__active':''">
                    <span id="breadcrumbValue">
                      <template v-if="curTabProp === 'qtype'">
                        <span>{{ dnsQtypeMapData.get(item.value)}}</span>
                      </template>
                      <template v-else-if="curTabProp === 'rcode'">
                        <span>{{ dnsRcodeMapData.get(item.value)}}</span>
                      </template>
                      <template v-else>
                        <span>{{ item.value }}</span>
                      </template>
                    </span><i class="cn-icon-xiala cn-icon"></i>
                  </div>
                </template>
                <el-row type="flex" justify="center" style="width: fit-content;flex-direction: column;">
                  <div class="search-input">
                    <el-input :placeholder="$t('filter.options')"
                              size="small"
                              v-model="dropDownValue"
                              @input="dropDownSearch"></el-input>
                  </div>
                  <ul class="select-dropdown" id="breadcrumbSelectDropdown" @scroll="scrollList()">
                    <li v-for="item in breadcrumbColumnValueListShow" title='' :key="item" :id="item"
                        class="select-dropdown__item" @click="changeValue(item)">
                      <template v-if="curTabProp === 'qtype'">
                        <span>{{ dnsQtypeMapData.get(item) }}</span>
                      </template>
                      <template v-else-if="curTabProp === 'rcode'">
                        <span>{{ dnsRcodeMapData.get(item) }}</span>
                      </template>
                      <template v-else>
                        <span>{{ item }}</span>
                      </template>
                    </li>
                  </ul>
                </el-row>
              </el-popover>
            </div>
          </template>
          <template v-else-if="index===2">
            <span v-if="route===wholeScreenRouterMapping.dns || !route.startsWith('/panel')">{{ $t(item.value) }}</span>
            <span v-else class="route-menu" @click="jump(route,item.value,'',3)">{{ $t(item.value) }}</span>
          </template>
          <!-- index=0和index=1的点击跳转由breadcrumb里的数据控制 -->
          <template v-else-if="index===1">
            <span v-if="item.clickable" class="route-menu" @click="jump(route,'','',2)">{{ item.value }}</span>
            <span v-else>{{ item.value }}</span>
          </template>
          <template v-else>
            <span v-if="item.clickable" class="route-menu" @click="jump(item.route,'','',0)">{{ item.value }}</span>
            <span v-else>{{ item.value }}</span>
          </template>
        </el-breadcrumb-item>
      </el-breadcrumb>
      <el-breadcrumb class="header__left-breadcrumb" separator=">" v-else>
        <el-breadcrumb-item class="header__left-breadcrumb-item" :id="`breadcrumb${item.value}`"
                            v-for="(item,index) in breadcrumb" :key="item.value">
          <span v-if="item.clickable" class="route-menu" @click="jumpOther(item.route,index)">{{ item.value }}</span>
          <span v-else>{{ item.value }}</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 菜单 -->
    <el-drawer
        v-model="showMenu"
        direction="ttb"
        custom-class="cn-menu"
        modal-class="cn-menu-modal"
        class="cn-menu"
        :with-header="false"
        :show-close="false"
    >
      <div class="cn-menu__left" v-if="otherMenu">
        <div class="left-menu" v-for="menu in otherMenu" :key="menu.id" @click="jumpOther(menu.route,'','',0)">
          <i :class="menu.icon"></i>
          <span>{{ $t(menu.i18n || menu.name) }}</span>
          <i class="cn-icon cn-icon-right"></i>
        </div>
      </div>
      <div class="cn-menu__middle" >
        <div class="middle-menus middle-menus--network-analytics">
          <div class="middle-menus__header">{{ $t('overall.networkAnalytics') }}</div>
          <div class="middle-menus__body" v-if="networkAnalyticsMenu && networkAnalyticsMenu.children">
            <div style="width: 260px;">
              <template v-for="(menu, index) in networkAnalyticsMenu.children" :key="index">
                <div class="middle-menu" v-if="index < 5" @click="jump(menu.route,'','',2)">
                  {{ $t(menu.i18n || menu.name) }}
                </div>
              </template>
            </div>
            <div>
              <template v-for="(menu, index) in networkAnalyticsMenu.children" :key="index">
                <div class="middle-menu" v-if="index >= 5 && index < 10" @click="jump(menu.route,'','',2)">
                  {{ $t(menu.i18n || menu.name) }}
                </div>
              </template>
            </div>
          </div>
        </div>
        <div class="middle-menus middle-menus--location-intelligence">
          <div class="middle-menus__header">{{ $t('overall.locationIntelligence') }}</div>
          <div class="middle-menus__body" v-if="locationIntelligenceMenu && locationIntelligenceMenu.children">
            <div style="width: 260px;">
              <template v-for="(menu, index) in locationIntelligenceMenu.children" :key="index">
                <div class="middle-menu" v-if="index < 5" @click="jump(menu.route,'','',2)">
                  {{ $t(menu.i18n || menu.name) }}
                </div>
              </template>
            </div>
            <div>
              <template v-for="(menu, index) in locationIntelligenceMenu.children" :key="index">
                <div class="middle-menu" v-if="index >= 5 && index < 10" @click="jump(menu.route,'','',2)">
                  {{ $t(menu.i18n || menu.name) }}
                </div>
              </template>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 改密码 -->
    <el-dialog v-model="showChangePin"
               class="change-pin-dialog"
               width="30%"
               :before-close="handleClose">
      <el-form :rules="changePassFormRules" :model="changePassForm" ref="changePassForm">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item :label="$t('overall.currentPassword')" prop="oldPwd">
              <el-input v-model="changePassForm.oldPwd" type="password"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('overall.newPassword')" prop="newPwd">
              <el-input v-model="changePassForm.newPwd" type="password"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('overall.confirmNewPassword')" prop="newPwd2">
              <el-input v-model="changePassForm.newPwd2" type="password"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showChangePin = false">{{ $t('overall.cancel') }}</el-button>
          <el-button type="primary" @click="submit">{{ $t('overall.update') }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import {
  curTabState,
  entityType,
  fromRoute,
  networkTable,
  operationType,
  storageKey,
  wholeScreenRouterMapping,
  ZH,
  EN
} from '@/utils/constants'
import { api } from '@/utils/api'
import { ref } from 'vue'
import {
  combineDrilldownTableWithUserConfig,
  combineTabList,
  getDefaultCurTab,
  getDnsMapData,
  getTabList,
  handleSpecialValue,
  overwriteUrl,
  urlParamsHandler
} from '@/utils/tools'
import { getNowTime, getSecond } from '@/utils/date-util'
import _ from 'lodash'
import { useRoute } from 'vue-router'
import { useDark, useToggle } from '@vueuse/core'

export default {
  name: 'Header',
  data () {
    const passwordComparison = (rule, value, callback) => {
      if (value !== this.changePassForm.newPwd) {
        callback(new Error(this.$t('validate.passwordConsistent')))
      } else {
        callback()
      }
    }
    const validateFiveLength = (rule, value, callback) => {
      if (value.length < 5) {
        callback(new Error(this.$t('validate.atLeastFive')))
      } else {
        callback()
      }
    }
    return {
      username: localStorage.getItem(storageKey.username),
      nickName: localStorage.getItem(storageKey.nickName),
      language: localStorage.getItem(storageKey.language) ? localStorage.getItem(storageKey.language) : EN,
      showChangePin: false,
      from: '', // entity类型
      changePassForm: {
        oldPwd: '',
        newPwd: '',
        newPwd2: ''
      },
      changePassFormRules: {
        oldPwd: [{
          required: true,
          message: this.$t('validate.required'),
          trigger: 'blur'
        }],
        newPwd: [{
          required: true,
          message: this.$t('validate.required'),
          trigger: 'blur'
        }, {
          validator: validateFiveLength,
          trigger: 'change'
        }],
        newPwd2: [{
          required: true,
          message: this.$t('validate.required'),
          trigger: 'blur'
        }, {
          validator: validateFiveLength,
          trigger: 'change'
        }, {
          validator: passwordComparison,
          trigger: 'blur'
        }]
      },
      showMenu: false,
      dropDownValue: '',
      breadcrumbColumnValueListShow: [],
      curTabProp: '',
      dnsRcodeMapData: new Map(),
      dnsQtypeMapData: new Map(),
      isDnsMapType: false,
      valueMeta: [],
      showBackground: false,
      selected: false,
      valueMenuId: '',
      fromRoute: fromRoute,
      detectionMenuList: [
        {
          name: 'securityEvents',
          i18n: 'entities.securityEvents',
          path: '/detection/securityEvent'
        },
        {
          name: 'performanceEvents',
          i18n: 'overall.performanceEvents',
          path: '/detection/performanceEvent'
        }
      ],
      curPageNum: 1,
      curTabState: curTabState,
      urlChangeParams: {},
      wholeScreenRouterMapping,
      logo: 'images/logo-header.svg',
      ZH,
      EN,
      // isDark: useDark()
    }
  },
  computed: {
    networkAnalyticsMenu () {
      return this.$store.getters.menuList.find(menu => menu.code === 'networkAnalytics')
    },
    locationIntelligenceMenu () {
      return this.$store.getters.menuList.find(menu => menu.code === 'locationIntelligence')
    },
    otherMenu () {
      return this.$store.getters.menuList.filter(menu => ['locationIntelligence', 'networkAnalytics', 'I18N', 'entityDetail', 'entityGraph', 'detectionPolicy'].indexOf(menu.code) === -1)

      /* function excludeButton (menu) {
        for (let i = 0; i < menu.length; i++) {
          if (menu[i].type === 2) {
            menu.splice(i, 1)
            i--
          } else {
            if (menu[i].children && menu[i].children.length > 0) {
              excludeButton(menu[i].children)
            }
          }
        }
      } */
    },
    breadcrumb () {
      const breadcrumb = []
      this.generateBreadcrumb(breadcrumb, this.$store.getters.menuList, this.$store.state.headerMenuByTab)
      if (breadcrumb) {
        // panel菜单是否可以点击跳转：一级菜单不可点击，二级菜单可以点击
        if (breadcrumb[0] && breadcrumb[1] && breadcrumb[1].route &&
                              breadcrumb[1].route.indexOf('/panel/') === 0) {
          breadcrumb[1].clickable = true
        } else { // 除panel外的菜单是否可以点击跳转:除了新增、编辑，其它均可点击
          breadcrumb.forEach(item => {
            if (item.value !== 'Create' && item.value !== 'Edit') {
              item.clickable = true
            }
          })
        }
      }

      const thirdMenu = this.getUrlParam(this.curTabState.thirdMenu, '')
      const fourthMenu = this.getUrlParam(this.curTabState.fourthMenu, '')

      let result = [...breadcrumb]
      if (fourthMenu) {
        result = [...result, { value: thirdMenu }, { value: fourthMenu }]
      } else if (thirdMenu) {
        result = [...result, { value: thirdMenu }]
      }
      return result
    },
    showEntityTypeSelector () {
      return this.$store.getters.getShowEntityTypeSelector
    },
    storeFrom () {
      return this.$store.getters.from
    },
    route () {
      return this.$route.path
    }
  },
  watch: {
    from (n) {
      this.$store.commit('entityTypeChange', n)
    },
    storeFrom (n) {
      if (this.from !== n) {
        this.from = n
      }
    },
    async breadcrumb (n) {
      this.breadcrumbColumnValueListShow = []
      this.curTabProp = this.$route.query.dimensionType ? this.$route.query.dimensionType : null
      if (this.$route.path.replace('/panel/', '') === fromRoute.dnsServiceInsights) {
        if (this.dnsQtypeMapData.size === 0) {
          this.dnsQtypeMapData = await getDnsMapData('dnsQtype')
        }
        if (this.dnsRcodeMapData.size === 0) {
          this.dnsRcodeMapData = await getDnsMapData('dnsRcode')
        }
      }
    },
    '$store.getters.timeFilter': function (newVal) {
      if (newVal && Object.keys(newVal).length > 0) {
        this.chartTimeFilter = newVal
      }
    },
    '$store.state.headerMenuByTab': function (newVal) {
      if (newVal) {
        const find = this.$store.getters.menuList.find(d => d.code === 'locationIntelligence')
        if (find) {
          const children = find.children
          const item = children.find(d => d.code === newVal)
          if (this.breadcrumb[0].code === find.code) {
            const obj = {
              code: item.code,
              value: item.i18n ? this.$t(item.i18n) : item.name,
              route: item.route,
              type: 1,
              clickable: true
            }
            this.breadcrumb[1] = obj
          }
        }
        this.chartTimeFilter = newVal
      }
    }
  },
  async mounted () {
    this.from = Object.keys(this.entityType)[0]
    // 是否需要dns的qtype和rcode的数据字典
    if (this.$route.path.replace('/panel/', '') === fromRoute.dnsServiceInsights) {
      if (this.dnsQtypeMapData.size === 0) {
        this.dnsQtypeMapData = await getDnsMapData('dnsQtype')
      }
      if (this.dnsRcodeMapData.size === 0) {
        this.dnsRcodeMapData = await getDnsMapData('dnsRcode')
      }
    }
    const path = this.$route.path
    if (path.indexOf('panel') > -1 && path.indexOf('linkMonitor') === -1) {
      await this.initDropdownList()
    }
  },
  setup () {
    const { query } = useRoute()
    // 获取url携带的range、startTime、endTime
    const rangeParam = query.range
    const startTimeParam = query.startTime
    const endTimeParam = query.endTime
    // 若url携带了，使用携带的值，否则使用默认值。

    const dateRangeValue = rangeParam ? parseInt(rangeParam) : 60
    const chartTimeFilter = ref({ dateRangeValue })
    if (!startTimeParam || !endTimeParam) {
      const { startTime, endTime } = getNowTime(dateRangeValue)
      chartTimeFilter.value.startTime = startTime
      chartTimeFilter.value.endTime = endTime
    } else {
      chartTimeFilter.value.startTime = parseInt(startTimeParam)
      chartTimeFilter.value.endTime = parseInt(endTimeParam)
    }

    return {
      chartTimeFilter,
      entityType // 所有entity类型，用于header下拉框选择
    }
  },
  methods: {
    generateBreadcrumb (breadcrumb, menus, tab) {
      const menu = menus.find(m => m.route === this.route)
      if (menu) {
        breadcrumb.unshift({
          code: menu.code,
          value: menu.i18n ? this.$t(menu.i18n) : menu.name,
          route: menu.route,
          type: menu.type
        })
        return true
      } else {
        for (let i = 0; i < menus.length; i++) {
          if (!_.isEmpty(menus[i].children)) {
            if (this.generateBreadcrumb(breadcrumb, menus[i].children)) {
              breadcrumb.unshift({
                code: menus[i].code,
                value: menus[i].i18n ? this.$t(menus[i].i18n) : menus[i].name,
                route: menus[i].route,
                type: menus[i].type
              })
              return true
            }
          }
        }
      }
    },
    handleClose () {
      this.showChangePin = false
    },
    changeLocal (lang) {
      if (lang !== localStorage.getItem(storageKey.language)) {
        localStorage.setItem(storageKey.language, lang)
        window.location.reload()
      }
    },
    showPinDialog () {
      this.showChangePin = true
    },
    logout () {
      sessionStorage.removeItem(storageKey.tokenExpireCurrentPath)
      localStorage.removeItem(storageKey.token)
      axios.get(api.logout)
    },
    switchTheme () {
      useToggle(this.isDark)
      const theme = this.isDark ? 'light' : 'dark'
      localStorage.setItem(storageKey.theme, theme)
    },
    refreshLang () {
      this.language = localStorage.getItem(storageKey.language)
      this.$i18n.locale = this.language
      this.$nextTick(() => {
        window.location.reload()
      })
    },
    getCurTabByLabel (label) {
      let curTab = null
      const tableType = this.$route.path.replace('/panel/', '') || 'networkOverview'
      const curTableInCode = networkTable[tableType] ? networkTable[tableType] : networkTable.networkOverview
      if (curTableInCode && curTableInCode.tabList) {
        curTab = curTableInCode.tabList.find(item => item.label === label)
      }
      return curTab
    },
    async initDropdownList () {
      // 是否需要dns的qtype和rcode的数据字典
      this.curTabProp = this.$route.query.dimensionType ? this.$route.query.dimensionType : null
      const currentValue = document.getElementById('breadcrumbValue') ? document.getElementById('breadcrumbValue').innerText : ''
      const columnName = this.getUrlParam(this.curTabState.thirdMenu, '')
      let type = 'ip'
      const tableType = this.$route.path.replace('/panel/', '') || 'networkOverview'
      const curTableInCode = networkTable[tableType] ? networkTable[tableType] : networkTable.networkOverview
      if (curTableInCode && curTableInCode.tabList) {
        const curTab = curTableInCode.tabList.find(item => item.label === columnName)
        if (curTab) {
          type = curTab.prop
        } else {
          type = curTableInCode.tabList[0].prop
        }
      }
      const params = {
        startTime: getSecond(this.chartTimeFilter.startTime),
        endTime: getSecond(this.chartTimeFilter.endTime),
        limit: 10 * this.curPageNum++,
        type: type,
        name: this.dropDownValue ? this.dropDownValue : ''
      }
      // 有的界面刷新时没有drilldownList接口地址，会报404
      if (!curTableInCode.url.drilldownList) {
        return true
      }
      axios.get(curTableInCode.url.drilldownList, { params }).then(async response => {
        if (response.status === 200) {
          this.breadcrumbColumnValueListShow = response.data.data.result
          if (this.$route.path.replace('/panel/', '') === fromRoute.dnsServiceInsights) {
            if (this.dnsQtypeMapData.size === 0) {
              this.dnsQtypeMapData = await getDnsMapData('dnsQtype')
            }
            if (this.dnsRcodeMapData.size === 0) {
              this.dnsRcodeMapData = await getDnsMapData('dnsRcode')
            }
          }
          this.$nextTick(() => {
            this.breadcrumbColumnValueListShow.forEach(item => {
              const selectedDom = document.getElementById(item)
              if (selectedDom) {
                let itemName = item
                if (this.curTabProp === 'qtype') {
                  itemName = this.dnsQtypeMapData.get(item)
                } else if (this.curTabProp === 'rcode') {
                  itemName = this.dnsRcodeMapData.get(item)
                }
                if (itemName === currentValue) {
                  selectedDom.classList.add('is-active')
                } else {
                  selectedDom.classList.remove('is-active')
                }
              }
            })
          })
        }
      })
    },
    showBreadcrumbPopover (valueMenuId) {
      this.curPageNum = 1
      this.showBackground = true
      this.dropDownValue = ''
      this.initDropdownList()
      this.valueMenuId = 'breadcrumb' + valueMenuId
    },
    hideBreadcrumbPopover () {
      this.showBackground = false
    },
    getUrlParam (param, defaultValue, isNumber) {
      if (isNumber) {
        return this.$route.query[param] ? Number(this.$route.query[param]) : defaultValue
      } else {
        return this.$route.query[param] ? this.$route.query[param] : defaultValue
      }
    },
    changeValue (value) {
      this.breadcrumbColumnValueListShow = []
      // 设置面包屑显示的内容及hover时的title
      let valName = value
      if (this.curTabProp === 'qtype') {
        valName = this.dnsQtypeMapData.get(value)
      } else if (this.curTabProp === 'rcode') {
        valName = this.dnsRcodeMapData.get(value)
      }
      this.curTabProp = this.$route.query.dimensionType ? this.$route.query.dimensionType : null
      document.getElementById('breadcrumbValue').innerText = valName
      document.getElementById(this.valueMenuId).setAttribute('title', valName)
      document.getElementById('breadcrumbButton').click()
      const columnName = this.getUrlParam(this.curTabState.thirdMenu, '')
      const curTab = this.getCurTabByLabel(columnName)
      if (curTab) {
        const queryCondition = []
        const searchProps = curTab.dillDownProp
        if (curTab.prop === 'protocolPort') {
          const valueGroup = value.split(':')
          if (valueGroup) {
            queryCondition.push('l7_protocol=\'' + valueGroup[0] + '\'')
            queryCondition.push('server_port=' + valueGroup[1])
          }
          // console.log(queryCondition.join(' AND '))
          this.urlChangeParams[this.curTabState.queryCondition] = queryCondition.join(' AND ')
          this.urlChangeParams[this.curTabState.lineQueryCondition] = queryCondition.join(' AND ')
        } else {
          if (curTab.queryCondition) {
            curTab.queryCondition.forEach(item => {
              queryCondition.push(item.replaceAll('$param', value))
            })
          } else if (searchProps) {
            searchProps.forEach(item => {
              queryCondition.push(item + '=\'' + handleSpecialValue(value) + '\'')
            })
          }

          this.urlChangeParams[this.curTabState.queryCondition] = queryCondition.join(' OR ')
          const lineQueryCondition = []
          if (curTab.lineQueryCondition) {
            curTab.lineQueryCondition.forEach(item => {
              lineQueryCondition.push(item.replaceAll('$param', handleSpecialValue(value)))
            })
            this.urlChangeParams[this.curTabState.lineQueryCondition] = lineQueryCondition.join(' OR ')
          }
        }
      }
      this.changeUrlTabState()
      this.jump(this.route, columnName, value, operationType.fourthMenu)
    },
    shrink () {
      this.showMenu = !this.showMenu
    },
    submit () {
      this.$refs.changePassForm.validate((valid) => {
        if (valid) {
          axios.put(api.pin, {
            oldPin: this.changePassForm.oldPwd,
            newPin: this.changePassForm.newPwd
          }).then(res => {
            if (res.status === 200) {
              this.$message.success(this.$t('tip.success'))
              this.showChangePin = false
            } else if (res.data.code === 518005) {
              this.$message.error(this.$t('tip.incorrectPassword'))
            } else {
              this.$message.error(res.data.message)
            }
          }).catch(e => {
            console.error(e)
            if (e.response.data && e.response.data.message) {
              this.$message.error(e.response.data.message)
            } else {
              this.$message.error(this.$t('tip.somethingWentWrong'))
            }
          })
        } else {
          return false
        }
      })
    },
    changeUrlTabState () {
      if (this.urlChangeParams && JSON.stringify(this.urlChangeParams) !== '{}') {
        const { query } = this.$route
        const newUrl = urlParamsHandler(window.location.href, query, this.urlChangeParams)
        overwriteUrl(newUrl)
      }
      this.urlChangeParams = {}
    },
    async handleCurDrilldownTableConfig (thirdMenu) {
      // const userId = localStorage.getItem(storageKey.userId)
      const tableType = this.$route.path.replace('/panel/', '') || 'networkOverview'
      const metric = this.getUrlParam(this.curTabState.tableMetric, 'Bits/s')
      const drillDownTableConfigs = await combineDrilldownTableWithUserConfig()
      const currentTableConfig = drillDownTableConfigs.find(config => config.route === tableType)
      const tables = currentTableConfig ? currentTableConfig.tables : []
      const commonTabList = currentTableConfig ? currentTableConfig.tabs : []
      if (tables && tables.length > 0) {
        const curTable = tables.find(table => table.id === tableType)
        if (curTable) {
          const tabList = getTabList(curTable, metric)// 未下钻的tab列表
          if (tabList && tabList.length > 0) {
            combineTabList(tableType, tabList, commonTabList)
            tabList.forEach(item => {
              if (item.label === thirdMenu) {
                item.checked = true
              }
            })
          }
        }
      }
    },
    // 仅处理除panel外的相关路径的导航
    async jumpOther (route, index) {
      route = route.replace('redirect:', '')
      this.showMenu = false
      if (route === this.route && index > 0) { // 当前只有一级菜单时，点击不进行刷新，重新跳转
        this.refresh()
        return
      }
      if (route) {
        this.$router.push({
          path: route,
          query: {
            t: +new Date()
          }
        })
      }
    },
    // 仅处理panel相关路径的导航
    async jump (route, columnName, columnValue, opeType) {
      route = route.replace('redirect:', '')
      if (route === '/panel/linkMonitor' && opeType === 3) {
        return true
      }
      this.showMenu = false
      const menus = this.breadcrumb
      if (opeType) {
        this.urlChangeParams[this.curTabState.tabOperationBeforeType] = this.getUrlParam(this.curTabState.tabOperationType, '', true)
        this.urlChangeParams[this.curTabState.tabOperationType] = opeType
        if (opeType === 3) {
          this.urlChangeParams.queryCondition = ''
          this.urlChangeParams.lineQueryCondition = ''
        }
      } else {
        this.urlChangeParams[this.curTabState.tabOperationType] = operationType.mainMenu
      }
      if (!columnName) { // 点击第二级菜单
        this.$store.commit('setNetworkOverviewTabList', [])
      }
      // 清空网络概况的特殊面包屑
      const tableType = this.$route.path.replace('/panel/', '') || 'networkOverview'
      const metric = this.getUrlParam(this.curTabState.tableMetric, 'Bits/s')
      const curTab = await getDefaultCurTab(tableType, metric, columnName)
      this.$store.getters.menuList.forEach(menu => {
        if (!this.$_.isEmpty(menu.children)) {
          menu.children.forEach(child => {
            if (this.$route.path === child.route) {
              if (columnValue) { // 点击的为值
                child.columnValue = columnValue
                child.columnName = columnName
                this.urlChangeParams[this.curTabState.thirdMenu] = columnName
                this.urlChangeParams[this.curTabState.fourthMenu] = columnValue
                this.urlChangeParams[this.curTabState.panelName] = columnValue
              } else if (columnName) { // 点击的为列名
                child.columnValue = ''
                child.columnName = columnName
                this.urlChangeParams[this.curTabState.thirdMenu] = columnName
                this.urlChangeParams[this.curTabState.fourthMenu] = ''
                this.urlChangeParams[this.curTabState.panelName] = columnName
                if (curTab.thirdDimensionQueryCondition) {
                  this.urlChangeParams[this.curTabState.thirdDimensionQueryCondition] = curTab.thirdDimensionQueryCondition.join(' OR ')
                }
                if (curTab.lineThirdDimensionQueryCondition) {
                  this.urlChangeParams[this.curTabState.lineThirdDimensionQueryCondition] = curTab.lineThirdDimensionQueryCondition.join(' OR ')
                }
                this.urlChangeParams[this.curTabState.curTab] = curTab.prop
                this.urlChangeParams[this.curTabState.dimensionType] = curTab ? curTab.prop : ''
                this.$_.omit(this.urlChangeParams, [this.curTabState.queryCondition, this.curTabState.networkOverviewBeforeTab, this.curTabState.lineQueryCondition])
              } else {
                child.columnName = ''
                child.columnValue = ''
                this.$_.omit(this.urlChangeParams, [this.curTabState.thirdPanel, this.curTabState.fourthPanel, this.curTabState.thirdMenu, this.curTabState.fourthMenu, this.curTabState.dimensionType, this.curTabState.panelName, this.curTabState.curTab, this.curTabState.queryCondition, this.curTabState.lineQueryCondition, this.curTabState.networkOverviewBeforeTab, this.curTabState.lineThirdDimensionQueryCondition, this.curTabState.thirdDimensionQueryCondition])
              }
            }
          })
        }
      })
      this.changeUrlTabState()
      if (opeType === 2 || opeType === 0) { // 二级菜单 或主菜单
        // 如果有四级菜单，则将四级菜单对应tab的checked设置为true:根据columnName和columnValue 或 url判断不准确
        if (menus[3]) {
          this.handleCurDrilldownTableConfig(this.breadcrumb[2], this.breadcrumb[3])
        }
        this.$router.push({
          path: route,
          query: {
            t: +new Date()
          }
        })
        return
      } else if (opeType === 3) {
        this.$router.push({
          query: {
            ...this.$route.query,
            fourthPanel: '',
            t: +new Date()
          }
        })
        return
      } else if (opeType !== 4) {
        this.$router.push({
          query: {
            ...this.$route.query,
            fourthPanel: '',
            thirdPanel: '',
            t: +new Date()
          }
        })
        return
      }
      if (route === this.route) {
        this.refresh()
        return
      }
      if (route) {
        this.$router.push({
          path: route,
          query: {
            t: +new Date()
          }
        })
      }
    },
    dropDownSearch () {
      this.curPageNum = 1
      this.initDropdownList()
    },
    refresh () {
      this.$emit('refresh')
    },
    refreshPanel (menu) {
      if (this.breadcrumb.length >= 4) {
        const breadList = this.breadcrumb.splice(3, this.breadcrumb.length - 3)
        this.breadcrumb = ref(breadList)
      }
    },
    scrollList () {
      const obj = document.getElementById('breadcrumbSelectDropdown')
      if (obj.scrollTop + obj.clientHeight === obj.scrollHeight) {
        this.initDropdownList()
      }
    }
  }
}
</script>
