'use strict'
import { util } from '../../util/util.js'
import { verify } from '../../util/verify.js'
import { khcToastr } from '../alert/khcToastr.js'
import { config } from '../../config.js'
import { fullMap } from '../../fullMap.js'
import { httpUtil } from '../../util/httpUtil.js'
import { table } from '../page/query/table/table.js'

class menuBigModel {
  constructor(data) {
    this.data = data.menuList
    this.showMenuStyleConfig1 = config.getConfigJson().showMenuStyleConfig1
    this.showMenuStyleConfig2 = config.getConfigJson().showMenuStyleConfig2
    this.showMenuStyleConfig3 = config.getConfigJson().showMenuStyleConfig3
    this.codeArray = []

    // =================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================
    this.isCollapsed = true
    this.activeFirstMenuItem = null
    this.hiddenSidenav = []
    this.isMenuEvent = false
  }
  render() {
    let that = this
    return new Promise((resolve, reject) => {
      this.showMenuIconLevel = that.data[0].menu_level
      let menuHtml = that.getFirstMenuHtml(that.data)
      let secondMenuHtml = that.getSecondMenuHtml(that.data)
      this.hiddenSidenav = that.data.filter(item => !item.menu_child.length && item.menu_page).map(item => item.menu_page)
      document.getElementById('showMenu').innerHTML = ''
      document.getElementById('showMenu').insertAdjacentHTML('beforeEnd', menuHtml)

      document.getElementById('showSecondMenu').innerHTML = ''
      document.getElementById('showSecondMenu').insertAdjacentHTML('beforeEnd', secondMenuHtml)
      //给系统名称左侧的图标添加事件点击隐藏左侧菜单，再次点击则展示
      that.setupEventDelegation()
      that.initActiveMenu(that.data)
      that.showSecondMenu(that.data[0].menu_page)

      that.setDisabled(3000) //禁用菜单，并在三秒后解除禁用
      resolve()
    })
  }

  getFirstMenuHtml(menuList) {
    let that = this
    const htmlItems = []
    for (let i = 0; i < menuList.length; i++) {
      if (menuList[i].menu_level === '2') {
        let iconHtml = ''
        if (menuList[i].menu_icon && menuList[i].menu_icon.length > 0) {
          iconHtml = `<i class="left-menu-icon ${menuList[i].menu_icon}"></i>`
        }
        htmlItems.push(`
                    <li class="sidenav-menu-item" data-menu-id="${
                      menuList[i].menu_id
                    }" ${that.getDefaultPageCode(menuList[i])}}>
                        ${iconHtml}
                        <span>${menuList[i].menu_name}</span>
                        <div class="pl-1 ml-auto" id="${menuList[i].uuid}"></div>
                    </li>
        `)
      }
    }
    return htmlItems.join('')
  }

  /**
   * 获取默认页面编码,处理一级菜单默认选中菜单项code
   *
   * @param item 菜单项
   * @returns 返回默认页面编码
   */
  getDefaultPageCode(item) {
    if (item.menu_child && item.menu_child.length > 0) {
      const firstChild = item.menu_child[0]
      return firstChild.menu_page
        ? `data-default-code="${firstChild.menu_page}"`
        : this.getDefaultPageCode(firstChild)
    }
    return `data-default-code="${item.menu_page || ''}"`
  }

