import axios from '@/common/services/axios-instance'
import qs from 'qs'
class NavMenuService {
  urlMap = {}
  urlTitleMap = {}
  waitForRequest = undefined
  count = 0
  workBench = { props: { workbench: '-999' } } // 显示的工作台
  processMenu(subMenu, parent) {
    subMenu.menuId = subMenu.id // 将真实id赋给menuId,快捷导航配置使用
    subMenu.id = subMenu.url ? subMenu.url + (subMenu.srcTrustId || '') : `submenu${this.count++}`
    subMenu.title = subMenu.text
    subMenu.scopedSlots = { title: 'title' }
    if (subMenu.target !== '_blank' && subMenu.url?.startsWith('http')) {
      // 非新窗口的绝对地址iframe里打开
      subMenu.url = `/sd-frame/sd-iframe/${encodeURIComponent(
        subMenu.url
      )}?title=${encodeURIComponent(subMenu.title)}`
    }
    if (subMenu.props.workbench) {
      if (parseInt(subMenu.props.workbench) > parseInt(this.workBench.props.workbench)) {
        this.workBench = subMenu
      } else {
        subMenu.disabled = true
      }
    }
    if (subMenu.url && !this.urlMap[subMenu.url] && parent.length && !subMenu.disabled) {
      this.urlMap[subMenu.url] = parent
      this.urlTitleMap[subMenu.url] = subMenu.title
    }

    subMenu.children?.forEach((sub) => this.processMenu(sub, [...parent, subMenu.id]))
  }

  getWorkBench() {
    return this.workBench
  }

  // 生成每个url所在的分类信息
  generateMap(menu) {
    this.count = 0
    this.urlMap = {}
    this.urlTitleMap = {}
    this.workBench = { props: { workbench: '-999' }, url: 'sd-frame/iam-content' } // 显示的工作台
    menu.forEach((sub) => this.processMenu(sub, []))
    menu.forEach((sub) => {
      let i = sub.children.findIndex((item) => item.disabled)
      while (i > 0) {
        sub.children.splice(i, 1)
        i = sub.children.findIndex((item) => item.disabled)
      }
    })
  }

  fetch() {
    // 有导航菜单分组code时，获取对应分组的导航菜单
    const menuGroupCode = qs
      .parse(window.location.search?.replace('?', ''))
      .menuGroupCode?.toString()
    const params = menuGroupCode ? '?menuGroupCode=' + encodeURIComponent(menuGroupCode) : ''
    const req = axios.get(`api/framework/v1/menu/auth-menu-trees${params}`).then((res) => {
      // 合并兼职的
      const menu = res.data.menuTreeNodes
      const mergeTrust = (menu) => {
        if (menu.length === 0) return
        if (menu.length === 1) {
          if (menu[0].mergeTrust) return
          mergeTrust(menu[0].children)
          return
        }
        if (menu.length > 1) {
          // 取id并去重
          const ids = [...new Set(menu.map((item) => item.id))]
          ids.forEach((id) => {
            // 找出有多个的合并到第一个的children里,并记录序号,再删除其他的
            const indexs = []
            let trustMenus = menu.filter((item, index) => {
              if (item.id === id) {
                indexs.push(index)
                return true
              }
            })
            if (trustMenus.length > 1) {
              trustMenus = JSON.parse(JSON.stringify(trustMenus))
              trustMenus.forEach((item) => (item.text = JSON.parse(item.props.groupPath).join('/')))
              menu[indexs[0]].trustMenus = trustMenus // 多个合并到第一个里
              menu[indexs[0]].mergeTrust = true // 合并生成的导航，不要再递归了
              indexs.shift() // 去除第一个并反转，按序号从大往小去掉已经合并的元素
              indexs.reverse()
              indexs.forEach((index) => menu.splice(index, 1))
            }
          })
        }
        menu.forEach((item) => {
          mergeTrust(item.children)
        })
      }
      mergeTrust(menu)
      this.generateMap(menu)
      return res.data
    })
    this.waitForRequest = req
    return req
  }

  getSelectedItem(url) {
    let data = this.urlMap[url]
    if (!data) {
      for (const key in this.urlMap) {
        if (url.startsWith(key)) {
          data = this.urlMap[key]
          url = key
          break
        }
      }
    }
    const [topCate, cate = undefined] = data || [] // 兼容cate不存在的情况
    return [topCate, cate, url]
  }

  getNavTitleByUrl(url) {
    // 等待导航请求返回后，再取title信息
    return Promise.resolve(this.waitForRequest).then(() => {
      const title = this.urlTitleMap[url]
      if (typeof title !== 'undefined') {
        return title
      } else {
        return Promise.reject(new Error('not found'))
      }
    })
  }

  // 流程
  getFlowsList(params) {
    return axios({
      url: `api/framework/v1/flow-manage/flows/list`,
      method: 'get',
      params,
    })
  }

  // 获取普通用户导航菜单
  getUserMenus() {
    return axios({
      url: 'api/framework/v1/menu/menu-trees/user',
      method: 'get',
    }).then((res) => {
      this.generateMap(res.data)
      return res.data
    })
  }

  // 快捷入口列表
  getQuickEnterList() {
    return axios({
      url: 'api/framework/v1/newflow/quickEnterBusinessType',
      method: 'get',
    })
  }

  // 全部入口列表
  getFirstCategoryBusinessType() {
    return axios({
      url: 'api/framework/v1/newflow/auth-businesstypes',
      method: 'get',
    })
  }

  // 获取当前用户快捷导航列表
  getQuickMenus() {
    return axios({
      url: 'api/framework/v1/personal-quick-menu/quickmenus/myquickmenus',
      method: 'get',
    }).then((res) => {
      return res.data
    })
  }

  // 批量新增快捷导航配置
  quickMenusBatchCreate(params) {
    return axios({
      url: 'api/framework/v1/personal-quick-menu/quickmenus/batchcreate',
      method: 'post',
      data: params,
    }).then((res) => {
      return res.data
    })
  }

  // 系统管理员快捷导航设置
  adminQuickMenusBatchCreate(params) {
    return axios({
      url: 'api/framework/v1/persnal-sys-quick-menu/sysquickmenus/batchcreate',
      method: 'post',
      data: params,
    }).then((res) => {
      return res.data
    })
  }

  // 快捷导航选择列表
  getQuickList(params) {
    return axios({
      url: 'api/framework/v1/page/businessList',
      method: 'post',
      data: params,
    }).then((res) => {
      return res.data
    })
  }

  // 系统快捷导航详情
  getSysQuickDetail(params) {
    return axios({
      url: 'api/framework/v1/page/wp/personal/quickmenu/oaPersonalSysQuickMenu',
      method: 'get',
      params,
    })
  }

  // 普通快捷导航详情
  getQuickDetail(params) {
    return axios({
      url: 'api/framework/v1/page/wp/personal/quickmenu/oaPersonalQuickMenu',
      method: 'get',
      params,
    })
  }

  // 保存图标/编辑保存单条记录
  saveItem(params) {
    return axios({
      url: 'api/framework/v1/page/handleData',
      method: 'post',
      data: params,
    })
  }

  // 获取催办提醒、到期提醒、系统提醒数,供frame-header判断小铃铛是否显示红点用
  getRemindCount(type) {
    return axios({
      url: 'api/framework/v1/person/messages/type-message-num',
      method: 'post',
      data: {
        type,
      },
    })
  }

  recordMenuClick(params) {
    return axios({
      url: 'api/xcoa-mobile/v1/operation-log/record-log',
      method: 'get',
      params,
    })
  }
}

export default new NavMenuService()