  /**
   * 获取二级菜单的HTML代码
   *
   * @param menuList 菜单列表
   * @param level 菜单层级，默认为1
   * @returns 返回生成的HTML字符串
   */
  getSecondMenuHtml(menuList, level = 1) {
    let htmlItems = ''
    menuList.forEach(item => {
      let currentLevel = level
      let iconHtml = ''
      if (item.menu_icon && item.menu_icon.length > 0) {
        iconHtml = `<i class="left-menu-icon ${item.menu_icon}"></i>`
      }
      if (item.menu_level === this.showMenuIconLevel) {
        htmlItems += `
            ${this.getSecondMenuHtml(item.menu_child, currentLevel + 1)}
        `
      } else if (item.menu_level !== '2' && item.menu_child.length > 0) {
        htmlItems += `
        <li class="sidenav-submenu" data-level="${currentLevel}" data-parent-id="${
          item.menu_parent_id
        }">
        <div class="sidenav-submenu__title">
          ${iconHtml}
          <span>${item.menu_name}</span>
          <i class="submenu-toggle-icon"></i>
          <div class="pl-1 ml-auto" id="${item.uuid}"></div>
        </div>
        <ul class="nav-menu sidenav-menu--inline">
        ${this.getSecondMenuHtml(item.menu_child, currentLevel + 1)}
        </ul>
        </li>
        `
      } else {
        this.codeArray.push(item.menu_page)
        htmlItems += `
        <li class="sidenav-menu-item submenu-title-noDropdow" data-code="${item.menu_page}" data-parent-id="${item.menu_parent_id}" data-level="${currentLevel}">
          ${iconHtml}
          <span>${item.menu_name}</span></span>
          <div class="pl-1 ml-auto" id="${item.uuid}"></div>
        </li>`
      }
    })
    return htmlItems
  }

  setupEventDelegation() {
    let that = this
    that.expandMenu()
    document.getElementById('menuIcon').addEventListener('click', () => that.toggleSidebar())
    document
      .getElementById('showMenu')
      .querySelectorAll('.sidenav-menu-item')
      .forEach(function (item, index) {
        item.addEventListener('click', () => that.handleFirstItemClick(item))
      })
    document.getElementById('sidebar-logo').addEventListener('click', () => {
      that.jumpPageByCode('page_home')
    })
  }

  /**
   * 切换侧边栏显示与隐藏状态
   */

  toggleSidebar() {
    document
      .querySelector('.main-container')
      .classList.toggle('hide-main-container', this.isCollapsed)
    document
      .querySelector('.second-sidebar')
      .classList.toggle('hide-sidebar-container', this.isCollapsed)
    this.isCollapsed = !this.isCollapsed
  }

  /**
   * 处理一级菜单的点击事件
   */
  handleFirstItemClick(e, code) {
    let that = this
    that.isMenuEvent = true
    if (!that.isCollapsed) {
      that.toggleSidebar()
    }

    !that.isCollapsed && that.firstMenuItemActive(e)
    that.firstMenuItemActive(e)
    const menuId = e.getAttribute('data-menu-id')
    let defaultcode = e.getAttribute('data-default-code')

    if (!util.isNull(menuId)) {
      that.showSecondMenu(menuId)
      that.open(defaultcode)
    }
    if (that.hiddenSidenav.some(item => item === defaultcode)) {
      that.jumpPageByCode(defaultcode)
    }
  }

  firstMenuItemActive(e) {
    let that = this
    if (that.activeMenuItem) {
      that.activeMenuItem.classList.remove('is-active')
    }
    e.classList.add('is-active')
    that.activeMenuItem = e
  }

  open(code,isOpenUrl) {
    let that = this
    let menuItem = document.querySelector(`[data-code="${code}"]`)
    if (menuItem) {
      // 展开上级菜单
      let submenuMenu = menuItem.closest('.sidenav-submenu')
      submenuMenu && that.toggleMenu(submenuMenu, true)
      that.jumpPage(menuItem, code,isOpenUrl)
    }
  }

  /**
   * 点击二级菜单项
   *
   * @param menu_page 菜单页码
   */
  secondMenuItemClick(menu_page) {
    let that = this
    let menuEleObj = document.querySelector(`[data-code="${menu_page}"]`)
    menuEleObj.addEventListener('click', function () {
      that.jumpPage(menuEleObj, menu_page)
    })
  }

  jumpPage(menuEleObj, menu_page,isOpenUrl) {
    let that = this
    that.isMenuEvent = true
    if (menuEleObj.className.includes('disabled')) {
      khcToastr.showErrorMessage({ msg: '操作频繁' })
      return
    }
    // window.location.href = '#' + menu_page
    if(util.isNull(isOpenUrl)||isOpenUrl){
      that.jumpPageByCode(menu_page)
    }
    that.handleClickMenuItem(menu_page)
  }

  jumpPageByCode(page_code) {
    window.location.href = config.getIndexUrl()+'#' + page_code
  }

  /**
   * 展开菜单
   */
  expandMenu() {
    let that = this
    document.querySelectorAll('.sidenav-submenu').forEach(submenu => {
      submenu
        .querySelector('.sidenav-submenu__title')
        .addEventListener('click', () => that.toggleMenu(submenu))
    })
  }

  /**
   * 显示对应下级菜单
   *
   * @param menuId 菜单ID
   */
  showSecondMenu(menuId) {
    // 显示对应下级菜单
    document
      .getElementById('showSecondMenu')
      .querySelectorAll('.sidenav-menu-item[data-level="2"], .sidenav-submenu[data-level="2"]')
      .forEach(menu => {
        menu.style.display = menu.getAttribute('data-parent-id') === menuId ? 'block' : 'none'
      })
  }

  /**
   * 更新菜单高度
   *
   * @param menu 菜单元素
   * @param expand 是否展开
   * @returns 返回高度差值
   */
  updateHeight(menu, expand) {
    let that = this
    if (!menu) return 0
    let totalHeight = 0
    if (expand) {
      menu.style.height = ''
      totalHeight = menu.scrollHeight
      menu.style.height = '0'
      setTimeout(() => (menu.style.height = totalHeight + 'px'), 10)
    } else {
      totalHeight = -menu.scrollHeight
      menu.style.height = '0'
    }

    return totalHeight
  }
  /**
   *
   * @param {*} 展开菜单动态更新高度
   */
  toggleMenu(submenu, isHashTriggered) {
    let isExpanding = !submenu.classList.contains('is-opened')
    if (isHashTriggered && !isExpanding) {
      // 如果是通过监听hash触发且本身已打开，则不执行后续操作
      return
    }
    let that = this
    submenu.querySelector('.submenu-toggle-icon').classList.toggle('collapsed')

    submenu.classList.toggle('is-opened')
    setTimeout(() => {
      let heightChange = that.updateHeight(submenu.querySelector('.nav-menu'), isExpanding)
      // 递归更新所有父菜单的高度
      let parentMenu = submenu.closest('.nav-menu')
      while (parentMenu) {
        parentMenu.style.height = `${parseInt(parentMenu.style.height) + heightChange}px`
        parentMenu = parentMenu.parentNode.closest('.nav-menu')
      }
    }, 20)
  }

  //初始化绑定选中左侧菜单事件
  initActiveMenu(menuList) {
    let that = this
    for (let i = 0; i < menuList.length; i++) {
      if (menuList[i].is_show_num == 'Y') {
        //查询菜单num数量提示
        if (menuList[i].show_num_data_type == '1') {
          //todo 这里后续有时间调整一下，代码冗余了
          let mJson = JSON.parse(menuList[i].m_json)
          let backgroundColor = util.getColorByName(menuList[i].show_num_color)
          let title = ''
          if (!util.isNull(menuList[i].show_num_template)) {
            title = menuList[i].show_num_template.replace('${data}', mJson.data)
          } else {
            title = mJson.data
          }
          let html = `<div class="badge badge-primary" style="background-color: ${backgroundColor};" title="${title}">${mJson.data}</div>`
          document.getElementById(menuList[i].uuid).innerHTML = html
        }
        if (menuList[i].show_num_data_type == '3') {
          let params = {
            version: '1.0.0',
            dsCode: 'ds_system_menu',
            queryCode: 'query_menu',
            methodName: 'getMenuShowNum'
          }
          params.uuid = menuList[i].uuid
          let obj = { url: config.getConfigJson().myActionUrl, params: params }
          httpUtil.post(obj, response => {
            let menuInfo = response.data.data.menuInfo
            //${menuList[i].menu_page=='page_project'?`<div class="badge badge-primary" style="background-color: #d9534f;" title="59">59</div>`:''}
            if (!util.isNull(menuInfo.data) && menuInfo.data != 0) {
              let backgroundColor = util.getColorByName(menuInfo.show_num_color)
              let title = ''
              if (!util.isNull(menuInfo.show_num_template)) {
                title = menuInfo.show_num_template.replace('${data}', menuInfo.data)
              } else {
                title = menuInfo.data
              }
              let html = `<div class="badge badge-primary" style="background-color: ${backgroundColor};" title="${title}">${menuInfo.data}</div>`
              document.getElementById(menuInfo.uuid).innerHTML = html
            }
          })
        }
      }
      if (menuList[i].menu_child.length > 0) {
        this.initActiveMenu(menuList[i].menu_child)
      } else if (
        !util.isNull(menuList[i].menu_page) &&
        menuList[i].menu_level !== that.showMenuIconLevel
      ) {
        //绑定单击事件
        that.secondMenuItemClick(menuList[i].menu_page)
      }
    }
  }

  /**
   * 通过code设置当前活动菜单
   *
   * @param code 菜单的code
   */
  handleClickMenuItem(code) {
    let that = this
    let eleObj = document.querySelector(`[data-code="${code}"]`)
    if (eleObj == null || eleObj.className.includes('disabled')) {
      return
    }
    if (eleObj != null) {
      that.removeActiveMenu()
      //将当前菜单设置为选中
      eleObj.classList.add('is-active')
    }
  }

  /**
   * 通过code设置当前激活的菜单,实现code反选菜单
   *
   * @param code 菜单的code值  TODO
   */
  setActiveMenuByCode(code,isOpenUrl) {
    let that = this
    if (that.hiddenSidenav.some(item => item === code)) {
      let firstMenuItem = document.querySelector(`[data-default-code="${code}"]`)
      that.firstMenuItemActive(firstMenuItem)
      that.toggleSidebar()
    }
    if (!that.isMenuEvent) {
      let menuItem = document.querySelector(`[data-code="${code}"]`)
      if (!util.isNull(menuItem)) {
        //   // 展开上级菜单
        let submenuMenu = menuItem.closest('.sidenav-submenu')
        let parentMenuCode = submenuMenu
          ? submenuMenu.getAttribute('data-parent-id')
          : menuItem.getAttribute('data-parent-id')
        let firstMenuItem = document.querySelector(`[data-menu-id="${parentMenuCode}"]`)
        that.firstMenuItemActive(firstMenuItem)
        that.showSecondMenu(parentMenuCode)
        that.open(code,isOpenUrl)
      }
    }
    that.isMenuEvent = false
  }

  //清空选中
  removeActiveMenu() {
    let that = this
    for (let j = 0; j < that.codeArray.length; j++) {
      let eleObj = document.querySelector(`[data-code="${that.codeArray[j]}"]`)
      if (eleObj != null) {
        for (let k = 0; k < eleObj.classList.length; k++) {
          if (eleObj.classList[k] == 'is-active') {
            eleObj.classList.remove('is-active')
          }
        }
      }
    }
  }
  //立即禁用，removeTimeout是什么时间后关闭禁用
  setDisabled(removeTimeout) {
    let that = this
    /*let menuLi=document.getElementById('showMenu').querySelectorAll('li')
            for (let i = 0; i < menuLi.length; i++) {
                let liEle=menuLi[i];
                liEle.classList.add('disabled');
            }*/
    if (!util.isNull(removeTimeout)) {
      setTimeout(() => {
        that.removeDisabled()
      }, removeTimeout)
    }
  }

  /**
   * @param timeout 延迟时间
   */
  removeDisabled(timeout) {
    if (util.isNull(timeout)) {
      timeout = 0
    }
    setTimeout(() => {
      let menuLi = document.getElementById('showMenu').querySelectorAll('li')
      for (let i = 0; i < menuLi.length; i++) {
        let liEle = menuLi[i]
        liEle.classList.remove('disabled')
      }
    }, timeout)
  }
}

export { menuBigModel }
